content
stringlengths 5
1.05M
|
---|
----Duel Arena-------------------------------------------------OF SOULSSS--xS productions-----------------
me = game.Players.xSoulStealerx
mainpos = Vector3.new(200,0,30)
function prop(part, parent, collide, tran, ref, x, y, z, color, anchor, form)
part.Parent = parent
part.formFactor = form
part.CanCollide = collide
part.Transparency = tran
part.Reflectance = ref
part.Size = Vector3.new(x,y,z)
part.BrickColor = BrickColor.new(color)
part.TopSurface = 0
part.BottomSurface = 0
part.Anchored = anchor
part.Locked = true
part:BreakJoints()
end
mod = Instance.new("Model",workspace)
mod.Name = "Duel arena by xSoul"
for i=0,math.pi, math.pi/3 do
local p = Instance.new("Part")
prop(p,mod,true,0,0,100,7,170,"Brick yellow",true,"Custom")
p.CFrame = CFrame.new(mainpos) * CFrame.Angles(0,i,0)
local k = Instance.new("Part")
prop(k,mod,true,0,0,30,40,30,"Brown",true,"Custom")
k.CFrame = p.CFrame * CFrame.new(p.Size.Z/2,k.Size.Y/2,0)
local f = Instance.new("Part")
prop(f,mod,true,0,0,30,40,30,"Brown",true,"Custom")
f.CFrame = p.CFrame * CFrame.new(-p.Size.Z/2,f.Size.Y/2,0)
local p = Instance.new("Part")
prop(p,mod,true,0,0,120,20,200,"Brick yellow",true,"Custom")
p.CFrame = CFrame.new(mainpos) * CFrame.Angles(0,i,0) * CFrame.new(0,k.Size.Y,0)
end
for i=0,math.pi*2,math.pi/30 do
local p = Instance.new("Part")
prop(p,mod,true,0,0,4,7,10,"Brown",true,"Custom")
p.CFrame = CFrame.new(mainpos) * CFrame.Angles(0,i,0) * CFrame.new(60,7,0)
end
|
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("High Botanist Freywinn", 553, 559)
if not mod then return end
mod:RegisterEnableMob(17975)
mod.engageId = 1926
-- mod.respawnTime = 0 -- resets, doesn't respawn
--------------------------------------------------------------------------------
-- Locals
--
local addsAlive = 0
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
34550, -- Tranquility
34752, -- Freezing Touch
}, {
[34550] = "general",
[34752] = -5453, -- White Seedling
}
end
function mod:OnBossEnable()
self:Log("SPELL_AURA_APPLIED", "Tranquility", 34551) -- 34551 = "Tree Form", the buff he applies to himself while channeling Tranquility. He applies 34550 to every unit being healed.
self:Log("SPELL_AURA_REMOVED", "TranquilityOver", 34551)
self:Log("SPELL_CAST_SUCCESS", "SummonFrayerProtectors", 34557)
self:Death("AddDeath", 19953)
self:Log("SPELL_AURA_APPLIED", "FreezingTouch", 34752)
self:Log("SPELL_AURA_REMOVED", "FreezingTouchRemoved", 34752)
end
function mod:OnEngage()
addsAlive = 0
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:Tranquility()
self:Message(34550, "red", "Long", CL.casting:format(self:SpellName(34550)))
self:CastBar(34550, 45)
end
function mod:TranquilityOver()
self:Message(34550, "green", nil, CL.over:format(self:SpellName(34550)))
self:StopBar(CL.cast:format(self:SpellName(34550)))
end
function mod:SummonFrayerProtectors()
addsAlive = addsAlive + 3
end
function mod:AddDeath()
addsAlive = addsAlive - 1
self:Message(34550, "green", "Info", CL.add_remaining:format(addsAlive))
end
function mod:FreezingTouch(args)
self:TargetMessage(args.spellId, args.destName, "orange", "Alarm", nil, nil, self:Dispeller("magic"))
self:TargetBar(args.spellId, 3, args.destName)
end
function mod:FreezingTouchRemoved(args)
self:StopBar(args.spellName, args.destName)
end
|
local ColliderGroup, super = Class(Collider)
function ColliderGroup:init(parent, colliders, mode)
super:init(self, parent, 0, 0, mode)
self.colliders = colliders or {}
for _,collider in ipairs(self.colliders) do
collider.parent = collider.parent or self.parent
end
end
function ColliderGroup:addCollider(collider)
collider.parent = collider.parent or self.parent
table.insert(self.colliders, collider)
end
function ColliderGroup:collidesWith(other)
other = self:getOtherCollider(other)
if not self:collidableCheck(other) then return false end
for _,collider in ipairs(self.colliders) do
if collider:collidesWith(other) then
return self:applyInvert(other, true)
end
end
return super:collidesWith(self, other)
end
function ColliderGroup:drawFor(obj,r,g,b,a)
for _,collider in ipairs(self.colliders) do
collider:drawFor(obj,r,g,b,a)
end
end
function ColliderGroup:drawFillFor(obj,r,g,b,a)
for _,collider in ipairs(self.colliders) do
collider:drawFillFor(obj,r,g,b,a)
end
end
function ColliderGroup:draw(r,g,b,a)
for _,collider in ipairs(self.colliders) do
collider:draw(r,g,b,a)
end
end
function ColliderGroup:drawFill(r,g,b,a)
for _,collider in ipairs(self.colliders) do
collider:drawFill(r,g,b,a)
end
end
return ColliderGroup |
local helpers = require "spec.helpers"
local PLUGIN_NAME = "olaplugin"
for _, strategy in helpers.each_strategy() do
describe(PLUGIN_NAME .. ": (access) [#" .. strategy .. "]", function()
local client
lazy_setup(function()
local bp = helpers.get_db_utils(strategy, nil, { PLUGIN_NAME })
-- Inject a test route. No need to create a service, there is a default
-- service which will echo the request.
local route1 = bp.routes:insert({
hosts = { "test1.com" },
})
-- add the plugin to test to the route we created
bp.plugins:insert {
name = PLUGIN_NAME,
route = { id = route1.id },
config = {},
}
-- start kong
assert(helpers.start_kong({
-- set the strategy
database = strategy,
-- use the custom test template to create a local mock server
nginx_conf = "spec/fixtures/custom_nginx.template",
-- make sure our plugin gets loaded
plugins = "bundled," .. PLUGIN_NAME,
}))
end)
lazy_teardown(function()
helpers.stop_kong(nil, true)
end)
before_each(function()
client = helpers.proxy_client()
end)
after_each(function()
if client then client:close() end
end)
describe("request", function()
it("gets a 'hello-world' header", function()
local r = client:get("/request", {
headers = {
host = "test1.com"
}
})
-- validate that the request succeeded, response status 200
assert.response(r).has.status(200)
-- now check the request (as echoed by mockbin) to have the header
local header_value = assert.request(r).has.header("hello-world")
-- validate the value of that header
assert.equal("this is on a request", header_value)
end)
end)
describe("response", function()
it("gets a 'bye-world' header", function()
local r = client:get("/request", {
headers = {
host = "test1.com"
}
})
-- validate that the request succeeded, response status 200
assert.response(r).has.status(200)
-- now check the response to have the header
local header_value = assert.response(r).has.header("bye-world")
-- validate the value of that header
assert.equal("this is on the response", header_value)
end)
end)
end)
end
|
--サイバネット・バックドア
--Cybnet Backdoor
--Scripted by Eerie Code
function c43839002.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_REMOVE+CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,43839002+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(c43839002.target)
e1:SetOperation(c43839002.activate)
c:RegisterEffect(e1)
end
function c43839002.rmfilter(c,tp)
return c:IsFaceup() and c:IsRace(RACE_CYBERS) and c:IsAbleToRemove() and c:GetBaseAttack()>0
and Duel.IsExistingMatchingCard(c43839002.thfilter,tp,LOCATION_DECK,0,1,nil,c)
end
function c43839002.thfilter(c,rc)
return c:IsRace(RACE_CYBERS) and c:GetAttack()<rc:GetBaseAttack() and c:IsAbleToHand()
end
function c43839002.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c43839002.rmfilter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(c43839002.rmfilter,tp,LOCATION_MZONE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c43839002.rmfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c43839002.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Remove(tc,POS_FACEUP,REASON_EFFECT+REASON_TEMPORARY)>0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetReset(RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN)
e1:SetLabelObject(tc)
e1:SetCountLimit(1)
e1:SetCondition(c43839002.retcon)
e1:SetOperation(c43839002.retop)
Duel.RegisterEffect(e1,tp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c43839002.thfilter,tp,LOCATION_DECK,0,1,1,nil,tc)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
end
function c43839002.retcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c43839002.retop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if Duel.ReturnToField(tc) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetDescription(aux.Stringid(43839002,0))
e1:SetProperty(EFFECT_FLAG_CLIENT_HINT)
e1:SetCode(EFFECT_DIRECT_ATTACK)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
|
--
package.path = "../?.lua;" .. package.path
require 'busted.runner'()
require 'init'
--
describe('Lang Functions', function()
describe('_:is_(var)', function()
it('should return true if `var` is native Lander property, otherwise false', function()
assert.are.equals(_:is_(123), false)
assert.are.equals(_:is_('fakeFunction'), false)
assert.are.equals(_:is_('istruthy'), false)
assert.are.equals(_:is_(function(v) return _:isTruthy(v) end), false)
assert.are.equals(_:is_(_.isTruthy), false)
assert.are.equals(_:is_('isTruthy'), true)
end)
end)
describe('_:isArray(var)', function()
it('should return true if `var` is an array, otherwise false', function()
assert.are.equals(_:isArray({}), true)
assert.are.equals(_:isArray({a = 1, 2, 'c'}), false)
assert.are.equals(_:isArray({a = 1, b = 2}), false)
assert.are.equals(_:isArray({false, true}), true)
assert.are.equals(_:isArray({1, 'b', 'c', 4}), true)
end)
end)
describe('_:isBoolean(var)', function()
it('should return true if `var` is not a boolean value, otherwise false', function()
assert.are.equals(_:isBoolean('true'), false)
assert.are.equals(_:isBoolean(true), true)
end)
end)
describe('_:isEmpty(var)', function()
it('should return true if `var` is an empty value, otherwise false', function()
assert.are.equals(_:isEmpty(''), true)
assert.are.equals(_:isEmpty('abc'), false)
assert.are.equals(_:isEmpty(false), true)
assert.are.equals(_:isEmpty(true), false)
assert.are.equals(_:isEmpty(0), true)
assert.are.equals(_:isEmpty(1), false)
assert.are.equals(_:isEmpty({}), true)
assert.are.equals(_:isEmpty({1, 2, 3}), false)
assert.are.equals(_:isEmpty(nil), true)
end)
end)
describe('_:isEqual(var1, var2)', function()
it('should return true if `var1` == `var2`, otherwise false', function()
-- boolean
assert.is_true(_:isEqual(true, true))
assert.is_false(_:isEqual(true, false))
-- number
assert.is_true(_:isEqual(1, 1))
assert.is_false(_:isEqual(1, 2))
-- string
assert.is_true(_:isEqual('foo', 'foo'))
assert.is_false(_:isEqual('foo', 'bar'))
-- table, simple
assert.is_true(_:isEqual({'a', 'b', 'c'}, {'a', 'b', 'c'}))
assert.is_false(_:isEqual({'a', 'b', 'c'}, {'a', 'c', 'b'}))
-- table, simple, unordered named keys
assert.is_true(_:isEqual({a = 1, b = 5, c = 3}, {c = 3, b = 5, a = 1}))
assert.is_false(_:isEqual({a = 1, b = 5, c = 3}, {c = 6, b = 10, a = 2}))
-- table, complex
local co = coroutine.create(function(v) return v end)
local func = (function(v) return v * 2 end)
local t1 = {
a = {1, 2, 3},
b = false,
c = {
a = { co, func },
'hello world!'
}
}
local t2 = {
a = {3, 2, 1},
c = true,
b = {
a = { co, func },
'goodbye world!'
}
}
assert.is_true(_:isEqual(t1, t1))
assert.is_true(_:isEqual(t1['c']['a'], t2['b']['a']))
assert.is_false(_:isEqual(t1, t2))
assert.is_false(_:isEqual(t1['c'], t2['b']))
end)
end)
describe('_:isEven(var)', function()
it('should return true if `var` is an even number, otherwise false', function()
assert.is_false(_:isEven(-1))
assert.is_false(_:isEven(147))
assert.is_false(_:isEven('abc'))
assert.is_true(_:isEven(0))
assert.is_true(_:isEven(168))
end)
end)
describe('_:isFalsey(var)', function()
it('should return true if `var` is falsey, otherwise false', function()
assert.are.equals(_:isFalsey(nil), true)
assert.are.equals(_:isFalsey(false), true)
assert.are.equals(_:isFalsey('abc'), false)
assert.are.equals(_:isFalsey(42), false)
assert.are.equals(_:isFalsey(function() end), false)
end)
end)
describe('_:isFunction(var)', function()
it('should return true if `var` is not a function, otherwise false', function()
assert.are.equals(_:isFunction(function() return 'Hello World!' end), true)
assert.are.equals(_:isFunction('Hello World!'), false)
assert.are.equals(_:isFunction('isEqual'), true)
assert.are.equals(_:isFunction('madeUpFunction'), false)
assert.are.equals(_:isFunction(function(v, k) return v end), true)
assert.are.equals(_:isFunction('abc'), false)
end)
end)
describe('_:isNaN(var)', function()
it('should return true if `var` is not a number, otherwise false', function()
assert.are.equals(_:isNaN('123'), true)
assert.are.equals(_:isNaN(123), false)
end)
end)
describe('_:isNegative(var)', function()
it('should return true if `var` is a negative number, otherwise false', function()
assert.are.equals(_:isNegative('abc'), false)
assert.are.equals(_:isNegative(-2), true)
assert.are.equals(_:isNegative(3), false)
end)
end)
describe('_:isNil(var)', function()
it('should return true if `var` is nil, otherwise false', function()
assert.are.equals(_:isNil('abc'), false)
assert.are.equals(_:isNil(nil), true)
end)
end)
describe('_:isNotNil(var)', function()
it('should return true if `var` is not nil, otherwise false', function()
assert.are.equals(_:isNotNil('abc'), true)
assert.are.equals(_:isNotNil(nil), false)
end)
end)
describe('_:isNumber(var)', function()
it('should return true if `var` is a number, otherwise false', function()
assert.are.equals(_:isNumber('abc'), false)
assert.are.equals(_:isNumber(42), true)
end)
end)
describe('_:isOdd(var)', function()
it('should return true if `var` is an even number, otherwise false', function()
assert.is_false(_:isOdd(0))
assert.is_false(_:isOdd(168))
assert.is_false(_:isOdd('abc'))
assert.is_true(_:isOdd(-1))
assert.is_true(_:isOdd(147))
end)
end)
describe('_:isPositive(var)', function()
it('should return true if `var` is a positive number, otherwise false', function()
assert.are.equals(_:isPositive('abc'), false)
assert.are.equals(_:isPositive(-2), false)
assert.are.equals(_:isPositive(3), true)
end)
end)
describe('_:isRegexPattern(var)', function()
it('should return true if `var` is a regex pattern, otherwise false', function()
assert.are.equals(_:isRegexPattern('abc'), false)
assert.are.equals(_:isRegexPattern('^abc'), false)
assert.are.equals(_:isRegexPattern('[abc]'), true)
assert.are.equals(_:isRegexPattern('%a+'), true)
end)
end)
describe('_:isSequence(var)', function()
it('should return true if `var` is a sequence, otherwise false', function()
assert.are.equals(_:isSequence({}), true)
assert.are.equals(_:isSequence({1, 3, 5, 6, 7}), true)
assert.are.equals(_:isSequence({a = 1, b = 3, 4, 8}), false)
assert.are.equals(_:isSequence({1, 4, 2, 10, 6}), false)
end)
end)
describe('_:isSet(var)', function()
it('should return true if `var` is a set, otherwise false', function()
assert.are.equals(_:isSet({}), true)
assert.are.equals(_:isSet({3, 3, 5, 6, 6}), false)
assert.are.equals(_:isSet({a = 1, b = 3, c = 4, 5, 8}), false)
assert.are.equals(_:isSet({1, 4, 2, 10, 6}), true)
end)
end)
describe('_:isString(var)', function()
it('should return true if `var` is a string, otherwise false', function()
assert.are.equals(_:isString('abc'), true)
assert.are.equals(_:isString(42), false)
end)
end)
describe('_:isTable(var)', function()
it('should return true if `var` is a table, otherwise false', function()
assert.are.equals(_:isTable('abc'), false)
assert.are.equals(_:isTable({'a', 'b', 'c'}), true)
end)
end)
describe('_:isTruthy(var)', function()
it('should return true if `var` is truthy otherwise false', function()
assert.are.equals(_:isTruthy(nil), false)
assert.are.equals(_:isTruthy(false), false)
assert.are.equals(_:isTruthy('abc'), true)
assert.are.equals(_:isTruthy(42), true)
assert.are.equals(_:isTruthy(function() end), true)
end)
end)
describe('_:isThread(var)', function()
it('should return true if `var` is a thread, otherwise false', function()
assert.are.equals(_:isThread('I am a thread!'), false)
assert.are.equals(_:isThread(coroutine.create(function() end)), true)
end)
end)
end) |
local lgi = require 'lgi'
local Gtk = lgi.Gtk
local Gio = lgi.Gio
local Gdk = lgi.Gdk
local GLib = lgi.GLib
local app = Gtk.Application { application_id = 'org.lgi.notifications' }
function rgb_to_hex(rgb)
return string.format("#%02x%02x%02x",math.floor(rgb.red*255),math.floor(rgb.green*255),math.floor(rgb.blue*255))
end
function app:on_activate()
local fixed = Gtk.Fixed {}
fixed:put(Gtk.Button {
label = 'Notify',
on_clicked = function (_)
local notification = Gio.Notification.new('Example Notification')
notification:set_body('This is a notification.')
app:send_notification('norif-example',notification)
end
},5,5)
fixed:put(Gtk.ColorButton {
on_color_set = function (b)
local notification = Gio.Notification.new('Color Selected')
notification:set_body(rgb_to_hex(b.rgba))
app:send_notification('norif-example',notification)
end
},5,40)
local window = Gtk.Window {
width_request = 300,
height_request = 300,
title = 'Notifications',
application = self,
fixed
}
window:show_all()
end
-- function window:on_destroy()
-- Gtk.main_quit()
-- end
-- window:show_all()
-- Gtk:main()
app:run { arg[0], ... }
|
local restMoney = {}
local restXp = {}
addEvent("dpDriftPoints.earnedPoints", true)
addEventHandler("dpDriftPoints.earnedPoints", resourceRoot, function (points)
local driftMoney = exports.dpShared:getEconomicsProperty("drift_money") or 0
local driftXP = exports.dpShared:getEconomicsProperty("drift_xp") or 0
local money = points / 100000 * driftMoney
local xp = points / 100000 * driftXP
if not restMoney[client] then
restMoney[client] = 0
end
if not restXp[client] then
restXp[client] = 0
end
restMoney[client] = restMoney[client] + (money - math.floor(money))
restXp[client] = restXp[client] + (xp - math.floor(xp))
if restMoney[client] >= 1 then
money = money + 1
restMoney[client] = restMoney[client] - 1
end
if restXp[client] >= 1 then
xp = xp + 1
restXp[client] = restXp[client] - 1
end
exports.dpCore:givePlayerMoney(client, math.floor(money))
exports.dpCore:givePlayerXP(client, math.floor(xp))
end)
addEventHandler("onPlayerQuit", root,
function ()
if restMoney[source] then
restMoney[source] = nil
end
if restXp[source] then
restXp[source] = nil
end
end
)
|
--[[
Copyright 2020 Manticore Games, Inc.
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.
--]]
--[[
This script uses the specified hit sphere on ability to damage enemy players or damageable objects on ability execute phase.
]]
-- Internal custom properties
local EQUIPMENT = script:FindAncestorByType('Equipment')
if not EQUIPMENT:IsA('Equipment') then
error(script.name .. " should be part of Equipment object hierarchy.")
end
-- User exposed properties
local HIT_SPHERE_RADIUS = EQUIPMENT:GetCustomProperty("HitSphereRadius")
local HIT_SPHERE_OFFSET = EQUIPMENT:GetCustomProperty("HitSphereOffset")
local SHOW_HIT_SPHERE = EQUIPMENT:GetCustomProperty("ShowHitSphere")
-- Internal variables
local abilityList = {}
-- nil Tick()
-- Checks the players or damageable objects within hitbox,
-- and makes sure swipe effects stay at the player's location
function Tick()
-- Check for the existence of the equipment or owner before running Tick
if not Object.IsValid(EQUIPMENT) then return end
if not Object.IsValid(EQUIPMENT.owner) then return end
if EQUIPMENT.owner.isDead then return end
for _, abilityInfo in ipairs(abilityList) do
if abilityInfo.canAttack then
DetectAndDamageInSphere(GetHitSpherePosition(), HIT_SPHERE_RADIUS, abilityInfo)
end
end
end
-- Vector3 GetHitSpherePosition()
-- Returns position of the hit sphere based on equipment owner player position and offset
function GetHitSpherePosition()
if not Object.IsValid(EQUIPMENT) then return Vector3.ZERO end
if not Object.IsValid(EQUIPMENT.owner) then return EQUIPMENT:GetWorldPosition() end
local ownerTransform = EQUIPMENT.owner:GetWorldTransform()
return EQUIPMENT.owner:GetWorldPosition() +
ownerTransform:GetForwardVector() * HIT_SPHERE_OFFSET.x +
ownerTransform:GetRightVector() * HIT_SPHERE_OFFSET.y +
ownerTransform:GetUpVector() * HIT_SPHERE_OFFSET.z
end
-- GetValidTarget(Object)
-- Returns the valid Player or Damageable object
function GetValidTarget(player, target)
if not Object.IsValid(target) then return nil end
if API.ValidTrainingTarget(player, target) then
return target
elseif API.ValidTrainingTarget(player, target) then
return target
else
return nil
end
end
-- nil DetectAndDamageInSphere(Vector3, float, table)
-- Creates sphere cast to detect valid object to apply damage on
function DetectAndDamageInSphere(center, radius, abilityInfo)
local hitResults = World.SpherecastAll(center, center + Vector3.FORWARD, radius)
if SHOW_HIT_SPHERE then
CoreDebug.DrawSphere(center, radius)
end
for index, hitResult in ipairs(hitResults) do
local validTarget = GetValidTarget(hitResult.other)
if validTarget then
MeleeAttack(validTarget, abilityInfo)
end
end
end
-- nil MeleeAttack(Player or Damageable Object)
-- Detect players or damagable objects within hitbox to apply damage
function MeleeAttack(target, abilityInfo)
if not Object.IsValid(target) then return end
local ability = abilityInfo.ability
if not Object.IsValid(ability) then return end
if not Object.IsValid(ability.owner) then return end
-- Ignore if the hitbox is overlapping with the owner
if target == ability.owner then return end
-- Ignore friendly attack
if target:IsA("Player") then
if Teams.AreTeamsFriendly(target.team, ability.owner.team) then return end
end
-- Avoid hitting the same player or damageable object multiple times in a single swing
if (abilityInfo.ignoreList[target] ~= 1) then
-- Creates new damage info at apply it to the enemy
local damage = Damage.New(abilityInfo.damage)
damage.sourcePlayer = ability.owner
damage.sourceAbility = ability
target:ApplyDamage(damage)
abilityInfo.ignoreList[target] = 1
end
end
-- nil OnEquipped()
-- Enables collision on player to make the hitbox collidable
function OnEquipped()
Task.Wait(0.1)
EQUIPMENT.collision = Collision.INHERIT
end
-- nil OnExecute(Ability)
-- Spawns a swing effect template on ability execute
function OnExecute(ability)
for _, abilityInfo in ipairs(abilityList) do
if abilityInfo.ability == ability then
abilityInfo.canAttack = true
abilityInfo.ignoreList = {}
end
end
end
-- nil ResetMelee(Ability)
-- Resets this scripts internal variables
function ResetMelee(ability)
-- Forget anything we hit this swing
if ability then
for _, abilityInfo in ipairs(abilityList) do
if abilityInfo.ability == ability then
abilityInfo.canAttack = false
abilityInfo.ignoreList = {}
end
end
else
for _, abilityInfo in ipairs(abilityList) do
abilityInfo.canAttack = false
abilityInfo.ignoreList = {}
end
end
end
-- Initialize
local abilityDescendants = EQUIPMENT:FindDescendantsByType("Ability")
for _, ability in ipairs(abilityDescendants) do
local useHitSphere = ability:GetCustomProperty("UseHitSphere")
if useHitSphere then
ability.executeEvent:Connect(OnExecute)
ability.cooldownEvent:Connect(ResetMelee)
table.insert(abilityList, {
ability = ability,
damage = ability:GetCustomProperty("Damage"),
useHitSphere = useHitSphere,
canAttack = false,
ignoreList = {}
})
end
end
EQUIPMENT.equippedEvent:Connect(OnEquipped)
EQUIPMENT.unequippedEvent:Connect(ResetMelee) |
local brute = require "brute"
local creds = require "creds"
local match = require "match"
local nmap = require "nmap"
local shortport = require "shortport"
description=[[
Performs brute force password auditing against a Nessus vulnerability scanning daemon using the NTP 1.2 protocol.
]]
---
-- @usage
-- nmap --script nessus-brute -p 1241 <host>
--
-- @output
-- PORT STATE SERVICE
-- 1241/tcp open nessus
-- | nessus-brute:
-- | Accounts
-- | nessus:nessus - Valid credentials
-- | Statistics
-- |_ Performed 35 guesses in 75 seconds, average tps: 0
--
-- This script does not appear to perform well when run using multiple threads
-- Although, it's very slow running under a single thread it does work as intended
--
--
-- Version 0.1
-- Created 22/10/2011 - v0.1 - created by Patrik Karlsson <[email protected]>
--
author = "Patrik Karlsson"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"intrusive", "brute"}
portrule = shortport.port_or_service(1241, "nessus", "tcp")
Driver =
{
new = function(self, host, port)
local o = { host = host, port = port }
setmetatable(o, self)
self.__index = self
return o
end,
connect = function( self )
self.socket = brute.new_socket()
if ( not(self.socket:connect(self.host, self.port, "ssl")) ) then
return false
end
return true
end,
login = function( self, username, password )
local handshake = "< NTP/1.2 >< plugins_cve_id plugins_version timestamps dependencies fast_login >\n"
local status, err = self.socket:send(handshake)
if ( not(status) ) then
local err = brute.Error:new( "Failed to send handshake to server" )
err:setAbort(true)
return false, err
end
local line
status, line = self.socket:receive_buf(match.pattern_limit("\r?\n", 2048), false)
if ( not(status) or line ~= "< NTP/1.2 >" ) then
local err = brute.Error:new( "The server failed to respond to handshake" )
err:setAbort( true )
return false, err
end
status, line = self.socket:receive()
if ( not(status) or line ~= "User : ") then
local err = brute.Error:new( "Expected \"User : \", got something else" )
err:setRetry( true )
return false, err
end
status = self.socket:send(username .. "\n")
if ( not(status) ) then
local err = brute.Error:new( "Failed to send username to server" )
err:setAbort( true )
return false, err
end
status, line = self.socket:receive()
if ( not(status) or line ~= "Password : ") then
local err = brute.Error:new( "Expected \"Password : \", got something else" )
err:setRetry( true )
return false, err
end
status = self.socket:send(password)
if ( not(status) ) then
local err = brute.Error:new( "Failed to send password to server" )
err:setAbort( true )
return false, err
end
-- the line feed has to be sent separate like this, otherwise we don't
-- receive the server response and the server simply hangs up
status = self.socket:send("\n")
if ( not(status) ) then
local err = brute.Error:new( "Failed to send password to server" )
err:setAbort( true )
return false, err
end
-- we force a brief incorrect statement just to get an error message to
-- confirm that we've successfully authenticated to the server
local bad_cli_pref = "CLIENT <|> PREFERENCES <|>\n<|> CLIENT\n"
status = self.socket:send(bad_cli_pref)
if ( not(status) ) then
local err = brute.Error:new( "Failed to send bad client preferences packet to server" )
err:setAbort( true )
return false, err
end
-- if the server disconnects us at this point, it's most likely due to
-- that the authentication failed, so simply treat it as an incorrect
-- password, rather than abort.
status, line = self.socket:receive()
if ( not(status) ) then
return false, brute.Error:new( "Incorrect password" )
end
if ( line:match("SERVER <|> PREFERENCES_ERRORS <|>") ) then
return true, creds.Account:new(username, password, creds.State.VALID)
end
return false, brute.Error:new( "Incorrect password" )
end,
disconnect = function( self )
self.socket:close()
end,
}
action = function(host, port)
local engine = brute.Engine:new(Driver, host, port)
engine.options.script_name = SCRIPT_NAME
-- the nessus service doesn't appear to do very well with multiple threads
engine:setMaxThreads(1)
local status, result = engine:start()
return result
end
|
local KUI, E, L, V, P, G = unpack(select(2, ...))
local S = E:GetModule("Skins")
--Cache global variables
--Lua functions
local _G = _G
--WoW API / Variables
--Global variables that we don't cache, list them here for mikk's FindGlobals script
-- GLOBALS:
local function styleVoidstorage()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.voidstorage ~= true or E.private.KlixUI.skins.blizzard.voidstorage ~= true then return end
local VoidStorageFrame = _G["VoidStorageFrame"]
VoidStorageFrame:Styling()
VoidStorageFrame.Page1:ClearAllPoints()
VoidStorageFrame.Page1:SetPoint("LEFT", VoidStorageFrame, "TOPRIGHT", 2, -60)
end
S:AddCallbackForAddon("Blizzard_VoidStorageUI", "KuiVoidStorage", styleVoidstorage) |
local theme={colors={normal={blue={0.27843137254902,0.97647058823529,0.96078431372549,1},green={0.97254901960784,0.0,0.34901960784314,1},cyan={0.76470588235294,0.21176470588235,0.47058823529412,1},white={0.35294117647059,0.28627450980392,0.43137254901961,1},red={0.15294117647059,0.85098039215686,0.83529411764706,1},magenta={0.74117647058824,0.003921568627451,0.32156862745098,1},black={0.99607843137255,1.0,1.0,1},yellow={0.35686274509804,0.63529411764706,0.71372549019608,1}},primary={background={0.99607843137255,1.0,1.0,1},foreground={0.35294117647059,0.28627450980392,0.43137254901961,1}},bright={blue={0.86666666666667,0.83921568627451,0.89803921568627,1},green={0.22352941176471,0.14509803921569,0.31764705882353,1},cyan={0.87058823529412,0.85490196078431,0.88627450980392,1},white={0.098039215686275,0.003921568627451,0.20392156862745,1},red={0.74117647058824,0.71372549019608,0.77254901960784,1},magenta={0.27843137254902,0.019607843137255,0.27450980392157,1},black={0.61176470588235,0.57254901960784,0.65882352941176,1},yellow={0.48235294117647,0.42745098039216,0.54509803921569,1}},cursor={text={0.99607843137255,1.0,1.0,1},cursor={0.35294117647059,0.28627450980392,0.43137254901961,1}}}}
return theme.colors |
--
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- extracts features from an image using a trained model
--
require 'torch'
require 'paths'
require 'io'
local DataLoader = require 'dataloader'
--if #arg < 1 then
-- io.stderr:write('Usage: th extract-features-batch.lua [MODEL]...\n')
-- os.exit(1)
--end
for _, f in ipairs(arg) do
if not paths.filep(f) then
io.stderr:write('file not found: ' .. f .. '\n')
os.exit(1)
end
end
require 'cudnn'
require 'cunn'
require 'image'
local models = require 'models/init'
--local t = require 'transforms'
local opt = {}
opt['gen'] = 'gen'
opt['data'] = '/d/home/yushiyao/Place2/256x256/val'
opt['dataset'] = 'places2'
opt['nThreads'] = 8
opt['batchSize'] = 256
opt['nGPU'] = 4
opt['shareGradInput'] = true
opt['netType'] = 'resnet'
opt['featureMap'] = true
opt['avgType'] = 'arith'
-- Load the model
--print ('loading model')
--local model = models.setup(opt, arg[1])
local model = models.setup(opt, arg[1])
--model:add(nn.View(50,2048,4)):setNumInputDims(2)
--if opt.avgType == 'arith' then
-- model:add(nn.Mean(3)):add(nn.Mean(4))
--end
-- local model = torch.load(arg[1])
-- Remove the fully connected layer
--assert(torch.type(model:get(#model.modules)) == 'nn.Linear')
-- model:remove(#model.modules)
-- Setup the dataloader
local loader = DataLoader.create(opt)
-- The model was trained with this input normalization
local meanstd = {
mean = { 0.485, 0.456, 0.406 },
std = { 0.229, 0.224, 0.225 },
}
--local transform = t.Compose{
-- t.Scale(256),
-- t.ColorNormalize(meanstd),
-- t.CenterCrop(224),
--}
local features
--function get_feature(model, img_list)
-- for i =1,#img_list do
-- -- load the image as a RGB float tensor with values 0..1
-- -- print (img_list[i])
-- local img = image.load(img_list[i], 3, 'float')
--
-- -- Scale, normalize, and crop the image
-- img = transform(img)
--
-- -- View as mini-batch of size 1
-- img = img:view(1, table.unpack(img:size():totable()))
--
-- -- Get the output of the layer before the (removed) fully connected layer
-- local output = model:forward(img:cuda()):squeeze(1)
--
-- if not features then
-- features = torch.FloatTensor(#img_list, output:size(1)):zero()
-- end
--
-- features[i]:copy(output)
-- end
-- return features
--end
function process_dataset(dataloader)
local timer = torch.Timer()
local dataTimer = torch.Timer()
local size = dataloader:size()
print ('Number of batches: ', size)
local feature = {}
local classIdx = {}
for i =1,401 do
feature[i] = {}
feature[i]['feature'] = torch.Tensor(50,2048,2,2)
feature[i]['name'] = {}
classIdx[i] = 1
end
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
input, target = copyInputs(sample)
-- print (input:size(), target:size())
local output = model:forward(input):float()
print (output:size())
-- print (n)
--print (n,size, timer:time().real, dataTime)
print (('Extract:[%d/%d] Time:%.3f Data:%.3f'):format(n, size, timer:time().real, dataTime))
timer:reset()
dataTimer:reset()
local idx
for t = 1, input:size()[1] do
idx = sample.target[t]
--print (feature[idx]:size())
--print (feature[idx][classIdx[idx]]:size())
feature[idx]['feature'][classIdx[idx]]:resize(output[t]:size())
--if opt.avgType == 'geo' then
-- for f =1,4 do
-- output[t]
-- end
--end
feature[idx]['feature'][classIdx[idx]] = output[t]
feature[idx]['name'][classIdx[idx]] = sample.name[t]
classIdx[idx] = classIdx[idx] + 1
end
end
--torch.save('features.t7', features)
--print ('whole feature saving complete!')
print ('start saving features')
for j =1,401 do
feature_path = paths.concat('/d/home/yushiyao/Place2/256x256/val_feature_map',j)
if not paths.dir(feature_path) then
print ('creating dir ', feature_path)
paths.mkdir(feature_path)
end
torch.save(paths.concat(feature_path, 'features_'..j..'.t7'), feature[j])
end
end
function copyInputs(sample)
-- Copies the input to a CUDA tensor, if using 1 GPU, or to pinned memory,
-- if using DataParallelTable. The target is always copied to a CUDA tensor
local input = torch.FloatTensor()
local target = torch.FloatTensor()
input:resize(sample.input:size()):copy(sample.input)
target:resize(sample.target:size()):copy(sample.target)
return input, target
end
print ('start extracting feature')
process_dataset(loader)
--torch.save('features.t7', features)
--print('saved features to features.t7')
|
-- BASIC PACKAGE
local fock_driver = require"iota.fock.driver"
-- NUMBER OF SITES AND PARTICLES
local NSITES = 7
local NFERMIONS = math.floor(NSITES/2)
-- CREATE TUPLE WITH THAT IDENTIFY FOCK SPACE
local tuple = true
do
-- SIMPLE SEQUENCE THAT ENUMERATES THE FERMIONIC CREATION DEGREES, IN THIS CASE, ONE PER SITE
local basis = {}
for k=1,NSITES do basis[k] = k end
tuple = fock_driver.createFermions(basis,NFERMIONS)
end
local max = #tuple
print('Number of Fock states:', #tuple)
-- PRINT FOCK SPACE
for k,v in pairs(tuple) do
if type(k) == 'number' then print(k,v) -- basis[] and respective symmetires
else print("\t",v,k) end -- Id coef |ket>
end
-- AUXILIARY FUNCTION
local strc = function(n) -- auxiliary function for print formated complex numbers
local complex = require"iota.complex.number"
local real,imag = complex.real(n),complex.imag(n)
return string.format("[%6.3f %6.3fi]",real,imag)
end
-- EXACT VALUES FOR ONE PARTICLE
print"EXACT VALUES FOR ONE PARTICLE"
local exact = {} -- one particle
if NSITES%2 == 0 then -- even
for m=1,NSITES do exact[#exact+1] = 2*math.cos(2*math.pi*m/NSITES) end
else -- odd
for m=-(NSITES)/2,(NSITES-1)/2 do exact[#exact+1] = 2*math.cos(2*math.pi*m/NSITES) end
end
table.sort(exact)
for m=1,#exact do print(m,strc(exact[m])) end
-- COMPUTE HAMILTONIAN MATRIX
-- non-interacting spinless fermionic ring Hamiltonian
local Hket = function(H,ketj)
for i=1,NSITES-1 do
H(-1.0, ketj:Af(i):Cf(i+1))
H(-1.0, ketj:Af(i+1):Cf(i))
end
H(-1.0, ketj:Af(1):Cf(NSITES))
H(-1.0, ketj:Af(NSITES):Cf(1))
end
local Hmatrix = fock_driver.get_Hmatrix(tuple, Hket)
-- PRINT HAMILTONIAN
print"HAMILTONIAN MATRIX"
if #tuple < 10 then -- sane option
for k=1,max do for l=1,max do
io.write(strc(Hmatrix[k][l])," ")
end print"" end
else print"Hamiltonian too big to be printed!" end
-- DIAGONALIZE
io.write"DIAGONALIZING THE HAMILTONIAN..."
local jacobi = require"iota.linearalgebra.jacobi"
local evec,eval = jacobi(Hmatrix)
print"OK"
-- COMPUTE EXACT VALUES FOR MANY PARTICLES
local exactene = {}
for k,_ in pairs(tuple) do if type(k) ~= 'number' then
local ene = 0.0
for _,v in pairs({k:getbasis()}) do ene = ene+exact[v] end
exactene[#exactene + 1] = ene
end end
table.sort(exactene)
-- PRINT EIGENVALUES TO COMPARE WITH EXACT ONES
local complex = require"iota.complex.number"
print("EIGENVALUES FOR "..tostring(NFERMIONS).." PARTICLES")
for k=1,#eval do
print(k, strc(eval[k]), strc(exactene[k]) )
assert(complex.abs(eval[k] - exactene[k]) < 1.0e-10)
end
-- THE END
|
List = {}
local List = List
function List.New()
return {first = 0, last = -1}
end
function List.Size(list)
if list.first > list.last then
return 0
else
return list.last + 1 - list.first
end
end
function List.Empty(list)
return list.first > list.last
end
function List.Get(list, index)
local index = list.first + index
return list[index]
end
function List.PushFront(list, value)
local first = list.first - 1
list.first = first
list[first] = value
end
function List.PushBack(list, value)
local last = list.last + 1
list.last = last
list[last] = value
end
function List.PopFront(list)
local first = list.first
if first > list.last then LogError("list is empty") end
local value = list[first]
list[first] = nil -- to allow garbage collection
list.first = first + 1
return value
end
function List.PopBack(list)
local last = list.last
if list.first > last then LogError("list is empty") end
local value = list[last]
list[last] = nil -- to allow garbage collection
list.last = last - 1
return value
end
function List.GetBack(list)
local last = list.last
return list[last]
end
function List.GetFront(list)
local first = list.first
return list[first]
end
|
local iterator -- to be defined later
function allwords()
--使用table实现不如闭包的性能
local state = {line = io.read(), pos = 1}
return iterator, state
end
function iterator (state)
while state.line do -- repeat while there are lines
-- search for next word
local s, e = string.find(state.line, "%w+", state.pos)
if s then -- found a word?
-- updatenext position (after this word)
state.pos = e + 1
return string.sub(state.line, s, e)
else -- word not found
state.line = io.read() -- try next line...
state.pos = 1 -- ... from first position
end
end
return nil -- no more lines: end loop
end |
local gui = require("__flib__.gui-beta")
local constants = require("constants")
local shared = require("scripts.shared")
local settings_page = {}
function settings_page.build(settings)
local output = {}
-- generic - auto-generated from constants
for category_name, elements in pairs(constants.settings) do
local category_output = (
{type = "frame", style = "rb_settings_category_frame", direction = "vertical", children = {
{type = "label", style = "caption_label", caption = {"rb-gui."..category_name}}
}}
)
for name, data in pairs(elements) do
category_output.children[#category_output.children+1] = {
type = "checkbox",
caption = {"rb-gui.setting-"..name},
tooltip = data.has_tooltip and {"rb-gui.setting-"..name.."-tooltip"} or nil,
state = settings[name],
ref = {"settings", name},
tags = {setting_name = name},
actions = {
on_click = {gui = "main", page = "settings", action = "update_setting"}
}
}
end
output[#output+1] = category_output
end
-- categories - auto-generated from recipe_category_prototypes
local recipe_categories_output = {
type = "frame",
style = "rb_settings_category_frame",
direction = "vertical",
children = {
{
type = "label",
style = "caption_label",
caption = {"rb-gui.recipe-categories"},
tooltip = {"rb-gui.recipe-categories-tooltip"}
}
}
}
for name in pairs(game.recipe_category_prototypes) do
recipe_categories_output.children[#recipe_categories_output.children + 1] = {
type = "checkbox",
caption = name,
state = settings.recipe_categories[name],
ref = {"settings", "recipe_category", name},
tags = {category_name = name},
actions = {
on_click = {gui = "main", page = "settings", action = "update_setting"}
}
}
end
output[#output + 1] = recipe_categories_output
return {
type = "frame",
style = "inner_frame_in_outer_frame",
direction = "vertical",
visible = false,
ref = {"settings", "window"},
children = {
{type = "flow", style = "flib_titlebar_flow", ref = {"settings", "titlebar_flow"}, children = {
{type = "label", style = "frame_title", caption = {"gui-menu.settings"}, ignored_by_interaction = true},
{type = "empty-widget", style = "flib_dialog_titlebar_drag_handle", ignored_by_interaction = true},
}},
{type = "frame", style = "inside_shallow_frame", children = {
{
type = "scroll-pane",
style = "rb_settings_content_scroll_pane",
direction = "vertical",
children = output
}
}}
}
}
end
function settings_page.init()
return {
open = false
}
end
function settings_page.update(player_settings, gui_data)
local refs = gui_data.refs.settings
for _, names in pairs(constants.settings) do
for name in pairs(names) do
refs[name].state = player_settings[name]
end
end
for name in pairs(game.recipe_category_prototypes) do
refs.recipe_category[name] = player_settings.recipe_categories[name]
end
end
function settings_page.handle_action(msg, e)
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
if msg.action == "update_setting" then
local tags = gui.get_tags(e.element)
local checked_state = e.element.state
if tags.category_name then
player_table.settings.recipe_categories[tags.category_name] = checked_state
else
player_table.settings[tags.setting_name] = checked_state
end
shared.refresh_contents(player, player_table)
end
end
return settings_page
|
local SocialResponseBuilder = {}
local App42ResponseBuilder = require("App42-Lua-API.App42ResponseBuilder")
local Social = require("App42-Lua-API.Social")
local Friends = require("App42-Lua-API.Friends")
local FacebookProfile = require("App42-Lua-API.FacebookProfile")
local PublicProfile = require("App42-Lua-API.PublicProfile")
function SocialResponseBuilder:buildResponse(jsonString)
local social = require("App42-Lua-API.Social")
local socialJSONObj = App42ResponseBuilder:getServiceJSONObject("social",jsonString)
if(socialJSONObj == nil) then
social:setStrResponse(jsonString)
social:setResponseSuccess(App42ResponseBuilder:isResponseSuccess(jsonString))
else
social = SocialResponseBuilder:buildSocialObject(socialJSONObj)
social:setStrResponse(jsonString)
social:setResponseSuccess(App42ResponseBuilder:isResponseSuccess(jsonString))
end
return social
end
function SocialResponseBuilder:buildSocialObject(socialJSONObject)
local social = SocialResponseBuilder:buildObjectFromJSONTree(socialJSONObject)
local friendArray = {}
local publicFriendArray = {}
if socialJSONObject.friends ~= nil then
local friendsDocArray = socialJSONObject.friends
if table.getn(friendsDocArray) > 0 then
for i=1, table.getn(friendsDocArray) do
friendArray[i] = SocialResponseBuilder:buildFriendsObjectFromJSONTree(friendsDocArray[i])
end
else
friendArray = SocialResponseBuilder:buildFriendsObjectFromJSONTree(friendsDocArray)
end
social:setFriendList(friendArray)
end
if socialJSONObject.me ~= nil then
local meJSONObject = socialJSONObject.me
local me = SocialResponseBuilder:buildFacebookObjectFromJSONTree(meJSONObject)
social:setFacebookProfile(me)
end
if socialJSONObject.facebookProfile ~= nil then
local meJSONObject = socialJSONObject.facebookProfile
local me = SocialResponseBuilder:buildOwnFacebookObjectFromJSONTree(meJSONObject)
social:setFacebookProfile(me)
end
if socialJSONObject.profile ~= nil then
local publicFriendsDocArray = socialJSONObject.profile
if table.getn(publicFriendsDocArray) > 0 then
for i=1, table.getn(publicFriendsDocArray) do
publicFriendArray[i] = SocialResponseBuilder:buildPublicFriendsObjectFromJSONTree(publicFriendsDocArray[i])
end
else
publicFriendArray = SocialResponseBuilder:buildPublicFriendsObjectFromJSONTree(publicFriendsDocArray)
end
social:setPublicProfile(publicFriendArray)
end
return social
end
function SocialResponseBuilder:buildObjectFromJSONTree(json)
local social = Social:new()
if(json.userName ~= nil)then
social:setUserName(json.userName)
end
if(json.status ~= nil) then
social:setStatus(json.status)
end
if(json.facebookAppId ~= nil) then
social:setFacebookAppId(json.facebookAppId)
end
if(json.facebookAppSecret ~= nil) then
social:setFacebookAppSecret(json.facebookAppSecret)
end
if(json.facebookAccessToken ~= nil) then
social:setFacebookAccessToken(json.facebookAccessToken)
end
if(json.twitterConsumerKey ~= nil) then
social:setTwitterConsumerKey(json.twitterConsumerKey)
end
if(json.twitterConsumerSecret ~= nil) then
social:setTwitterConsumerSecret(json.twitterConsumerSecret)
end
if(json.twitterAccessTokenSecret ~= nil) then
social:setTwitterAccessTokenSecret(json.twitterAccessTokenSecret)
end
if(json.twitterAccessToken ~= nil) then
social:setTwitterAccessToken(json.twitterAccessToken)
end
if(json.linkedinApiKey ~= nil) then
social:setLinkedinApiKey(json.linkedinApiKey)
end
if(json.linkedinSecretKey ~= nil) then
social:setLinkedinSecretKey(json.linkedinSecretKey)
end
if(json.linkedinAccessToken ~= nil) then
social:setLinkedinAccessToken(json.linkedinAccessToken)
end
if(json.linkedinAccessTokenSecret ~= nil) then
social:setLinkedinAccessTokenSecret(json.linkedinAccessTokenSecret)
end
return social
end
function SocialResponseBuilder:buildFacebookObjectFromJSONTree(json)
local me = FacebookProfile:new()
if(json.name ~= nil) then
me:setName(json.name)
end
if(json.picture ~= nil) then
me:setPicture(json.picture)
end
if(json.id ~= nil) then
me:setId(json.id)
end
return me
end
function SocialResponseBuilder:buildFriendsObjectFromJSONTree(json)
local friends =Friends:new()
if(json.installed ~= nil)then
friends:setInstalled(json.installed)
end
if(json.name ~= nil) then
friends:setName(json.name)
end
if(json.picture ~= nil) then
friends:setPicture(json.picture)
end
if(json.id ~= nil) then
friends:setId(json.id)
end
return friends
end
function SocialResponseBuilder:buildOwnFacebookObjectFromJSONTree(json)
local me = FacebookProfile:new()
if(json.name ~= nil) then
me:setName(json.name)
end
if(json.picture ~= nil) then
me:setPicture(json.picture)
end
if(json.id ~= nil) then
me:setId(json.id)
end
if(json.firstName ~= nil) then
me:setFirstName(json.firstName)
end
if(json.lastName ~= nil) then
me:setLastName(json.lastName)
end
if(json.gender ~= nil) then
me:setGender(json.gender)
end
if(json.link ~= nil) then
me:setLink(json.link)
end
if(json.locale ~= nil) then
me:setLocale(json.locale)
end
if(json.username ~= nil) then
me:setUserName(json.username)
end
return me
end
function SocialResponseBuilder:buildPublicFriendsObjectFromJSONTree(json)
local me =PublicProfile:new()
if(json.name ~= nil) then
me:setName(json.name)
end
if(json.picture ~= nil) then
me:setPicture(json.picture)
end
if(json.id ~= nil) then
me:setId(json.id)
end
return me
end
return SocialResponseBuilder |
--[[
Project: SA-MP API
Author: LUCHARE
All structures are taken from mod_s0beit_sa.
Copyright: BlastHack
mod_sa is available from https://github.com/BlastHackNet/mod_s0beit_sa/
]]
local sys = require 'SA-MP API.kernel'
sys.safely_include 'SA-MP API.samp.0_3_7-R3.stServerPresets'
sys.safely_include 'SA-MP API.samp.0_3_7-R3.stSAMPPools'
sys.ffi.cdef[[
struct stSAMP {
char pad_0[44];
void *pRakClientInterface;
char szIP[257];
char szHostname[257];
bool m_bDisableCollision;
bool m_bUpdateCameraTarget;
bool bNametagStatus;
int ulPort;
int iLanMode;
unsigned int ulMapIcons[100];
int iGameState;
unsigned int ulConnectTick;
stServerPresets *pSettings;
char pad_2[5];
stSAMPPools *pPools;
} __attribute__ ((packed));
]]
|
function gadget:GetInfo()
return {
name = "Mex Upgrader Gadget",
desc = "Upgrades mexes.",
author = "author: BigHead, modified by DeadnightWarrior",
date = "September 13, 2007",
license = "GNU GPL, v2 or later",
layer = 100,
enabled = true -- loaded by default?
}
end
local ignoreWeapons = false --if the only weapon is a shield it is ignored
local ignoreStealth = false
local remove = table.remove
local GetTeamUnits = Spring.GetTeamUnits
local GetUnitDefID = Spring.GetUnitDefID
local GiveOrderToUnit = Spring.GiveOrderToUnit
local GetUnitPosition = Spring.GetUnitPosition
local GetUnitHealth = Spring.GetUnitHealth
local GetGroundHeight = Spring.GetGroundHeight
local GetUnitTeam = Spring.GetUnitTeam
local GetCommandQueue = Spring.GetCommandQueue
local Echo = Spring.Echo
local FindUnitCmdDesc = Spring.FindUnitCmdDesc
local InsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local EditUnitCmdDesc = Spring.EditUnitCmdDesc
local SendMessageToTeam = Spring.SendMessageToTeam
local ValidUnitID = Spring.ValidUnitID
local GetUnitIsDead = Spring.GetUnitIsDead
local builderDefs = {}
local mexDefs = {}
local messageCount = {}
local mexes = {}
local builders = {}
local IDLE = 0
local FOLOWING_ORDERS = 1
local RECLAIMING = 2
local BUILDING = 3
local scheduledBuilders = {}
local addFakeReclaim = {}
local addCommands = {}
local CMD_RECLAIM = CMD.RECLAIM
local CMD_STOP = CMD.STOP
local CMD_INSERT = CMD.INSERT
local CMD_OPT_INTERNAL = CMD.OPT_INTERNAL
local CMD_AUTOMEX = 31143
local CMD_UPGRADEMEX = 31244
local ONTooltip = "Metal makers are upgraded automatically\nby this builder."
local OFFTooltip = "Metal makers are NOT upgraded automatically\nby this builder."
local autoMexCmdDesc = {
id = CMD_AUTOMEX,
type = CMDTYPE.ICON_MODE,
name = 'Automatic Mex Upgrade',
cursor = 'AutoMex',
action = 'automex',
tooltip = ONTooltip,
params = { '0', 'UpgMex OFF', 'UpgMex ON'}
}
local upgradeMexCmdDesc = {
id = CMD_UPGRADEMEX,
type = CMDTYPE.ICON_UNIT_OR_AREA,
name = ' Upgrade \n Mex',
cursor = 'Attack',
action = 'upgrademex',
tooltip = 'Upgrade Mex',
hidden = false,
params = {}
}
function determine(ud, wd)
local tmpbuilders = {}
for unitDefID, unitDef in pairs(ud) do
if isBuilder(unitDef) then
tmpbuilders[#tmpbuilders+1] = unitDefID
else
local extractsMetal = unitDef.extractsMetal
if (extractsMetal > 0) then
local mexDef = {}
mexDef.extractsMetal = extractsMetal
if #unitDef.weapons <= 1 then
if (#unitDef.weapons == 1 and wd[unitDef.weapons[1].weaponDef].isShield) then
mexDef.armed = #unitDef.weapons < 0
else
mexDef.armed = #unitDef.weapons > 0
end
else
mexDef.armed = #unitDef.weapons > 0
end
mexDef.stealth = unitDef.stealth
mexDef.name = unitDef.name
mexDef.water = unitDef.minWaterDepth >= 0
mexDefs[unitDefID] = mexDef
end
end
end
for _, unitDefID in ipairs(tmpbuilders) do
local upgradePairs = nil
for _, optionID in ipairs(ud[unitDefID].buildOptions) do
local mexDef = mexDefs[optionID]
if mexDef then
upgradePairs = processMexData(optionID, mexDef, upgradePairs)
end
end
if upgradePairs then
builderDefs[unitDefID] = upgradePairs
end
end
end
function processMexData(mexDefID, mexDef, upgradePairs)
for defID, def in pairs(mexDefs) do
if (ignoreStealth or mexDef.stealth == def.stealth) and (ignoreWeapons or mexDef.armed == def.armed) and mexDef.water == true and def.water == true then
if mexDef.extractsMetal > def.extractsMetal then
if not upgradePairs then
upgradePairs = {}
end
local upgrader = upgradePairs[defID]
if not upgrader or mexDef.extractsMetal > mexDefs[upgrader].extractsMetal and mexDef.water == true and mexDefs[upgrader].water == true then
upgradePairs[defID] = mexDefID
end
end
end
if (ignoreStealth or mexDef.stealth == def.stealth) and (ignoreWeapons or mexDef.armed == def.armed) and mexDef.water == false and def.water == false then
--Spring.Echo(mexDef.extractsMetal , def.extractsMetal)
if mexDef.extractsMetal > def.extractsMetal then
if not upgradePairs then
upgradePairs = {}
end
local upgrader = upgradePairs[defID]
if not upgrader or mexDef.extractsMetal > mexDefs[upgrader].extractsMetal and mexDef.water == false and mexDefs[upgrader].water == false then
upgradePairs[defID] = mexDefID
end
end
end
end
return upgradePairs
end
function isBuilder(unitDef)
return (unitDef.isBuilder and unitDef.canAssist)
end
if (gadgetHandler:IsSyncedCode()) then
-- This part of the code determines who should upgrade what
---------------------------------------------------------------------------------------------------------------------------
function gadget:Initialize()
determine(UnitDefs, WeaponDefs)
registerUnits()
end
function registerUnits()
local teams = Spring.GetTeamList()
for _, teamID in ipairs(teams) do
builders[teamID] = {}
mexes[teamID] = {}
for _, unitID in ipairs(GetTeamUnits(teamID)) do
local unitDefID = GetUnitDefID(unitID)
registerUnit(unitID, unitDefID, teamID)
end
end
end
-- This part of the code actually does somethings (upgrades mexes)
---------------------------------------------------------------------------------------------------------------------------
function gadget:GameFrame(n)
for unitID, data in pairs(addCommands) do
GiveOrderToUnit(unitID, data.cmd, data.params, data.options)
end
addCommands = {}
for unitID, data in pairs(scheduledBuilders) do
local teamID = GetUnitTeam(unitID)
if builders[teamID] then
local builder = builders[teamID][unitID]
local y = GetGroundHeight(builder.targetX, builder.targetZ)
GiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_RECLAIM, CMD_OPT_INTERNAL, data}, {"alt"});
GiveOrderToUnit(unitID, CMD_INSERT, {1,-builder.targetUpgrade,CMD_OPT_INTERNAL,builder.targetX, y, builder.targetZ, 0}, {"alt"});
builder.orderTaken = true
end
end
scheduledBuilders = {}
for unitID, _ in pairs(addFakeReclaim) do
local commands = GetCommandQueue(unitID,20)
for i, cmd in ipairs(commands) do
if cmd.id == CMD_UPGRADEMEX and not (commands[i+1] and commands[i+1].id == CMD_RECLAIM) then
GiveOrderToUnit(unitID, CMD_INSERT, {i, CMD_RECLAIM, CMD_OPT_INTERNAL+1, cmd.params[1]}, {"alt"})
end
end
end
addFakeReclaim = {}
gadgetHandler:RemoveCallIn("GameFrame")
end
function autoUpgradeDisabled(unitID, teamID)
local builder = builders[teamID][unitID]
builder.autoUpgrade = false
if getUnitPhase(unitID, teamID) == RECLAIMING then
mexes[teamID][builder.targetMex].assignedBuilder = nil
GiveOrderToUnit(unitID, CMD_STOP, {}, {""})
end
end
function autoUpgradeEnabled(unitID, teamID)
local builder = builders[teamID][unitID]
builder.autoUpgrade = true
local phase = getUnitPhase(unitID, teamID)
if phase ~= BUILDING then
local upgradePairs = builderDefs[builder.unitDefID]
if getClosestMex(unitID, upgradePairs, teamID) then
upgradeClosestMex(unitID, teamID)
end
end
end
function upgradeClosestMex(unitID, teamID, mexesInRange)
local builder = builders[teamID][unitID]
local upgradePairs = builderDefs[builder.unitDefID]
local mexID = getClosestMex(unitID, upgradePairs, teamID, mexesInRange)
if not mexID then
SendToUnsynced("messages", false, teamID, builder.humanName, messageCount[unitID])
if messageCount[unitID] == 250 then
SendToUnsynced("messages", true, teamID, builder.humanName, messageCount[unitID])
Spring.GiveOrderToUnit(unitID, CMD_AUTOMEX, { 0 }, {"alt"})
end
messageCount[unitID] = messageCount[unitID] + 1
return false
end
orderBuilder(unitID, mexID)
return true
end
function orderBuilder(unitID, mexID)
--GiveOrderToUnit(unitID, CMD_UPGRADEMEX, {mexID}, {""});
--addCommands[unitID] = {cmd = CMD_UPGRADEMEX, params = {mexID}, options = {""}}
addCommands[unitID] = {cmd = CMD_INSERT, params = {1, CMD_UPGRADEMEX, CMD_OPT_INTERNAL, mexID}, options = {"alt"}}
gadgetHandler:UpdateCallIn("GameFrame")
end
function upgradeMex(unitID, mexID, teamID)
local builder = builders[teamID][unitID]
local mex = mexes[teamID][mexID]
if not mex then
return
end
local upgradePairs = builderDefs[builder.unitDefID]
builder.targetMex = mexID
builder.targetUpgrade = upgradePairs[mex.unitDefID]
builder.targetX = mex.x
builder.targetY = mex.y
builder.targetZ = mex.z
mex.assignedBuilder = unitID
gadgetHandler:UpdateCallIn("GameFrame")
scheduledBuilders[unitID] = mexID
end
function getClosestMex(unitID, upgradePairs, teamID, mexesInRange)
local bestDistance = nil
local bestMexID, bestMexDefID = nil, nil
if not mexesInRange then
mexesInRange = mexes[teamID]
end
for mexID, mex in pairs(mexesInRange) do
if not mex.assignedBuilder then
local mexDefID = mex.unitDefID
local upgradeTo = upgradePairs[mexDefID]
if upgradeTo then
local dist = getDistance(unitID, mexID, teamID)
if not bestDistance or dist < bestDistance then
bestDistance = dist
bestMexID, bestMexDefID = mexID, mexDefID
end
end
end
end
return bestMexID, bestMexDefID
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam)
unregisterUnit(unitID, unitDefID, unitTeam, true)
end
function gadget:UnitIdle(unitID, unitDefID, unitTeam)
local builder = builders[unitTeam][unitID]
if builder then
if builder.autoUpgrade then
upgradeClosestMex(unitID, unitTeam)
end
end
end
function gadget:UnitTaken(unitID, unitDefID, unitTeam, newTeam)
unregisterUnit(unitID, unitDefID, unitTeam, false)
end
function unregisterUnit(unitID, unitDefID, unitTeam, destroyed)
local mex = mexes[unitTeam][unitID]
local builder = builders[unitTeam][unitID]
if mex then
local builderID = mex.assignedBuilder
if builderID then
builder = builders[unitTeam][builderID]
if not (destroyed and getDistance(builderID, unitID, unitTeam) < builder.buildDistance * 2) then
upgradeClosestMex(builderID, unitTeam)
end
end
messageCount[unitID] = nil
mexes[unitTeam][unitID] = nil
elseif builder then
if getUnitPhase(unitID, unitTeam) == RECLAIMING then
local mex = mexes[unitTeam][builder.targetMex]
if mexes[unitTeam][builder.targetMex] then
mexes[unitTeam][builder.targetMex].assignedBuilder = nil
end
if mex then
assignClosestBuilder(builder.targetMex, mex, unitTeam)
end
end
builders[unitTeam][unitID] = nil
end
end
function registerUnit(unitID, unitDefID, unitTeam)
if builderDefs[unitDefID] then
local builder = {}
local unitDef = UnitDefs[unitDefID]
messageCount[unitID] = 0
builder.unitDefID = unitDefID
builder.autoUpgrade = false
builder.buildDistance = unitDef.buildDistance
builder.humanName = unitDef.humanName
builder.teamID = unitTeam
builders[unitTeam][unitID] = builder
addLayoutCommands(unitID)
elseif mexDefs[unitDefID] then
local mex = {}
mex.unitDefID = unitDefID
mex.teamID = unitTeam
mex.x, mex.y, mex.z = GetUnitPosition(unitID)
mexes[unitTeam][unitID] = mex
assignClosestBuilder(unitID, mex, unitTeam)
end
end
function assignClosestBuilder(mexID, mex, teamID)
local bestDistance = nil
local bestBuilder, bestBuilderID = nil
local mexDefID = mex.unitDefID
for unitID, builder in pairs(builders[teamID]) do
if builder.autoUpgrade and getUnitPhase(unitID, teamID) == IDLE then
local upgradePairs = builderDefs[builder.unitDefID]
local upgradeTo = upgradePairs[mexDefID]
if upgradeTo then
local dist = getDistance(unitID, mexID, teamID)
if not bestDistance or dist < bestDistance then
bestDistance = dist
bestBuilder = builder
bestBuilderID = unitID
end
end
end
end
if bestBuilder then
orderBuilder(bestBuilderID, mexID)
end
end
function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID)
registerUnit(unitID, unitDefID, unitTeam)
end
function gadget:UnitGiven(unitID, unitDefID, unitTeam, oldTeam)
registerUnit(unitID, unitDefID, unitTeam)
end
function getDistance(unitID, mexID, teamID)
local x1, _, y1 = GetUnitPosition(unitID)
local mex = mexes[teamID][mexID]
local x2, y2 = mex.x, mex.z
if not (x1 and y1 and x2 and y2) then return math.huge end --hack
return math.sqrt((x1-x2)^2 + (y1-y2)^2)
end
function getDistanceFromPosition(x1, y1, mexID, teamID)
local mex = mexes[teamID][mexID]
local x2, y2 = mex.x, mex.z
if not (x2 and y2) then return math.huge end --hack
return math.sqrt((x1-x2)^2 + (y1-y2)^2)
end
function getUnitPhase(unitID, teamID)
local commands = GetCommandQueue(unitID,1)
if #commands == 0 then
return IDLE
end
local cmd = commands[1]
local builder = builders[teamID][unitID]
if cmd.id == CMD_RECLAIM and cmd.params[1] == builder.targetMex then
return RECLAIMING
elseif builder.targetUpgrade and cmd.id == builder.targetUpgrade then
return BUILDING
else
return FOLLOWING_ORDERS
end
end
-- Gadget Button
---------------------------------------------------------------------------------------------------------------------------
local ON, OFF = 1, 0
function addLayoutCommands(unitID)
local insertID =
FindUnitCmdDesc(unitID, CMD.CLOAK) or
FindUnitCmdDesc(unitID, CMD.ONOFF) or
FindUnitCmdDesc(unitID, CMD.TRAJECTORY) or
FindUnitCmdDesc(unitID, CMD.REPEAT) or
FindUnitCmdDesc(unitID, CMD.MOVE_STATE) or
FindUnitCmdDesc(unitID, CMD.FIRE_STATE) or
123456 -- back of the pack
autoMexCmdDesc.params[1] = '0'
updateCommand(unitID, insertID + 1, autoMexCmdDesc)
updateCommand(unitID, insertID + 2, upgradeMexCmdDesc)
end
function updateCommand(unitID, insertID, cmd)
local cmdDescId = FindUnitCmdDesc(unitID, cmd.id)
if not cmdDescId then
InsertUnitCmdDesc(unitID, insertID, cmd)
else
EditUnitCmdDesc(unitID, cmdDescId, cmd)
end
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, _)
--Echo("AC " .. cmdID)
local builder = builders[teamID][unitID]
if cmdID == CMD_UPGRADEMEX then
if not cmdParams[2] then -- Unit
local mex = mexes[teamID][cmdParams[1]]
if mex and builder then
local upgradePairs = builderDefs[builder.unitDefID]
local upgradeTo = upgradePairs[mex.unitDefID]
if upgradeTo then
addFakeReclaim[unitID] = true;
gadgetHandler:UpdateCallIn("GameFrame")
return true
end
end
-- Circle
else
return true
end
return false
elseif cmdID ~= CMD_AUTOMEX then
if builder and builder.targetMex and ValidUnitID(builder.targetMex) and (not GetUnitIsDead(builder.targetMex)) and (getUnitPhase(unitID, teamID) == RECLAIMING) then
mexes[teamID][builder.targetMex].assignedBuilder = nil
end
return true
end
local cmdDescID = FindUnitCmdDesc(unitID, CMD_AUTOMEX)
if (cmdDescID == nil) then
return
end
local status = cmdParams[1]
local tooltip
if status == OFF then
autoUpgradeDisabled(unitID, teamID)
tooltip = OFFTooltip
status = OFF
else
autoUpgradeEnabled(unitID, teamID)
tooltip = ONTooltip
status = ON
end
autoMexCmdDesc.params[1] = status
EditUnitCmdDesc(unitID, cmdDescID, {
params = autoMexCmdDesc.params,
tooltip = tooltip
})
return false
end
function gadget:CommandFallback(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
--Echo("CF " .. cmdID)
if cmdID ~= CMD_UPGRADEMEX or not unitID or not unitDefID then
return false
end
local builder = builders[teamID][unitID]
if not builder then
return false
end
if not cmdParams[2] then
-- Unit
if not builder.orderTaken then
local mexID = cmdParams[1]
upgradeMex(unitID, mexID, teamID)
return true, false
else
builder.orderTaken = false
return true, true
end
else
--Circle
local x, y, z, radius = cmdParams[1], cmdParams[2], cmdParams[3], cmdParams[4]
local mexesInRange = {}
local canUpgrade = false
for mexID, mex in pairs(mexes[teamID]) do
if not mex.assignedBuilder and getDistanceFromPosition(x, z, mexID, teamID) < radius then
mexesInRange[mexID] = mexes[teamID][mexID]
canUpgrade = true
end
end
if canUpgrade then
local upgradePairs = builderDefs[builder.unitDefID]
local mexID = getClosestMex(unitID, upgradePairs, teamID, mexesInRange)
if mexID then
addCommands[unitID] = {cmd = CMD_INSERT, params = {0, CMD_UPGRADEMEX, CMD_OPT_INTERNAL, mexID}, options = {"alt"}}
gadgetHandler:UpdateCallIn("GameFrame")
return true, false
end
end
return true, true
end
end
--Unsynced
else
local bDefs = {}
local count = 0
local CMD_AUTOMEX = 31143
local GetSpectatingState = Spring.GetSpectatingState
local GetMyTeamID = Spring.GetMyTeamID
local function RegisterUpgradePairs(_, val)
if Script.LuaUI("registerUpgradePairs") then
Script.LuaUI.registerUpgradePairs(bDefs)
end
return true
end
local function Messages(_, AutoOffMessage, teamID, humanName, Count)
local myTeamID = GetMyTeamID()
if myTeamID == teamID and not GetSpectatingState() then
if AutoOffMessage then
Spring.Echo("\255\255\255\001" ..humanName .. " AutoUpgrade mex Disabled")
end
if (Count%10 == 0) and not AutoOffMessage then
Spring.Echo("\255\255\255\001" ..humanName .. " No Mexes to Upgrade")
end
end
end
function gadget:Initialize()
determine(UnitDefs, WeaponDefs)
for k,v in pairs(builderDefs) do
local upgradePairs = {}
for k2,v2 in pairs(v) do
upgradePairs[k2] = v2
end
bDefs[k] = upgradePairs
end
gadgetHandler:AddChatAction("registerUpgradePairs", RegisterUpgradePairs, "toggles registerUpgradePairs setting")
gadgetHandler:AddSyncAction("messages", Messages)
end
function gadget:Shutdown()
gadgetHandler:RemoveChatAction("registerUpgradePairs")
gadgetHandler.RemoveSyncAction("Messages")
end
end
|
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937'
--[[
do not change anything in here you idiot!
what do u want here go start you fucking script and enter your server
you idiot!
--]]
client_script 'SDP info-c.lua' |
--[[
Name: Hive -> Turtle Automation System
Type: Server
Author: DannySMc
Platform: Lua Virtual Machine
CCType: Advanced Computer
Dependencies: Wireless Modem, HTTP Enabled.
Shared Database Store:
+ hive -> list = Will list all jobs saved to the job store.
+ hive -> download = Will download a job and save it to the server.
+ hive -> upload = Will allow you to upload a job from the server to the job store.
Server Connections API:
(FORMAT: function name -> args -> output)
+ hive_core_connect -> username, password -> "false" (failed) clienthash if worked.
+ hive_core_disconnect -> clienthash -> "true" or "false"
+
]]
---------------------------------------- INITIALISATION OF VARIABLES AND NAMING CONVENTIONS ----------------------------------------
cchive = {}
cchive.__index = cchive
cchive.draw = {}
cchive.draw.__index = cchive.draw
cchive.core = {}
cchive.core.__index = cchive.core
-------------------------------------- END INITIALISATION OF VARIABLES AND NAMING CONVENTIONS ----------------------------------------
-- Download my API
local downloadapi = false
local nTries = 0
while not downloadapi do
local ok, err = pcall( function()
if http then
aa = aa or {}
local a = http.get("https://api.dannysmc.com/files/apis/progutils.lua")
a = a.readAll()
local env = {}
a = loadstring(a)
local env = getfenv()
setfenv(a,env)
local status, err = pcall(a, unpack(aa))
if (not status) and err then
printError("Error loading api")
return false
end
local returned = err
env = env
_G["progutils"] = env
end
end)
if not ok then
term.clear()
term.setCursorPos(1,1)
print("Download API (Attempt: "..nTries.."/".."5)")
if nTries >= 5 then
shell.run("shell")
end
else
downloadapi = true
end
end
-- Set up variables
hivedata = {
["buffer"] = {};
["config"] = {
["modemSide"] = "top";
["type"] = "server:solo";
["name"] = "CC-Hive Server";
};
["trusted"] = {};
["status"] = {
["server"] = "OKAY";
["buffer"] = "OKAY";
["requests"] = {
["total"] = 0;
["session"] = 0;
};
};
}
function cchive.main()
local ok, err = pcall( function()
-- Initialise Hive
cchive.init()
-- Initialise Screen
cchive.screen()
-- Load Configs
cchive.config()
cchive.event()
end)
if not ok then
col.screen("white")
local text = "Thanks for using CC-Hive, it seems an error has occured, forcing the system to halt, please choose the appropriate option."
for k,v in ipairs(data.wordwrap(text, 40)) do
draw.textc(v, k+4, false, "grey", "white")
end
draw.textc("---------- Error Message ----------", 11, false, "grey", "white")
for k,v in ipairs(data.wordwrap(err, 45)) do
draw.textc(v, k+12, false, "red", "white")
end
sleep(2)
draw.cscreen()
else
col.screen("white")
local text = "Thanks for using CC-Hive, this software is developed and maintained by Lupus590, DannySMc and KingofGamesYami."
for k,v in ipairs(data.wordwrap(text, 40)) do
draw.textc(v, k+15, false, "grey", "white")
end
local logo = paintutils.loadImage("CC-Hive/src/Assets/logo.lua")
paintutils.drawImage(logo, 8, 2)
sleep(2)
draw.cscreen()
end
end
function cchive.init()
end
function cchive.screen()
col.screen("white")
draw.box(1, 51, 1, 1, " ", "grey", "grey")
draw.textl("CC-Hive", 1, false, "cyan", "grey")
draw.textr(misc.time(), 1, false, "lime", "grey")
draw.texta("[SERVER]: " .. hivedata.status.server, 1, 4, false, "grey", "white")
draw.texta("[BUFFER]: " .. hivedata.status.buffer.. " - ("..#hivedata.buffer..")", 1, 5, false, "grey", "white")
draw.texta("[REQUES]: Session("..hivedata.status.requests.session..") - Total("..hivedata.status.requests.total..")", 1, 6, false, "grey", "white")
end
function cchive.config()
end
function cchive.event()
while true do
local args = { os.pullEvent() }
if args[1] == "timer" then
draw.textr(misc.time(), 1, false, "lime", "grey")
elseif args[1] == "rednet_message" then
-- Check if reply is trusted
for _, v in ipairs(hivedata.trusted) do
if v.id == args[2] then
-- Do main code parsing here.
-- Add a transmit.decode() function to API to streamline this?
local request = basesf.decode(args[3])
local request1 = convert.bintotxt(request)
request = textutils.unserialize(request)
if request.command == "FINISHED" then
-- Turtle Command
elseif request.command == "WORKING" then
-- Turtle Command
elseif request.command == "ERROR" then
-- Turtle Command
elseif request.command == "RUN_JOB" then
-- Turtle Command
elseif request.command == "CLIENT_CONNECT" then
-- Client Command
-- Add to trusted,
-- Administer encryption keys
-- Same thing for turtles initially connecting
elseif request.command == "NEW_JOB" then
-- Client Command
elseif request.command == "DEL_JOB" then
-- Client Command
end
hivedata.status.requests.session = hivedata.status.requests.session + 1
hivedata.status.requests.total = hivedata.status.requests.total + 1
end
end
elseif args[1] == "char" then
break
end
end
end
--[[
REQUESTS:
CLIENT:
+ JOB_NEW
+ JOB_DEL
+ JOB_EDT
TURTLE:
+ TASK_NEW
+ TASK_DEL
+ TASK
MONITOR:
+ MON_STATUS
+ MON_STATUS_TURTLE
+ MON_JOBS
]]
---------------------------------------- START CC-HIVE SYSTEM SERVER ----------------------------------------
if downloadapi then
cchive.main()
else
error("CC-Hive\'s server has crashed! :(")
end
|
--this = SceneNode()
PathModel = {}
function PathModel.new(inParentNode, inColor)
--inParentNode = SceneNode()
local self = {}
local mesh = NodeMesh()
local color = inColor
local s = 2
local w = 0.1
local boxSize = Vec3()
local boxWidth = 0
function self.setVisible(visible)
mesh:setVisible(visible)
end
function self.setPosition(globalPos)
mesh:setLocalPosition(globalPos)
end
function self.collision(globalLine)
local box = Box( -Vec3(boxSize.x,0, boxSize.z) - Vec3(boxWidth), Vec3(boxSize.x, boxSize.y*2, boxSize.z) + Vec3(boxWidth))
local localLine = Line3D( mesh:getGlobalMatrix():inverseM() * globalLine.startPos, mesh:getGlobalMatrix():inverseM() * globalLine.endPos)
local collision, position = Collision.line3DSegmentBoxIntersection( localLine, box)
return collision, mesh:getGlobalMatrix() * position
end
function self.destroy()
mesh:destroy()
mesh = nil
end
function addPanel(p1, p2, at, color)
local up = (p2-p1):normalizeV() * w
local right = at:crossProductV(up):normalizeV() * w
local index = mesh:getNumVertex()
mesh:addVertex(p1 + up + right + at, color)
mesh:addVertex(p1 + up + right - at, color)
mesh:addVertex(p2 - up + right + at, color)
mesh:addVertex(p2 - up + right - at, color)
mesh:addIndex(index + 0)
mesh:addIndex(index + 1)
mesh:addIndex(index + 2)
mesh:addIndex(index + 1)
mesh:addIndex(index + 3)
mesh:addIndex(index + 2)
end
function addSide(p1, p2, p3, p4, color, rightColor, upColor)
local up = (p2-p1):normalizeV() * w
local right = (p4-p1):normalizeV() * w
local atVec = up:crossProductV(right):normalizeV() * w
local index = mesh:getNumVertex()
mesh:addVertex(p1 - up - right + atVec, color)
mesh:addVertex(p1 + up + right + atVec, color)
mesh:addVertex(p2 + up - right + atVec, color)
mesh:addVertex(p2 - up + right + atVec, color)
mesh:addVertex(p3 + up + right + atVec, color)
mesh:addVertex(p3 - up - right + atVec, color)
mesh:addVertex(p4 - up + right + atVec, color)
mesh:addVertex(p4 + up - right + atVec, color)
for i=0, 6, 2 do
mesh:addIndex(index + (i + 0) % 8)
mesh:addIndex(index + (i + 1) % 8)
mesh:addIndex(index + (i + 2) % 8)
mesh:addIndex(index + (i + 1) % 8)
mesh:addIndex(index + (i + 3) % 8)
mesh:addIndex(index + (i + 2) % 8)
end
addPanel(p1, p2, atVec, rightColor)
addPanel(p2, p3, atVec, upColor)
addPanel(p3, p4, atVec, rightColor)
addPanel(p4, p1, atVec, upColor)
end
function self.setQubeSize(cubeSize, lineWidth)
--cubeSize = Vec3()
--lineWidth = number()
boxSize = cubeSize
boxWidth = lineWidth
mesh:clearMesh()
s = cubeSize
w = lineWidth
corner = {Vec3(-s.x,0,-s.z), Vec3(-s.x,0,s.z), Vec3(s.x,0,s.z), Vec3(s.x,0,-s.z), Vec3(-s.x,s.y*2,-s.z), Vec3(-s.x,s.y*2,s.z), Vec3(s.x,s.y*2,s.z), Vec3(s.x,s.y*2,-s.z)}
local atColor = inColor
local rightColor = inColor * 0.5
local upColor = inColor * 0.75
addSide(corner[1], corner[5], corner[8], corner[4], atColor, rightColor, upColor)
addSide(corner[3], corner[7], corner[6], corner[2], atColor, rightColor, upColor)
addSide(corner[2], corner[6], corner[5], corner[1], rightColor, atColor, upColor)
addSide(corner[4], corner[8], corner[7], corner[3], rightColor, atColor, upColor)
addSide(corner[6], corner[7], corner[8], corner[5], upColor, atColor, rightColor)
addSide(corner[1], corner[4], corner[3], corner[2], upColor, atColor, rightColor)
mesh:compile()
mesh:setBoundingSphere(Sphere( Vec3(0,cubeSize.y,0), cubeSize:length()))
end
function init()
mesh = NodeMesh()
mesh:setVertexType(VertexType.position3, VertexType.color3)
inParentNode:addChild(mesh)
mesh:setRenderLevel(31)
mesh:setShader(Core.getShader("toolNormal"))
mesh:setColor(Vec4(1))
mesh:setCanBeSaved(false)
mesh:setCollisionEnabled(false)
end
init()
return self
end |
SILE.hyphenator.languages["bg"] = {}
SILE.hyphenator.languages["bg"].patterns =
{
"1а1",
"1б1",
"1в1",
"1г1",
"1д1",
"1е1",
"1ж1",
"1з1",
"1и1",
"1й1",
"1к1",
"1л1",
"1м1",
"1н1",
"1о1",
"1п1",
"1р1",
"1с1",
"1т1",
"1у1",
"1ф1",
"1х1",
"1ц1",
"1ч1",
"1ш1",
"1щ1",
"1ъ1",
"0ь0",
"1ю1",
"1я1",
"б4а б4е б4и б4о б4у б4ъ б4ю б4я",
"в4а в4е в4и в4о в4у в4ъ в4ю в4я",
"г4а г4е г4и г4о г4у г4ъ г4ю г4я",
"д4а д4е д4и д4о д4у д4ъ д4ю д4я",
"ж4а ж4е ж4и ж4о ж4у ж4ъ ж4ю ж4я",
"з4а з4е з4и з4о з4у з4ъ з4ю з4я",
"й4а й4е й4и й4о й4у й4ъ й4ю й4я",
"к4а к4е к4и к4о к4у к4ъ к4ю к4я",
"л4а л4е л4и л4о л4у л4ъ л4ю л4я",
"м4а м4е м4и м4о м4у м4ъ м4ю м4я",
"н4а н4е н4и н4о н4у н4ъ н4ю н4я",
"п4а п4е п4и п4о п4у п4ъ п4ю п4я",
"р4а р4е р4и р4о р4у р4ъ р4ю р4я",
"с4а с4е с4и с4о с4у с4ъ с4ю с4я",
"т4а т4е т4и т4о т4у т4ъ т4ю т4я",
"ф4а ф4е ф4и ф4о ф4у ф4ъ ф4ю ф4я",
"х4а х4е х4и х4о х4у х4ъ х4ю х4я",
"ц4а ц4е ц4и ц4о ц4у ц4ъ ц4ю ц4я",
"ч4а ч4е ч4и ч4о ч4у ч4ъ ч4ю ч4я",
"ш4а ш4е ш4и ш4о ш4у ш4ъ ш4ю ш4я",
"щ4а щ4е щ4и щ4о щ4у щ4ъ щ4ю щ4я",
"ь4а ь4е ь4и ь4о ь4у ь4ъ ь4ю ь4я",
"4б3б4",
"2б3в2",
"2б3г2",
"2б3д2",
"2б3ж2",
"2б3з2",
"2б3й2",
"2б3к2",
"2б3л2",
"2б3м2",
"2б3н2",
"2б3п2",
"2б3р2",
"2б3с2",
"2б3т2",
"2б3ф2",
"2б3х2",
"2б3ц2",
"2б3ч2",
"2б3ш2",
"2б3щ2",
"2в3б2",
"4в3в4",
"2в3г2",
"2в3д2",
"2в3ж2",
"2в3з2",
"2в3й2",
"2в3к2",
"2в3л2",
"2в3м2",
"2в3н2",
"2в3п2",
"2в3р2",
"2в3с2",
"2в3т2",
"2в3ф2",
"2в3х2",
"2в3ц2",
"2в3ч2",
"2в3ш2",
"2в3щ2",
"2г3б2",
"2г3в2",
"4г3г4",
"2г3д2",
"2г3ж2",
"2г3з2",
"2г3й2",
"2г3к2",
"2г3л2",
"2г3м2",
"2г3н2",
"2г3п2",
"2г3р2",
"2г3с2",
"2г3т2",
"2г3ф2",
"2г3х2",
"2г3ц2",
"2г3ч2",
"2г3ш2",
"2г3щ2",
"2д3б2",
"2д3в2",
"2д3г2",
"4д3д4",
"3д4ж",
"2д3з2",
"2д3й2",
"2д3к2",
"2д3л2",
"2д3м2",
"2д3н2",
"2д3п2",
"2д3р2",
"2д3с2",
"2д3т2",
"2д3ф2",
"2д3х2",
"2д3ц2",
"2д3ч2",
"2д3ш2",
"2д3щ2",
"2ж3б2",
"2ж3в2",
"2ж3г2",
"2ж3д2",
"4ж3ж4",
"2ж3з2",
"2ж3й2",
"2ж3к2",
"2ж3л2",
"2ж3м2",
"2ж3н2",
"2ж3п2",
"2ж3р2",
"2ж3с2",
"2ж3т2",
"2ж3ф2",
"2ж3х2",
"2ж3ц2",
"2ж3ч2",
"2ж3ш2",
"2ж3щ2",
"2з3б2",
"2з3в2",
"2з3г2",
"2з3д2",
"2з3ж2",
"4з3з4",
"2з3й2",
"2з3к2",
"2з3л2",
"2з3м2",
"2з3н2",
"2з3п2",
"2з3р2",
"2з3с2",
"2з3т2",
"2з3ф2",
"2з3х2",
"2з3ц2",
"2з3ч2",
"2з3ш2",
"2з3щ2",
"2й3б2",
"2й3в2",
"2й3г2",
"2й3д2",
"2й3ж2",
"2й3з2",
"4й3й4",
"2й3к2",
"2й3л2",
"2й3м2",
"2й3н2",
"2й3п2",
"2й3р2",
"2й3с2",
"2й3т2",
"2й3ф2",
"2й3х2",
"2й3ц2",
"2й3ч2",
"2й3ш2",
"2й3щ2",
"2к3б2",
"2к3в2",
"2к3г2",
"2к3д2",
"2к3ж2",
"2к3з2",
"2к3й2",
"4к3к4",
"2к3л2",
"2к3м2",
"2к3н2",
"2к3п2",
"2к3р2",
"2к3с2",
"2к3т2",
"2к3ф2",
"2к3х2",
"2к3ц2",
"2к3ч2",
"2к3ш2",
"2к3щ2",
"2л3б2",
"2л3в2",
"2л3г2",
"2л3д2",
"2л3ж2",
"2л3з2",
"2л3й2",
"2л3к2",
"4л3л4",
"2л3м2",
"2л3н2",
"2л3п2",
"2л3р2",
"2л3с2",
"2л3т2",
"2л3ф2",
"2л3х2",
"2л3ц2",
"2л3ч2",
"2л3ш2",
"2л3щ2",
"2м3б2",
"2м3в2",
"2м3г2",
"2м3д2",
"2м3ж2",
"2м3з2",
"2м3й2",
"2м3к2",
"2м3л2",
"4м3м4",
"2м3н2",
"2м3п2",
"2м3р2",
"2м3с2",
"2м3т2",
"2м3ф2",
"2м3х2",
"2м3ц2",
"2м3ч2",
"2м3ш2",
"2м3щ2",
"2н3б2",
"2н3в2",
"2н3г2",
"2н3д2",
"2н3ж2",
"2н3з2",
"2н3й2",
"2н3к2",
"2н3л2",
"2н3м2",
"4н3н4",
"2н3п2",
"2н3р2",
"2н3с2",
"2н3т2",
"2н3ф2",
"2н3х2",
"2н3ц2",
"2н3ч2",
"2н3ш2",
"2н3щ2",
"2п3б2",
"2п3в2",
"2п3г2",
"2п3д2",
"2п3ж2",
"2п3з2",
"2п3й2",
"2п3к2",
"2п3л2",
"2п3м2",
"2п3н2",
"4п3п4",
"2п3р2",
"2п3с2",
"2п3т2",
"2п3ф2",
"2п3х2",
"2п3ц2",
"2п3ч2",
"2п3ш2",
"2п3щ2",
"2р3б2",
"2р3в2",
"2р3г2",
"2р3д2",
"2р3ж2",
"2р3з2",
"2р3й2",
"2р3к2",
"2р3л2",
"2р3м2",
"2р3н2",
"2р3п2",
"4р3р4",
"2р3с2",
"2р3т2",
"2р3ф2",
"2р3х2",
"2р3ц2",
"2р3ч2",
"2р3ш2",
"2р3щ2",
"2с3б2",
"2с3в2",
"2с3г2",
"2с3д2",
"2с3ж2",
"2с3з2",
"2с3й2",
"2с3к2",
"2с3л2",
"2с3м2",
"2с3н2",
"2с3п2",
"2с3р2",
"4с3с4",
"2с3т2",
"2с3ф2",
"2с3х2",
"2с3ц2",
"2с3ч2",
"2с3ш2",
"2с3щ2",
"2т3б2",
"2т3в2",
"2т3г2",
"2т3д2",
"2т3ж2",
"2т3з2",
"2т3й2",
"2т3к2",
"2т3л2",
"2т3м2",
"2т3н2",
"2т3п2",
"2т3р2",
"2т3с2",
"4т3т4",
"2т3ф2",
"2т3х2",
"2т3ц2",
"2т3ч2",
"2т3ш2",
"2т3щ2",
"2ф3б2",
"2ф3в2",
"2ф3г2",
"2ф3д2",
"2ф3ж2",
"2ф3з2",
"2ф3й2",
"2ф3к2",
"2ф3л2",
"2ф3м2",
"2ф3н2",
"2ф3п2",
"2ф3р2",
"2ф3с2",
"2ф3т2",
"4ф3ф4",
"2ф3х2",
"2ф3ц2",
"2ф3ч2",
"2ф3ш2",
"2ф3щ2",
"2х3б2",
"2х3в2",
"2х3г2",
"2х3д2",
"2х3ж2",
"2х3з2",
"2х3й2",
"2х3к2",
"2х3л2",
"2х3м2",
"2х3н2",
"2х3п2",
"2х3р2",
"2х3с2",
"2х3т2",
"2х3ф2",
"4х3х4",
"2х3ц2",
"2х3ч2",
"2х3ш2",
"2х3щ2",
"2ц3б2",
"2ц3в2",
"2ц3г2",
"2ц3д2",
"2ц3ж2",
"2ц3з2",
"2ц3й2",
"2ц3к2",
"2ц3л2",
"2ц3м2",
"2ц3н2",
"2ц3п2",
"2ц3р2",
"2ц3с2",
"2ц3т2",
"2ц3ф2",
"2ц3х2",
"4ц3ц4",
"2ц3ч2",
"2ц3ш2",
"2ц3щ2",
"2ч3б2",
"2ч3в2",
"2ч3г2",
"2ч3д2",
"2ч3ж2",
"2ч3з2",
"2ч3й2",
"2ч3к2",
"2ч3л2",
"2ч3м2",
"2ч3н2",
"2ч3п2",
"2ч3р2",
"2ч3с2",
"2ч3т2",
"2ч3ф2",
"2ч3х2",
"2ч3ц2",
"4ч3ч4",
"2ч3ш2",
"2ч3щ2",
"2ш3б2",
"2ш3в2",
"2ш3г2",
"2ш3д2",
"2ш3ж2",
"2ш3з2",
"2ш3й2",
"2ш3к2",
"2ш3л2",
"2ш3м2",
"2ш3н2",
"2ш3п2",
"2ш3р2",
"2ш3с2",
"2ш3т2",
"2ш3ф2",
"2ш3х2",
"2ш3ц2",
"2ш3ч2",
"4ш3ш4",
"2ш3щ2",
"2щ3б2",
"2щ3в2",
"2щ3г2",
"2щ3д2",
"2щ3ж2",
"2щ3з2",
"2щ3й2",
"2щ3к2",
"2щ3л2",
"2щ3м2",
"2щ3н2",
"2щ3п2",
"2щ3р2",
"2щ3с2",
"2щ3т2",
"2щ3ф2",
"2щ3х2",
"2щ3ц2",
"2щ3ч2",
"2щ3ш2",
"4щ3щ4",
"ааа4",
"аае4",
"ааи4",
"аао4",
"аау4",
"ааъ4",
"ааю4",
"аая4",
"аеа4",
"аее4",
"аеи4",
"аео4",
"аеу4",
"аеъ4",
"аею4",
"аея4",
"аиа4",
"аие4",
"аии4",
"аио4",
"аиу4",
"аиъ4",
"аию4",
"аия4",
"аоа4",
"аое4",
"аои4",
"аоо4",
"аоу4",
"аоъ4",
"аою4",
"аоя4",
"ауа4",
"ауе4",
"ауи4",
"ауо4",
"ауу4",
"ауъ4",
"аую4",
"ауя4",
"аъа4",
"аъе4",
"аъи4",
"аъо4",
"аъу4",
"аъъ4",
"аъю4",
"аъя4",
"аюа4",
"аюе4",
"аюи4",
"аюо4",
"аюу4",
"аюъ4",
"аюю4",
"аюя4",
"аяа4",
"аяе4",
"аяи4",
"аяо4",
"аяу4",
"аяъ4",
"аяю4",
"аяя4",
"еаа4",
"еае4",
"еаи4",
"еао4",
"еау4",
"еаъ4",
"еаю4",
"еая4",
"ееа4",
"еее4",
"ееи4",
"еео4",
"ееу4",
"ееъ4",
"еею4",
"еея4",
"еиа4",
"еие4",
"еии4",
"еио4",
"еиу4",
"еиъ4",
"еию4",
"еия4",
"еоа4",
"еое4",
"еои4",
"еоо4",
"еоу4",
"еоъ4",
"еою4",
"еоя4",
"еуа4",
"еуе4",
"еуи4",
"еуо4",
"еуу4",
"еуъ4",
"еую4",
"еуя4",
"еъа4",
"еъе4",
"еъи4",
"еъо4",
"еъу4",
"еъъ4",
"еъю4",
"еъя4",
"еюа4",
"еюе4",
"еюи4",
"еюо4",
"еюу4",
"еюъ4",
"еюю4",
"еюя4",
"еяа4",
"еяе4",
"еяи4",
"еяо4",
"еяу4",
"еяъ4",
"еяю4",
"еяя4",
"иаа4",
"иае4",
"иаи4",
"иао4",
"иау4",
"иаъ4",
"иаю4",
"иая4",
"иеа4",
"иее4",
"иеи4",
"иео4",
"иеу4",
"иеъ4",
"иею4",
"иея4",
"ииа4",
"иие4",
"иии4",
"иио4",
"ииу4",
"ииъ4",
"иию4",
"иия4",
"иоа4",
"иое4",
"иои4",
"иоо4",
"иоу4",
"иоъ4",
"иою4",
"иоя4",
"иуа4",
"иуе4",
"иуи4",
"иуо4",
"иуу4",
"иуъ4",
"иую4",
"иуя4",
"иъа4",
"иъе4",
"иъи4",
"иъо4",
"иъу4",
"иъъ4",
"иъю4",
"иъя4",
"июа4",
"июе4",
"июи4",
"июо4",
"июу4",
"июъ4",
"июю4",
"июя4",
"ияа4",
"ияе4",
"ияи4",
"ияо4",
"ияу4",
"ияъ4",
"ияю4",
"ияя4",
"оаа4",
"оае4",
"оаи4",
"оао4",
"оау4",
"оаъ4",
"оаю4",
"оая4",
"оеа4",
"оее4",
"оеи4",
"оео4",
"оеу4",
"оеъ4",
"оею4",
"оея4",
"оиа4",
"оие4",
"оии4",
"оио4",
"оиу4",
"оиъ4",
"оию4",
"оия4",
"ооа4",
"оое4",
"оои4",
"ооо4",
"ооу4",
"ооъ4",
"оою4",
"ооя4",
"оуа4",
"оуе4",
"оуи4",
"оуо4",
"оуу4",
"оуъ4",
"оую4",
"оуя4",
"оъа4",
"оъе4",
"оъи4",
"оъо4",
"оъу4",
"оъъ4",
"оъю4",
"оъя4",
"оюа4",
"оюе4",
"оюи4",
"оюо4",
"оюу4",
"оюъ4",
"оюю4",
"оюя4",
"ояа4",
"ояе4",
"ояи4",
"ояо4",
"ояу4",
"ояъ4",
"ояю4",
"ояя4",
"уаа4",
"уае4",
"уаи4",
"уао4",
"уау4",
"уаъ4",
"уаю4",
"уая4",
"уеа4",
"уее4",
"уеи4",
"уео4",
"уеу4",
"уеъ4",
"уею4",
"уея4",
"уиа4",
"уие4",
"уии4",
"уио4",
"уиу4",
"уиъ4",
"уию4",
"уия4",
"уоа4",
"уое4",
"уои4",
"уоо4",
"уоу4",
"уоъ4",
"уою4",
"уоя4",
"ууа4",
"ууе4",
"ууи4",
"ууо4",
"ууу4",
"ууъ4",
"уую4",
"ууя4",
"уъа4",
"уъе4",
"уъи4",
"уъо4",
"уъу4",
"уъъ4",
"уъю4",
"уъя4",
"уюа4",
"уюе4",
"уюи4",
"уюо4",
"уюу4",
"уюъ4",
"уюю4",
"уюя4",
"уяа4",
"уяе4",
"уяи4",
"уяо4",
"уяу4",
"уяъ4",
"уяю4",
"уяя4",
"ъаа4",
"ъае4",
"ъаи4",
"ъао4",
"ъау4",
"ъаъ4",
"ъаю4",
"ъая4",
"ъеа4",
"ъее4",
"ъеи4",
"ъео4",
"ъеу4",
"ъеъ4",
"ъею4",
"ъея4",
"ъиа4",
"ъие4",
"ъии4",
"ъио4",
"ъиу4",
"ъиъ4",
"ъию4",
"ъия4",
"ъоа4",
"ъое4",
"ъои4",
"ъоо4",
"ъоу4",
"ъоъ4",
"ъою4",
"ъоя4",
"ъуа4",
"ъуе4",
"ъуи4",
"ъуо4",
"ъуу4",
"ъуъ4",
"ъую4",
"ъуя4",
"ъъа4",
"ъъе4",
"ъъи4",
"ъъо4",
"ъъу4",
"ъъъ4",
"ъъю4",
"ъъя4",
"ъюа4",
"ъюе4",
"ъюи4",
"ъюо4",
"ъюу4",
"ъюъ4",
"ъюю4",
"ъюя4",
"ъяа4",
"ъяе4",
"ъяи4",
"ъяо4",
"ъяу4",
"ъяъ4",
"ъяю4",
"ъяя4",
"юаа4",
"юае4",
"юаи4",
"юао4",
"юау4",
"юаъ4",
"юаю4",
"юая4",
"юеа4",
"юее4",
"юеи4",
"юео4",
"юеу4",
"юеъ4",
"юею4",
"юея4",
"юиа4",
"юие4",
"юии4",
"юио4",
"юиу4",
"юиъ4",
"юию4",
"юия4",
"юоа4",
"юое4",
"юои4",
"юоо4",
"юоу4",
"юоъ4",
"юою4",
"юоя4",
"юуа4",
"юуе4",
"юуи4",
"юуо4",
"юуу4",
"юуъ4",
"юую4",
"юуя4",
"юъа4",
"юъе4",
"юъи4",
"юъо4",
"юъу4",
"юъъ4",
"юъю4",
"юъя4",
"ююа4",
"ююе4",
"ююи4",
"ююо4",
"ююу4",
"ююъ4",
"ююю4",
"ююя4",
"юяа4",
"юяе4",
"юяи4",
"юяо4",
"юяу4",
"юяъ4",
"юяю4",
"юяя4",
"яаа4",
"яае4",
"яаи4",
"яао4",
"яау4",
"яаъ4",
"яаю4",
"яая4",
"яеа4",
"яее4",
"яеи4",
"яео4",
"яеу4",
"яеъ4",
"яею4",
"яея4",
"яиа4",
"яие4",
"яии4",
"яио4",
"яиу4",
"яиъ4",
"яию4",
"яия4",
"яоа4",
"яое4",
"яои4",
"яоо4",
"яоу4",
"яоъ4",
"яою4",
"яоя4",
"яуа4",
"яуе4",
"яуи4",
"яуо4",
"яуу4",
"яуъ4",
"яую4",
"яуя4",
"яъа4",
"яъе4",
"яъи4",
"яъо4",
"яъу4",
"яъъ4",
"яъю4",
"яъя4",
"яюа4",
"яюе4",
"яюи4",
"яюо4",
"яюу4",
"яюъ4",
"яюю4",
"яюя4",
"яяа4",
"яяе4",
"яяи4",
"яяо4",
"яяу4",
"яяъ4",
"яяю4",
"яяя4",
"й4бб",
"й4бв",
"й4бг",
"й4бд",
"й4бж",
"й4бз",
"й4бй",
"й4бк",
"й4бл",
"й4бм",
"й4бн",
"й4бп",
"й4бр",
"й4бс",
"й4бт",
"й4бф",
"й4бх",
"й4бц",
"й4бч",
"й4бш",
"й4бщ",
"й4вб",
"й4вв",
"й4вг",
"й4вд",
"й4вж",
"й4вз",
"й4вй",
"й4вк",
"й4вл",
"й4вм",
"й4вн",
"й4вп",
"й4вр",
"й4вс",
"й4вт",
"й4вф",
"й4вх",
"й4вц",
"й4вч",
"й4вш",
"й4вщ",
"й4гб",
"й4гв",
"й4гг",
"й4гд",
"й4гж",
"й4гз",
"й4гй",
"й4гк",
"й4гл",
"й4гм",
"й4гн",
"й4гп",
"й4гр",
"й4гс",
"й4гт",
"й4гф",
"й4гх",
"й4гц",
"й4гч",
"й4гш",
"й4гщ",
"й4дб",
"й4дв",
"й4дг",
"й4дд",
"й4дж",
"й4дз",
"й4дй",
"й4дк",
"й4дл",
"й4дм",
"й4дн",
"й4дп",
"й4др",
"й4дс",
"й4дт",
"й4дф",
"й4дх",
"й4дц",
"й4дч",
"й4дш",
"й4дщ",
"й4жб",
"й4жв",
"й4жг",
"й4жд",
"й4жж",
"й4жз",
"й4жй",
"й4жк",
"й4жл",
"й4жм",
"й4жн",
"й4жп",
"й4жр",
"й4жс",
"й4жт",
"й4жф",
"й4жх",
"й4жц",
"й4жч",
"й4жш",
"й4жщ",
"й4зб",
"й4зв",
"й4зг",
"й4зд",
"й4зж",
"й4зз",
"й4зй",
"й4зк",
"й4зл",
"й4зм",
"й4зн",
"й4зп",
"й4зр",
"й4зс",
"й4зт",
"й4зф",
"й4зх",
"й4зц",
"й4зч",
"й4зш",
"й4зщ",
"й4йб",
"й4йв",
"й4йг",
"й4йд",
"й4йж",
"й4йз",
"й4йй",
"й4йк",
"й4йл",
"й4йм",
"й4йн",
"й4йп",
"й4йр",
"й4йс",
"й4йт",
"й4йф",
"й4йх",
"й4йц",
"й4йч",
"й4йш",
"й4йщ",
"й4кб",
"й4кв",
"й4кг",
"й4кд",
"й4кж",
"й4кз",
"й4кй",
"й4кк",
"й4кл",
"й4км",
"й4кн",
"й4кп",
"й4кр",
"й4кс",
"й4кт",
"й4кф",
"й4кх",
"й4кц",
"й4кч",
"й4кш",
"й4кщ",
"й4лб",
"й4лв",
"й4лг",
"й4лд",
"й4лж",
"й4лз",
"й4лй",
"й4лк",
"й4лл",
"й4лм",
"й4лн",
"й4лп",
"й4лр",
"й4лс",
"й4лт",
"й4лф",
"й4лх",
"й4лц",
"й4лч",
"й4лш",
"й4лщ",
"й4мб",
"й4мв",
"й4мг",
"й4мд",
"й4мж",
"й4мз",
"й4мй",
"й4мк",
"й4мл",
"й4мм",
"й4мн",
"й4мп",
"й4мр",
"й4мс",
"й4мт",
"й4мф",
"й4мх",
"й4мц",
"й4мч",
"й4мш",
"й4мщ",
"й4нб",
"й4нв",
"й4нг",
"й4нд",
"й4нж",
"й4нз",
"й4нй",
"й4нк",
"й4нл",
"й4нм",
"й4нн",
"й4нп",
"й4нр",
"й4нс",
"й4нт",
"й4нф",
"й4нх",
"й4нц",
"й4нч",
"й4нш",
"й4нщ",
"й4пб",
"й4пв",
"й4пг",
"й4пд",
"й4пж",
"й4пз",
"й4пй",
"й4пк",
"й4пл",
"й4пм",
"й4пн",
"й4пп",
"й4пр",
"й4пс",
"й4пт",
"й4пф",
"й4пх",
"й4пц",
"й4пч",
"й4пш",
"й4пщ",
"й4рб",
"й4рв",
"й4рг",
"й4рд",
"й4рж",
"й4рз",
"й4рй",
"й4рк",
"й4рл",
"й4рм",
"й4рн",
"й4рп",
"й4рр",
"й4рс",
"й4рт",
"й4рф",
"й4рх",
"й4рц",
"й4рч",
"й4рш",
"й4рщ",
"й4сб",
"й4св",
"й4сг",
"й4сд",
"й4сж",
"й4сз",
"й4сй",
"й4ск",
"й4сл",
"й4см",
"й4сн",
"й4сп",
"й4ср",
"й4сс",
"й4ст",
"й4сф",
"й4сх",
"й4сц",
"й4сч",
"й4сш",
"й4сщ",
"й4тб",
"й4тв",
"й4тг",
"й4тд",
"й4тж",
"й4тз",
"й4тй",
"й4тк",
"й4тл",
"й4тм",
"й4тн",
"й4тп",
"й4тр",
"й4тс",
"й4тт",
"й4тф",
"й4тх",
"й4тц",
"й4тч",
"й4тш",
"й4тщ",
"й4фб",
"й4фв",
"й4фг",
"й4фд",
"й4фж",
"й4фз",
"й4фй",
"й4фк",
"й4фл",
"й4фм",
"й4фн",
"й4фп",
"й4фр",
"й4фс",
"й4фт",
"й4фф",
"й4фх",
"й4фц",
"й4фч",
"й4фш",
"й4фщ",
"й4хб",
"й4хв",
"й4хг",
"й4хд",
"й4хж",
"й4хз",
"й4хй",
"й4хк",
"й4хл",
"й4хм",
"й4хн",
"й4хп",
"й4хр",
"й4хс",
"й4хт",
"й4хф",
"й4хх",
"й4хц",
"й4хч",
"й4хш",
"й4хщ",
"й4цб",
"й4цв",
"й4цг",
"й4цд",
"й4цж",
"й4цз",
"й4цй",
"й4цк",
"й4цл",
"й4цм",
"й4цн",
"й4цп",
"й4цр",
"й4цс",
"й4цт",
"й4цф",
"й4цх",
"й4цц",
"й4цч",
"й4цш",
"й4цщ",
"й4чб",
"й4чв",
"й4чг",
"й4чд",
"й4чж",
"й4чз",
"й4чй",
"й4чк",
"й4чл",
"й4чм",
"й4чн",
"й4чп",
"й4чр",
"й4чс",
"й4чт",
"й4чф",
"й4чх",
"й4чц",
"й4чч",
"й4чш",
"й4чщ",
"й4шб",
"й4шв",
"й4шг",
"й4шд",
"й4шж",
"й4шз",
"й4шй",
"й4шк",
"й4шл",
"й4шм",
"й4шн",
"й4шп",
"й4шр",
"й4шс",
"й4шт",
"й4шф",
"й4шх",
"й4шц",
"й4шч",
"й4шш",
"й4шщ",
"й4щб",
"й4щв",
"й4щг",
"й4щд",
"й4щж",
"й4щз",
"й4щй",
"й4щк",
"й4щл",
"й4щм",
"й4щн",
"й4щп",
"й4щр",
"й4щс",
"й4щт",
"й4щф",
"й4щх",
"й4щц",
"й4щч",
"й4щш",
"й4щщ",
"б4ь",
"в4ь",
"г4ь",
"д4ь",
"ж4ь",
"з4ь",
"й4ь",
"к4ь",
"л4ь",
"м4ь",
"н4ь",
"п4ь",
"р4ь",
"с4ь",
"т4ь",
"ф4ь",
"х4ь",
"ц4ь",
"ч4ь",
"ш4ь",
"щ4ь",
"ь4ь",
".дз4в",
".дж4р",
".дж4л",
".вг4л",
".вд4л",
".вг4р",
".вг4н",
".вп4л",
".вк4л",
".вк4р",
".вт4р",
".сг4л",
".зд4р",
".сг4р",
".сб4р",
".сд4р",
".жд4р",
".ск4л",
".сп4л",
".сп4р",
".ст4р",
".ск4р",
".шп4р",
".ск4в",
".вз4р",
".вс4л",
".вс4м",
".вс4р",
".св4р",
".сх4л",
".сх4р",
".хв4р",
".вс4т",
".сх4в",
".см4р",
"н4кт.",
"н4кс.",
"к4ст.",
}
|
--[[buttonData = {
type = "button",
name = "My Button", -- string id or function returning a string
func = function() end,
tooltip = "Button's tooltip text.", -- string id or function returning a string (optional)
width = "full", -- or "half" (optional)
disabled = function() return db.someBooleanSetting end, -- or boolean (optional)
icon = "icon\\path.dds", -- (optional)
isDangerous = false, -- boolean, if set to true, the button text will be red and a confirmation dialog with the button label and warning text will show on click before the callback is executed (optional)
warning = "Will need to reload the UI.", -- (optional)
reference = "MyAddonButton", -- unique global reference to control (optional)
} ]]
local widgetVersion = 11
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("button", widgetVersion) then return end
local wm = WINDOW_MANAGER
local function UpdateDisabled(control)
local disable = control.data.disabled
if type(disable) == "function" then
disable = disable()
end
control.button:SetEnabled(not disable)
end
--controlName is optional
local MIN_HEIGHT = 28 -- default_button height
local HALF_WIDTH_LINE_SPACING = 2
function LAMCreateControl.button(parent, buttonData, controlName)
local control = LAM.util.CreateBaseControl(parent, buttonData, controlName)
control:SetMouseEnabled(true)
local width = control:GetWidth()
if control.isHalfWidth then
control:SetDimensions(width / 2, MIN_HEIGHT * 2 + HALF_WIDTH_LINE_SPACING)
else
control:SetDimensions(width, MIN_HEIGHT)
end
if buttonData.icon then
control.button = wm:CreateControl(nil, control, CT_BUTTON)
control.button:SetDimensions(26, 26)
control.button:SetNormalTexture(buttonData.icon)
control.button:SetPressedOffset(2, 2)
else
--control.button = wm:CreateControlFromVirtual(controlName.."Button", control, "ZO_DefaultButton")
control.button = wm:CreateControlFromVirtual(nil, control, "ZO_DefaultButton")
control.button:SetWidth(width / 3)
control.button:SetText(LAM.util.GetStringFromValue(buttonData.name))
if buttonData.isDangerous then control.button:SetNormalFontColor(ZO_ERROR_COLOR:UnpackRGBA()) end
end
local button = control.button
button:SetAnchor(control.isHalfWidth and CENTER or RIGHT)
button:SetClickSound("Click")
button.data = {tooltipText = LAM.util.GetStringFromValue(buttonData.tooltip)}
button:SetHandler("OnMouseEnter", ZO_Options_OnMouseEnter)
button:SetHandler("OnMouseExit", ZO_Options_OnMouseExit)
button:SetHandler("OnClicked", function(...)
local args = {...}
local function callback()
buttonData.func(unpack(args))
LAM.util.RequestRefreshIfNeeded(control)
end
if(buttonData.isDangerous) then
local title = LAM.util.GetStringFromValue(buttonData.name)
local body = LAM.util.GetStringFromValue(buttonData.warning)
LAM.util.ShowConfirmationDialog(title, body, callback)
else
callback()
end
end)
if buttonData.warning ~= nil then
control.warning = wm:CreateControlFromVirtual(nil, control, "ZO_Options_WarningIcon")
control.warning:SetAnchor(RIGHT, button, LEFT, -5, 0)
control.UpdateWarning = LAM.util.UpdateWarning
control:UpdateWarning()
end
if buttonData.disabled ~= nil then
control.UpdateDisabled = UpdateDisabled
control:UpdateDisabled()
end
LAM.util.RegisterForRefreshIfNeeded(control)
return control
end
|
require("moonsc").import_tags()
-- Test that eventless transitions take precedence over event-driven ones
return _scxml{ initial="s1",
_state{ id="s1",
_onentry{
_raise{ event="internalEvent" },
_send{ event="externalEvent" },
},
_transition{ event="*", target="fail" },
_transition{ target="pass" },
},
_final{id='pass'},
_final{id='fail'},
}
|
--[[-----------------------------------------------------------------------------------------------------------------------
Display all chat commands
-----------------------------------------------------------------------------------------------------------------------]]--
local PLUGIN = {}
PLUGIN.Title = "Chatcommands"
PLUGIN.Description = "Display all available chat commands."
PLUGIN.Author = "Overv"
PLUGIN.ChatCommand = "commands"
if SERVER then
util.AddNetworkString( "EV_CommandStart" )
util.AddNetworkString( "EV_CommandEnd" )
util.AddNetworkString( "EV_Command" )
end
function PLUGIN:Call( ply, args )
local commands = table.Copy( evolve.plugins )
table.sort( commands, function( a, b )
local cmdA, cmdB = ( a.ChatCommand or "" ), ( b.ChatCommand or "" )
if ( type(cmdA) == "table" ) then cmdA = cmdA[1] end
if ( type(cmdB) == "table" ) then cmdB = cmdB[1] end
return cmdA < cmdB
end )
if ( ply:IsValid() ) then
net.Start( "EV_CommandStart" ) net.Send( ply )
for _, plug in ipairs( commands ) do
if ( plug.ChatCommand ) then
if ( type( plug.ChatCommand ) == "string" ) then
net.Start( "EV_Command" )
net.WriteString( plug.ChatCommand )
net.WriteString( tostring( plug.Usage ) )
net.WriteString( plug.Description )
net.Send( ply )
elseif ( type( plug.ChatCommand ) == "table" ) then
for _, cmd in pairs( plug.ChatCommand ) do
net.Start( "EV_Command" )
net.WriteString( cmd )
net.WriteString( tostring( plug.Usage ) )
net.WriteString( plug.Description )
net.Send( ply )
end
end
end
end
net.Start( "EV_CommandEnd") net.Send( ply )
evolve:Notify( ply, evolve.colors.white, "All chat commands have been printed to your console." )
else
for _, plugin in ipairs( commands ) do
if ( plugin.ChatCommand ) then
if ( plugin.Usage ) then
print( "!" .. plugin.ChatCommand .. " " .. plugin.Usage .. " - " .. plugin.Description )
else
print( "!" .. plugin.ChatCommand .. " - " .. plugin.Description )
end
end
end
end
end
net.Receive( "EV_CommandStart", function( len )
print( "\n============ Available chat commands for Evolve ============\n" )
end )
net.Receive( "EV_CommandEnd", function( len )
print( "" )
end )
net.Receive( "EV_Command", function( len )
local com = net.ReadString()
local usage = net.ReadString()
local desc = net.ReadString()
if ( usage != "nil" ) then
print( "!" .. com .. " " .. usage .. " - " .. desc )
else
print( "!" .. com .. " - " .. desc )
end
end )
evolve:RegisterPlugin( PLUGIN ) |
local skynet = require "skynet"
local netpack = require "netpack"
local socket = require "socket"
local protobufload = require "protobufload"
local logstat = require "base.logstat"
local p_core=require "p.core"
local player = require "npc.player"
local define_battle = require "define.define_battle"
local battle_send = require "battle.battle_send"
local pload = protobufload.inst()
require "struct.globle"
---------------------------------------------------------------------------
local DEBUG_MOVE = function (...) logstat.log_file2("move.txt",...) end
local DEBUG_MOVE_TABLE = function (table) logstat.log_file_r("move.txt",table) end
local DEBUG_COUNT = function (...) logstat.log_file2("count.txt",...) end
----------------------------------------------------------------------------
local battle = {}
local mt = { __index = battle }
function battle.new ()
o = o or {} -- create object if user does not provide one
setmetatable (o, mt)
o:set_init(0)
return o
end
function battle:set_obj(card,oid)
self.objsmap[oid]=card
end
function battle:get_obj(oid)
return self.objsmap[oid]
end
function battle:get_player(userId)
return self.playMap[userId]
end
function battle:init(agent,userId,agent2,userId2)
self.isinit = 0
logstat.log_day("battle","battle:init! \n")
self.send_users = {} --发送方包括观战者
self.player_me = player.new()
self.player_other = player.new()
self.player_me:init(agent,userId)
self.player_other:init(agent2,userId2)
self.playMap = {}
self.playMap[userId] = self.player_me
self.playMap[userId2] = self.player_other
self.turn_time = 0
print("userId:"..userId..",userId2:"..userId2)
self:get_fighter(userId)
self:get_fighter(userId2)
if userId == 1 then
self.npc = self.player_me
else
self.npc = self.player_other
end
-- 战场区域
-- front_begin == uid 从上而下从左向右索引递增,否则从下向上从右向左递增
-- front_begin == uid 的排列:
-- 1 2 3 4 5 6
-- 7 8 9 10 11 12
-- 13 14 15 16 17 18
-- front_begin != uid的排列:
-- 18 17 16 15 14 13
-- 12 11 10 9 8 7
-- 6 5 4 3 2 1
self.front_begin = 0
--战场牌序
self.front = {0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0
}
---------------------------------------------------------------------------------
--状态控制
self.war_stutas = 0 --战场阶段
self.turn_stutas = 0 -- 回合下一个阶段
self.cur_turn_stutas = 0 --当前回合阶段
self.turn_time = 0 --回合阶段结束时间点
self.turn = 0 --Aid , Bid
self.another_ok = 0 --一方确认开始,等待另一个或时间结束
self.first_turn = 0 --标记第一回合
self.winner= nil --胜利玩家id
self.mpdata = {}
self.mpdata[userId] = {}
self.mpdata[userId]["crd"]={}
self.mpdata[userId]["cmd"]={}
self.mpdata[userId]["hnd"]={}
self.mpdata[userId]["stk"] = {}
self.mpdata[userId]["dep"] = {}
self.mpdata[userId]["dis"] = {}
self.mpdata[userId]["std"]={}
self.mpdata[userId]["mrc"]=0
self.mpdata[userId]["rc"]=0
self.mpdata[userId2] = {}
self.mpdata[userId2]["crd"]={}
self.mpdata[userId2]["cmd"]={}
self.mpdata[userId2]["hnd"]={}
self.mpdata[userId2]["stk"] = {}
self.mpdata[userId2]["dep"] = {}
self.mpdata[userId2]["dis"] = {}
self.mpdata[userId2]["std"]={}
self.mpdata[userId2]["mrc"]=0
self.mpdata[userId2]["rc"]=0
self:enter_war()
self.isinit = 1
end
function battle:get_front_begin()
return self.front_begin
end
function battle:get_front_begin()
return self.front_begin
end
function battle:set_front_begin(value)
self.front_begin = value
end
function battle:set_front(card,pos)
if card~=nil then
self.front[pos] = card
else
self.front[pos] = 0
end
if card~=nil and card~=0 then
card:set_pos(pos)
--DEBUG_MOVE("set_front",card:get_id(),card:get_uid(),card:get_pos())
end
end
function battle:get_front(pos)
-- if self.front[pos]~=0 then
-- DEBUG_MOVE(self.front[pos]:get_id())
-- end
return self.front[pos]
end
function battle:get_fronts()
return self.front
end
function battle:get_first_turn()
return self.first_turn
end
function battle:set_first_turn( value )
self.first_turn = value
end
function battle:get_turn()
return self.turn
end
function battle:set_init(value)
self.isinit = value
end
function battle:IsInit()
return self.isinit
end
function battle:get_turn_time()
return self.turn_time
end
function battle:set_turn_time(value)
self.turn_time = value
end
function battle:set_front_begin(value)
self.front_begin = value
battle_send.front_begin(self,value)
end
function battle:set_turn(value)
self.turn = value
battle_send.set_turn(self,value)
end
function battle:set_war_stutas( value)
self.war_stutas = value
end
--服务器下一个状态
function battle:set_turn_stutas( value)
self.turn_time = 0;
self.turn_stutas = value
end
function battle:add_send_users( value )
if value:get_userid() ~=1 then
table.insert(self.send_users,value)
end
end
function battle:sub_send_users( value )
for _,user in ipairs(self.send_users) do
if value:get_userid() == user:get_userid() then
table.remove(self.send_users,value)
end
end
end
function battle:get_send_users()
return self.send_users
end
function battle:set_cur_stutas(value)
self.cur_turn_stutas = value
end
function battle:get_cur_stutas(value)
return self.cur_turn_stutas
end
function battle:get_turn_stutas()
return self.turn_stutas
end
function battle:get_npc()
return self.npc
end
function battle:set_npc( value )
self.npc = value
end
function battle:set_another_ok( value)
self.another_ok = value
end
function battle:get_another_ok()
return self.another_ok
end
function battle:get_send_users()
return self.send_users
end
--双方进入牌局
function battle:enter_war()
logstat.log_day("battle","enter_war!\n")
self.player_me:set_battle(self)
self.player_other:set_battle(self)
self:add_send_users(self.player_me)
self:add_send_users(self.player_other)
self:init_ply_info(self.player_me)
self:init_ply_info(self.player_other)
self:set_front_begin(self.player_other:get_userid())
self:set_turn(self.player_me:get_userid())
self:set_first_turn(1)
self:set_war_stutas(define_battle.WAR_READY); -- 战斗准备
self:set_turn_stutas(define_battle.JIEDUAN_HUIHE_KAISHI)
self:set_cur_stutas(define_battle.JIEDUAN_CHUSHIHUA)
self:set_turn_time(os.time() + 1) -- 当前阶段结束时间点
if self:get_npc() then
self:set_another_ok(1)
end
----------------------发送初始化消息---------------------------------------------------
self.player_me:send_user_info(self.send_users)
self.player_other:send_user_info(self.send_users)
battle_send.cur_stutas(self,self:get_cur_stutas(),0)
battle_send.set_turn(self,self:get_turn())
battle_send.cur_stutas(self,self:get_cur_stutas(),1)
------------------------------------------------------------------------------------
end
--==================== 发送协议 start ====================
--初始化手牌,牌库,装备
function battle:init_ply_info( me)
me:init_crd()
me:init_cmd()
me:init_hand()
end
function battle:send(users,code,msg)
print("player:send:"..code)
print("--------------------------------------")
for _,user in ipairs(users) do
print("send user.agent:"..user:get_agent())
skynet.call(tonumber(user:get_agent()), "lua", "send",code,msg)
--skynet.call(agent[fd], "lua", "start", gate, fd,gamed)
end
end
function battle:get_fighter(userId)
local user,k
for k,user in pairs(self.playMap) do
if k ~= userId then
return k
end
end
return 0
end
function battle:get_winner()
return self.winner
end
function battle:set_winner(userId)
self.winner = userId
end
function battle:set_obj(card,oid)
if _G.objsmap==nil then
_G.objsmap = {}
end
_G.objsmap[oid]=card;
end
--------------------------------------------------------------------
-- 最大血量
function battle:get_mhp( id)
local me
if ~self.isinit then
return 0
end
if(self.id_1~=id)and(self.id_2~=id) then
return 0
end
me = self.playMap[id]
return card:get_mhp()
end
--最大血量
function battle:add_mhp(id, value, times)
local me
if ~self.isinit then
return 0;
end
if(self.id_1~=id)and(self.id_2~=id) then
return 0
end
me = self.playMap[id]
if value>0 then
me:add_hp(value)
end
end
function battle:set_mhp( id, i)
local me
if ~self.isinit then
return 0
end
me = self.playMap[id]
me:set_mhp(i)
end
-- // =======================================================================
-- // 当前血量
function battle:get_hp( id)
local me
if ~self.isinit then
return 0
end
me = self:get_player(id)
return me:get_hp()
end
function battle:set_hp( id, i)
local me
if ~self.isinit then
return 0
end
me = self.playMap[id]
me:set_hp(i)
-- send_user(war->get_send_users(),"%d%d%d",0x2011, id,CARD_CLASS->get_hp(card) );
end
function battle:add_hp( id, value)
local card,me
DEBUG_COUNT("battle:add_hp",id,value,self.isinit)
if self.isinit == 0 then
return 0
end
me = self:get_player(id)
me:set_hp(me:get_hp()+value)
--send_user(this_object()->get_send_users(),"%d%d%d",0x2011, id,CARD_CLASS->get_hp(card) );
end
--------------------------------------------------------------------------------------------------
--发送牌库信息
function battle_send.card_dead(war,m_user_id,m_cardid,m_pos)
local msg = pload.encode("game.card_dead",{
cardid = m_cardid;
pos =m_pos;
user_id = m_user_id;
})
local d_msg = pload.decode("game.card_dead",msg)
print_r(d_msg)
war:send(war:get_send_users(),4019,msg)
DEBUG_MOVE("card_dead",m_user_id,m_cardid,m_pos)
end
return battle |
--------------------------------------------------------------------------
-- This is a derived class from MF_Base. This classes knows how
-- to expand the environment variables into Lua syntax.
-- @classmod MF_Lua
require("strict")
--------------------------------------------------------------------------
-- Lmod License
--------------------------------------------------------------------------
--
-- Lmod is licensed under the terms of the MIT license reproduced below.
-- This means that Lmod is free software and can be used for both academic
-- and commercial purposes at absolutely no cost.
--
-- ----------------------------------------------------------------------
--
-- Copyright (C) 2008-2018 Robert McLay
--
-- 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.
--
--------------------------------------------------------------------------
local MF_Lmod = inheritsFrom(MF_Base)
local dbg = require("Dbg"):dbg()
local concatTbl = table.concat
MF_Lmod.my_name = "Lmod"
--------------------------------------------------------------------------
-- generate string for setenv write in Lua.
-- @param self MF_Lua object
-- @param k key
-- @param v value
function MF_Lmod.setenv(self, k, v)
return "setenv(" .. k:doubleQuoteString() .. "," .. v:doubleQuoteString() .. ")"
end
--------------------------------------------------------------------------
-- generate string for prepend_path write in Lua.
-- @param self MF_Lua object
-- @param k key
-- @param v value
function MF_Lmod.prepend_path(self, k, v)
return "prepend_path(" .. k:doubleQuoteString() .. "," .. v:doubleQuoteString() .. ")"
end
--------------------------------------------------------------------------
-- generate string for append_path write in Lua.
-- @param self MF_Lua object
-- @param k key
-- @param v value
function MF_Lmod.append_path(self, k, v)
return "append_path(" .. k:doubleQuoteString() .. "," .. v:doubleQuoteString() .. ")"
end
return MF_Lmod
|
/*---------------------------------------------------------
Initializes the effect. The data is a table of data
which was passed from the server.
---------------------------------------------------------*/
function EFFECT:Init( data )
local Gun = data:GetEntity()
local Propellant = data:GetScale() or 1
local ReloadTime = data:GetMagnitude() or 1
local Class = Gun.Class
local FlashClass = Gun.FlashClass
local RoundType = ACF.IdRounds[data:GetSurfaceProp()] or "AP"
local PosOverride = data:GetOrigin()
--print(PosOverride)
local FromAnimationEvent = data:GetMaterialIndex() or 0
if FromAnimationEvent < 1 then
FromAnimationEvent = false
end
if not ACF.Classes.GunClass[Class] then
Class = "C"
end
local GunSound = Gun:GetNWString( "Sound" ) or ACF.Classes["GunClass"][Class]["sound"] or ""
if Gun:IsValid() then
local lply = false
if CLIENT and LocalPlayer() == Gun.Owner then
if not FromAnimationEvent then return end
lply = true
end
if Propellant > 0 then
local SoundPressure = (Propellant*1000)^0.5
Muzzle =
{
Pos = Gun.Owner:GetShootPos(),
Ang = Gun.Owner:EyeAngles()
}
Gun:EmitSound( GunSound, math.Clamp(SoundPressure,75,255), math.Clamp(100,15,255), 1, CHAN_WEAPON )
//sound.Play( GunSound, Muzzle.Pos , math.Clamp(SoundPressure,75,255), math.Clamp(100,15,255))
if not ((Class == "MG") or (Class == "RAC")) then
//sound.Play( GunSound, Muzzle.Pos , math.Clamp(SoundPressure,75,255), math.Clamp(100,15,255))
Gun:EmitSound( GunSound, math.Clamp(SoundPressure,75,255), math.Clamp(100,15,255), 1, CHAN_WEAPON )
end
local aimoffset = Gun.AimOffset or Vector()
--local muzzoffset
if FromAnimationEvent == 5003 then
Muzzle.Pos = PosOverride
--muzzoffset = Vector(0,0,0)
elseif FromAnimationEvent == 5001 then
local mdl = Gun.Owner:GetViewModel()
Muzzle.Pos = mdl:GetAttachment(1).Pos
--muzzoffset = Vector(0,0,0)
end
--Muzzle.Pos = Muzzle.Pos + muzzoffset
local flash = ACF.Classes["GunClass"][FlashClass]["muzzleflash"]
ParticleEffect( flash, Muzzle.Pos, Muzzle.Ang, Gun )
if Gun.Launcher then
local muzzoffset = (Muzzle.Ang:Forward() * -aimoffset.x) + (Muzzle.Ang:Right() * aimoffset.y) + (Muzzle.Ang:Up() * aimoffset.z)
Muzzle.Pos = Gun.Owner:GetShootPos() + muzzoffset
Muzzle.Ang = (-Muzzle.Ang:Forward()):Angle()
ParticleEffect( flash, Muzzle.Pos, Muzzle.Ang, Gun )
end
end
end
end
/*---------------------------------------------------------
THINK
---------------------------------------------------------*/
function EFFECT:Think( )
return false
end
/*---------------------------------------------------------
Draw the effect
---------------------------------------------------------*/
function EFFECT:Render()
end |
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local lib = ReplicatedStorage.lib
local component = script.Parent
local view = component.view
local Roact = require(lib.Roact)
local App = Roact.Component:extend("App")
local Inventory = require(view.Inventory)
local Crafting = require(view.Crafting)
local Boosts = require(view.Boosts)
local Codes = require(view.Codes)
local Options = require(view.Options)
local Tooltip = require(component.Tooltip)
local MenuBar = require(component.MenuBar)
local HealthBar = require(component.HealthBar)
local NotificationContainer = require(component.NotificationContainer)
local AlphaWarning = require(component.AlphaWarning)
local AttackButton = require(component.AttackButton)
--local Toolbar = require(uiComponents.Toolbar)
function App:init()
self._context.pzCore = self.props.pzCore
end
function App:didMount()
end
function App:render()
local elements = {
inventory = Roact.createElement(Inventory),
crafting = Roact.createElement(Crafting),
boosts = Roact.createElement(Boosts),
codes = Roact.createElement(Codes),
options = Roact.createElement(Options),
tooltip = Roact.createElement(Tooltip),
menubar = Roact.createElement(MenuBar),
healthbar = Roact.createElement(HealthBar),
notificationContainer = Roact.createElement(NotificationContainer),
alphaWarning = Roact.createElement(AlphaWarning),
attackButton = Roact.createElement(AttackButton),
-- toolbar = Roact.createElement(Toolbar),
}
return Roact.createElement("ScreenGui",{
ResetOnSpawn = false,
ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
}, elements)
end
return App |
local keyTable = {
INPUT_KEY_UNKNOWN = -1,
INPUT_KEY_SPACE = 32,
INPUT_KEY_APOSTROPHE = 39,
INPUT_KEY_COMMA = 44,
INPUT_KEY_MINUS = 45,
INPUT_KEY_PERIOD = 46,
INPUT_KEY_SLASH = 47,
INPUT_KEY_0 = 48,
INPUT_KEY_1 = 49,
INPUT_KEY_2 = 50,
INPUT_KEY_3 = 51,
INPUT_KEY_4 = 52,
INPUT_KEY_5 = 53,
INPUT_KEY_6 = 54,
INPUT_KEY_7 = 55,
INPUT_KEY_8 = 56,
INPUT_KEY_9 = 57,
INPUT_KEY_SEMICOLON = 59,
INPUT_KEY_EQUAL = 61,
INPUT_KEY_A = 65,
INPUT_KEY_B = 66,
INPUT_KEY_C = 67,
INPUT_KEY_D = 68,
INPUT_KEY_E = 69,
INPUT_KEY_F = 70,
INPUT_KEY_G = 71,
INPUT_KEY_H = 72,
INPUT_KEY_I = 73,
INPUT_KEY_J = 74,
INPUT_KEY_K = 75,
INPUT_KEY_L = 76,
INPUT_KEY_M = 77,
INPUT_KEY_N = 78,
INPUT_KEY_O = 79,
INPUT_KEY_P = 80,
INPUT_KEY_Q = 81,
INPUT_KEY_R = 82,
INPUT_KEY_S = 83,
INPUT_KEY_T = 84,
INPUT_KEY_U = 85,
INPUT_KEY_V = 86,
INPUT_KEY_W = 87,
INPUT_KEY_X = 88,
INPUT_KEY_Y = 89,
INPUT_KEY_Z = 90,
INPUT_KEY_LEFT_BRACKET = 91,
INPUT_KEY_BACKSLASH = 92,
INPUT_KEY_RIGHT_BRACKET = 93,
INPUT_KEY_GRAVE_ACCENT = 96,
INPUT_KEY_ESCAPE = 256,
INPUT_KEY_ENTER = 257,
INPUT_KEY_TAB = 258,
INPUT_KEY_BACKSPACE = 259,
INPUT_KEY_INSERT = 260,
INPUT_KEY_DELETE = 261,
INPUT_KEY_RIGHT = 262,
INPUT_KEY_LEFT = 263,
INPUT_KEY_DOWN = 264,
INPUT_KEY_UP = 265,
INPUT_KEY_PAGE_UP = 266,
INPUT_KEY_PAGE_DOWN = 267,
INPUT_KEY_HOME = 268,
INPUT_KEY_END = 269,
INPUT_KEY_CAPS_LOCK = 280,
INPUT_KEY_SCROLL_LOCK = 281,
INPUT_KEY_NUM_LOCK = 282,
INPUT_KEY_PRINT_SCREEN = 283,
INPUT_KEY_PAUSE = 284,
INPUT_KEY_F1 = 290,
INPUT_KEY_F2 = 291,
INPUT_KEY_F3 = 292,
INPUT_KEY_F4 = 293,
INPUT_KEY_F5 = 294,
INPUT_KEY_F6 = 295,
INPUT_KEY_F7 = 296,
INPUT_KEY_F8 = 297,
INPUT_KEY_F9 = 298,
INPUT_KEY_F10 = 299,
INPUT_KEY_F11 = 300,
INPUT_KEY_F12 = 301,
INPUT_KEY_F13 = 302,
INPUT_KEY_F14 = 303,
INPUT_KEY_F15 = 304,
INPUT_KEY_F16 = 305,
INPUT_KEY_F17 = 306,
INPUT_KEY_F18 = 307,
INPUT_KEY_F19 = 308,
INPUT_KEY_F20 = 309,
INPUT_KEY_F21 = 310,
INPUT_KEY_F22 = 311,
INPUT_KEY_F23 = 312,
INPUT_KEY_F24 = 313,
INPUT_KEY_F25 = 314,
INPUT_KEY_KP_0 = 320,
INPUT_KEY_KP_1 = 321,
INPUT_KEY_KP_2 = 322,
INPUT_KEY_KP_3 = 323,
INPUT_KEY_KP_4 = 324,
INPUT_KEY_KP_5 = 325,
INPUT_KEY_KP_6 = 326,
INPUT_KEY_KP_7 = 327,
INPUT_KEY_KP_8 = 328,
INPUT_KEY_KP_9 = 329,
INPUT_KEY_KP_DECIMAL = 330,
INPUT_KEY_KP_DIVIDE = 331,
INPUT_KEY_KP_MULTIPLY = 332,
INPUT_KEY_KP_SUBTRACT = 333,
INPUT_KEY_KP_ADD = 334,
INPUT_KEY_KP_ENTER = 335,
INPUT_KEY_KP_EQUAL = 336,
INPUT_KEY_LEFT_SHIFT = 340,
INPUT_KEY_LEFT_CONTROL = 341,
INPUT_KEY_LEFT_ALT = 342,
INPUT_KEY_RIGHT_SHIFT = 344,
INPUT_KEY_RIGHT_CONTROL = 345,
INPUT_KEY_RIGHT_ALT = 346,
INPUT_MOUSE_BUTTON_LEFT = 0,
INPUT_MOUSE_BUTTON_RIGHT = 1,
INPUT_MOUSE_BUTTON_MIDDLE = 2,
INPUT_MOUSE_BUTTON_4 = 3,
INPUT_MOUSE_BUTTON_5 = 4,
INPUT_MOUSE_BUTTON_6 = 5,
INPUT_MOUSE_BUTTON_7 = 6,
INPUT_MOUSE_BUTTON_8 = 7,
}
return keyTable; |
--- 属性系统,事件密切的功能扩展支持的事件
hattribute.xtrasSupportEvents = {
CONST_EVENT.attack, CONST_EVENT.beAttack,
CONST_EVENT.skill, CONST_EVENT.beSkill,
CONST_EVENT.item, CONST_EVENT.beItem,
CONST_EVENT.damage, CONST_EVENT.beDamage,
CONST_EVENT.attackDetect, CONST_EVENT.attackGetTarget, CONST_EVENT.beAttackReady,
CONST_EVENT.skillStudy, CONST_EVENT.skillReady, CONST_EVENT.skillCast, CONST_EVENT.skillEffect, CONST_EVENT.skillStop, CONST_EVENT.skillFinish,
CONST_EVENT.itemUsed, CONST_EVENT.itemSell, CONST_EVENT.unitSell, CONST_EVENT.itemDrop, CONST_EVENT.itemPawn, CONST_EVENT.itemGet,
CONST_EVENT.itemSynthesis, CONST_EVENT.itemOverWeight, CONST_EVENT.itemOverSlot,
CONST_EVENT.damageResistance,
CONST_EVENT.avoid, CONST_EVENT.beAvoid, CONST_EVENT.breakArmor, CONST_EVENT.beBreakArmor,
CONST_EVENT.swim, CONST_EVENT.beSwim, CONST_EVENT.broken, CONST_EVENT.beBroken,
CONST_EVENT.silent, CONST_EVENT.beSilent, CONST_EVENT.unarm, CONST_EVENT.beUnarm, CONST_EVENT.fetter, CONST_EVENT.beFetter,
CONST_EVENT.bomb, CONST_EVENT.beBomb,
CONST_EVENT.lightningChain, CONST_EVENT.beLightningChain,
CONST_EVENT.crackFly, CONST_EVENT.beCrackFly,
CONST_EVENT.rebound, CONST_EVENT.beRebound,
CONST_EVENT.knocking, CONST_EVENT.beKnocking,
CONST_EVENT.split, CONST_EVENT.beSplit,
CONST_EVENT.hemophagia, CONST_EVENT.beHemophagia, CONST_EVENT.skillHemophagia, CONST_EVENT.beSkillHemophagia,
CONST_EVENT.punish, CONST_EVENT.dead, CONST_EVENT.kill, CONST_EVENT.reborn, CONST_EVENT.levelUp,
CONST_EVENT.moveStart, CONST_EVENT.moving, CONST_EVENT.moveStop, CONST_EVENT.holdOn, CONST_EVENT.stop,
}
--- 属性系统,val数据支持的单位属性
hattribute.xtrasSupportVals = {
"life", "mana", "move",
"defend", "defend_white", "defend_green",
"attack", "attack_white", "attack_green", "attack_range", "attack_range_acquire", "attack_space",
"str", "agi", "int", "str_green", "agi_green", "int_green", "str_white", "agi_white", "int_white",
"level",
"gold", "lumber",
}
--- 是否允许死亡单位通过xtras效果验证
---@private
---@param targetUnit userdata 执行单位
---@param type string attr|spec
---@param field string any
---@return boolean
hattribute.xtrasPassAlive = function(targetUnit, type, field)
if (his.alive(targetUnit)) then
return true
end
if (type == 'attr') then
return false
elseif (type == 'spec') then
if (field == 'split' or field == 'bomb' or field == 'paw') then
return true
end
end
return false
end
--- 快速取单位xtras的数据
---@param whichUnit userdata
---@param eventKey string
---@return table
hattribute.getXtras = function(whichUnit, eventKey)
if (whichUnit == nil or eventKey == nil or type(whichUnit) ~= 'userdata') then
return {}
end
if (hunit.getName(whichUnit) == nil) then
return {}
end
local xtras = hattribute.get(whichUnit, 'xtras')
if (xtras == nil or type(xtras) ~= 'table' or #xtras <= 0) then
return {}
end
local xtrasInEvent = {}
for _, x in ipairs(xtras) do
if (eventKey == x._t.on) then
table.insert(xtrasInEvent, x._t)
end
end
return xtrasInEvent
end
--- 判断是否有xtras
---@param whichUnit userdata
---@param eventKey string
---@return table
hattribute.hasXtras = function(whichUnit, eventKey)
return #(hattribute.getXtras(whichUnit, eventKey)) > 0
end
--- 属性系统,事件密切的功能扩展
--- 以事件的handle作为主引导,例如attack事件的引导就是攻击者,而beDamage事件的引导就是受伤者
--- action为字符串分三段:
--- triggerUnit.attr.attack_speed
--- [ 作用目标 ].[类型].[ 效果参数 ]
--- | - [作用目标] 范围是 hevent 回调时 evtData 相关单位
--- | - [类型] 暂分为 attr(属性改动,攻速攻击等) 和 spec(特别效果,暴击击飞等)
--- | - [效果参数] 如attr时,可以填attack_speed改攻速,而effect时可以填knocking触发暴击
--- | - [其他参数] 其他的参数有常规通用的也有固定搭配,请看说明:
--- odds 触发几率>0(%)
--- during 持续时间>0,这个时间在不同场景意义不同(*attr有效、spec里的眩晕、沉默、缴械、定身、击飞有效)
--- effect 特效字符串,主特效
--- effectEnum 特效字符串,选取单位的 (* 爆破有效)
---
--- val 数值或伤害~=0,这个字段可以填数字,在spec时也可填限定特殊的数据,详情如下:
--- 1、数字型,如 100, 50.50
--- 2、字符串 "damage",会自动获取evtData里面的damage数据
--- 3、字符串-目标单位属性段 "targetUnit.attack_white"
--- 以点分隔,上例会自动获取evtData里面的targetUnit单位,并使用它的白字攻击作为数据
--- 第二个属性不能随意调用任意属性,可查看 hattribute.valSupportAttribute
--- 4、字符串-单位等级 "targetUnit.level"
--- 以点分隔,上例会自动获取evtData里面的"targetUnit"单位的单位等级作为数据
--- 这是运用 hhero.getCurLevel
--- 5、字符串-目标玩家属性段 "targetUnit.gold"
--- 以点分隔,上例会自动获取evtData里面的"targetUnit"单位的拥有者,并使用玩家属性作为数据
--- 第二个属性是gold|lumber时自动切换
---
--- percent 程度>0(%) 对val的补充,默认100%,可大于100% (*attr有效、spec里的眩晕、沉默、缴械、定身、击飞有效)
--- 也可填限定特殊的数据,详情如下:
--- 1、数字型,如 100, 50
----- 2、范围型如一个table {10, 90} 表示随机 10%~90%
--- damageSrc 伤害来源(可选的,如果evtData有且无自定义,自动使用)
--- damageType 伤害类型(可选的,如果evtData有且无自定义,自动使用)
--- radius 半径范围>0 (* 分裂、爆破有效)
--- qty 数量>0 (* 只有闪电链有效)
--- rate 增长率(%) (* 只有闪电链有效,负数就是衰减)
--- lightning_type 闪电类型 (* 只有闪电链有效,参考 hlightning.type)
--- distance 距离 (* 只有击飞有效)
--- height 高度 (* 只有击飞有效)
--- 惯用例子:
--- hattr.set(unit, 0, {
-- xtras = {
-- add = {
-- { on = CONST_EVENT.attack, action = "triggerUnit.attr.attack_speed", odds = 20.0, val = 1.5, during = 3.0, effect = nil },
-- { on = CONST_EVENT.attack, action = "attackUnit.attr.attack_speed", odds = 20.0, val = 1.5, during = 3.0, effect = nil },
-- { on = CONST_EVENT.skill, action = "castUnit.attr.attack_green", odds = 20.0, val = 2, during = 3.0, effect = nil },
-- { on = CONST_EVENT.item, action = "useUnit.attr.int_white", odds = 20.0, val = 2, during = 3.0, effect = nil },
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.knocking", odds = 100, percent = 100, effect = nil },
-- { on = CONST_EVENT.skill, action = "targetUnit.spec.violence", odds = 100, percent = 100, effect = nil },
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.split", odds = 100, percent = {30,50}, radius = 250 },
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.swim",odds = 0.0, val = 0.0, during = 0.0, effect = nil},
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.broken",odds = 0.0, val = 0.0, effect = nil},
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.silent",odds = 0.0, val = 0.0, during = 0.0, effect = nil},
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.unarm",odds = 0.0, val = 0.0, during = 0.0, effect = nil},
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.fetter",odds = 0.0, val = 0.0, during = 0.0, effect = nil},
-- { on = CONST_EVENT.attack, action = "targetUnit.spec.bomb",odds = 0.0, radius = 0.0, val = 0.0, effect = nil},
-- { on = CONST_EVENT.damage, action = "targetUnit.spec.lightning_chain", odds = 50, val = 100, qty = 0, rate = 0.0 },
-- { on = CONST_EVENT.beDamage, action = "sourceUnit.spec.crack_fly", odds = 50, val = 100, distance = 300, height = 200, during = 0.5 },
-- { on = CONST_EVENT.attack, action = "sourceUnit.spec.paw", odds = 50, val = 'damage', effect = 'Abilities\\Weapons\\GargoyleMissile\\GargoyleMissile.mdl', radius = 50, odds = 50, speed = 10, deg = 30, distance = 500, qty = 3 },
-- }
-- },
-- })
---@private
hattribute.xtras = function(triggerUnit, eventKey, evtData)
if (triggerUnit == nil or eventKey == nil or evtData == nil) then
return
end
-- 排除不支持的事件
if (table.includes(hattribute.xtrasSupportEvents, eventKey) == false) then
return
end
-- 排除非单位
if (hunit.getName(triggerUnit) == nil) then
return
end
-- 排除死亡单位,删除单位
if (his.dead(triggerUnit) or his.deleted(triggerUnit)) then
return
end
-- 获取属性
local xtras = hattribute.getXtras(triggerUnit, eventKey)
if (#xtras <= 0) then
xtras = nil
return
end
-- 分析默认伤害来源
for _, x in ipairs(xtras) do
local actions = string.explode('.', x.action)
if (#actions == 3) then
local target = actions[1]
local actionType = actions[2]
if (table.includes({ 'attr', 'spec' }, actionType) ~= false and evtData[target] ~= nil and hunit.getName(evtData[target]) ~= nil) then
if (his.deleted(evtData[target]) == false and hattribute.xtrasPassAlive(evtData[target], actions[2], actions[3])) then
local targetUnit = evtData[target]
local actionField = actions[3]
local val = 0
local percent = x.percent or 100
-- 处理数值
if (type(x.val) == 'number') then
val = math.round(x.val)
elseif (type(x.val) == 'string') then
local xVal = x.val
local isNegative = (string.sub(xVal, 1, 1) == '-')
if (isNegative) then
xVal = string.sub(xVal, 2)
end
if (xVal == 'damage') then
val = evtData.damage or 0
else
local valAttr = string.explode('.', xVal)
if (#valAttr == 2) then
local au = evtData[valAttr[1]]
local aa = valAttr[2]
if (au and table.includes(hattribute.xtrasSupportVals, aa)) then
if (aa == 'level') then
val = hhero.getCurLevel(au)
elseif (aa == 'gold') then
val = hplayer.getGold(hunit.getOwner(au))
elseif (aa == 'lumber') then
val = hplayer.getLumber(hunit.getOwner(au))
else
val = hattribute.get(au, aa)
end
end
end
end
if (isNegative) then
val = -val
end
end
-- 处理百分比
if (type(percent) == 'table') then
percent = math.random(percent[1] or 0, percent[2] or 0)
end
if (percent < 0) then
percent = 0
end
val = math.round(val * percent * 0.01)
if (actionType == 'attr') then
-- 属性改动
if (val ~= 0 and (x.during or 0) > 0 and math.random(1, 1000) <= (x.odds or 0) * 10) then
-- 判断是否buff/debuff(判断基准就是判断val是否大于/小于0)
-- buff时,要计算目标单位的buff阻碍(如:可以设计一个boss造成强化阻碍,影响玩家的被动加成)
-- debuff时,要计算目标单位的debuff抵抗(如:可以设计一个物品抵抗debuff,减少影响)
-- 以上两个都是大于0才有效
if (val > 0) then
-- buff; > 0
local buff_oppose = hattribute.get(targetUnit, 'buff_oppose')
if (buff_oppose > 0) then
val = val * (1 - 0.01 * buff_oppose)
end
if (val > 0) then
hattr.set(targetUnit, x.during, { [actionField] = "+" .. val })
if (type(x.effect) == "string" and string.len(x.effect) > 0) then
heffect.bindUnit(x.effect, targetUnit, "origin", x.during)
end
end
else
-- debuff; < 0
local debuff_oppose = hattribute.get(targetUnit, 'debuff_oppose')
if (debuff_oppose > 0) then
val = val * (1 - 0.01 * debuff_oppose)
end
if (val < 0) then
hattr.set(targetUnit, x.during, { [actionField] = tostring(val) })
if (type(x.effect) == "string" and string.len(x.effect) > 0) then
heffect.bindUnit(x.effect, targetUnit, "origin", x.during)
end
end
end
end
elseif (actionType == 'spec') then
-- 特殊效果
if ((x.odds or 0) > 0) then
local damageSrc = x.damageSrc or CONST_DAMAGE_SRC.unknown
local damageType = x.damageType or { CONST_DAMAGE_TYPE.common }
if (val >= 0) then
if (actionField == "knocking") then
-- 额外暴击;已不分物理还是魔法,触发方式是自定义的
hskill.knocking({
targetUnit = targetUnit,
odds = x.odds,
damage = val,
percent = 100,
sourceUnit = triggerUnit,
effect = x.effect,
damageType = x.damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "split") then
--分裂
hskill.split({
targetUnit = targetUnit,
odds = x.odds,
damage = val,
percent = 100,
radius = x.radius,
sourceUnit = triggerUnit,
effect = x.effect,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "broken") then
--打断
hskill.broken({
targetUnit = targetUnit,
odds = x.odds,
damage = val,
sourceUnit = triggerUnit,
effect = x.effect,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "swim") then
--眩晕
hskill.swim({
targetUnit = targetUnit,
odds = x.odds,
damage = val,
during = x.during,
sourceUnit = triggerUnit,
effect = x.effect,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "silent") then
--沉默
hskill.silent({
targetUnit = targetUnit,
odds = x.odds,
damage = val,
during = x.during,
sourceUnit = triggerUnit,
effect = x.effect,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "unarm") then
--缴械
hskill.unarm({
targetUnit = targetUnit,
odds = x.odds,
damage = val,
during = x.during,
sourceUnit = triggerUnit,
effect = x.effect,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "fetter") then
--定身
hskill.fetter({
targetUnit = targetUnit,
odds = x.odds,
damage = val,
during = x.during,
sourceUnit = triggerUnit,
effect = x.effect,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "bomb") then
--爆破
hskill.bomb({
odds = x.odds,
damage = val,
radius = x.radius,
targetUnit = targetUnit,
sourceUnit = triggerUnit,
effect = x.effect,
effectEnum = x.effectEnum,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "lightning_chain") then
--闪电链
hskill.lightningChain({
odds = x.odds,
damage = val,
lightningType = x.lightning_type,
qty = x.qty,
rate = x.rate,
radius = x.radius or 500,
effect = x.effect,
isRepeat = false,
targetUnit = targetUnit,
prevUnit = triggerUnit,
sourceUnit = triggerUnit,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "crack_fly") then
--击飞
hskill.crackFly({
odds = x.odds,
damage = val,
targetUnit = targetUnit,
sourceUnit = triggerUnit,
distance = x.distance,
height = x.height,
during = x.during,
effect = x.effect,
damageType = damageType,
damageSrc = damageSrc,
isFixed = true,
})
elseif (actionField == "paw") then
--支线冲击效果,只支持token箭矢对坐标形式
if (math.random(1, 1000) <= x.odds * 10) then
local pxy = math.polarProjection(
hunit.x(triggerUnit), hunit.y(triggerUnit),
x.distance or 300,
math.getDegBetweenUnit(triggerUnit, targetUnit)
)
hskill.leapPaw({
tokenArrow = x.effect,
tokenArrowHeight = x.tokenArrowHeight or 0,
qty = x.qty or 1,
deg = x.deg or 15,
speed = x.speed or 8,
height = x.height or 0,
shake = x.shake or 0,
acceleration = x.acceleration or 0,
damageMovementRadius = x.radius or 50,
damageMovement = val,
damageMovementRepeat = false,
damageType = damageType,
damageSrc = damageSrc,
sourceUnit = triggerUnit,
x = pxy.x,
y = pxy.y,
isFixed = true,
filter = function(filterUnit)
return (his.enemy(filterUnit, triggerUnit) and his.alive(filterUnit) and (false == his.structure(filterUnit)))
end
})
end
end
end
end
end
end
end
end
end
end |
function onStart()
logInfo("Lua onStart called!")
logInfo("Latency: "..tostring(gameGetLatency()))
logInfo("Is multiplayer: "..tostring(gameIsMultiplayer()))
end
function onEnd(argIsWinner)
end
function onFrame()
if(gameGetFrameCount()%1000==0)then
logInfo("Frame count:"..tostring(gameGetFrameCount()))
end
end
function onSendText(argText)
end
function onPlayerLeft(argPlayer)
end
function onNukeDetect(argPosition)
end
function onUnitCreate(argUnit)
logInfo("onUnitCreate()")
logInfo("Unit created: "..unitTypeGetName(unitGetType(argUnit)))
end
function onUnitDestroy(argUnit)
logInfo("onUnitDestroy()")
logInfo("Unit destroyed: "..unitTypeGetName(unitGetType(argUnit)))
end
function onUnitMorph(argUnit)
logInfo("onUnitMorph()")
logInfo("Unit morphed: "..unitTypeGetName(unitGetType(argUnit)))
end
function onUnitShow(argUnit)
logInfo("onUnitShow()")
logInfo("Unit shown: "..unitTypeGetName(unitGetType(argUnit)))
end
function onUnitHide(argUnit)
logInfo("onUnitHide()")
logInfo("Unit hidden: "..unitTypeGetName(unitGetType(argUnit)))
end
function onUnitRenegade(argUnit)
logInfo("onUnitRenegade()")
logInfo("Unit mind controlled: "..unitTypeGetName(unitGetType(argUnit)))
end |
local Sing_bar = {}
local x = 0
local total_lenght = 0
local animate_time = 0.2
local proofread_list = {
[1] = {total_lenght = 185 , x = -0.75 },
[2] = {total_lenght = 83 , x = -1.125 },
}
function Sing_bar:CleanObjs()
for i = 1, self.total_count, 1 do
UnityEngine.GameObject.Destroy(self["bar_"..i].gameObject)
self["bar_"..i] = nil
end
self.total_count = 0
end
function Sing_bar:CleanSingBar()
if self.current_count ~= self.total_count then
self.Tween:DORestart(true)
end
self.view.total.transform:DOScale(Vector3(1,1,1), 0.6):OnComplete(function()
self.gameObject:SetActive(false)
self:CleanObjs()
end)
end
function Sing_bar:Start()
if self.gameObject.tag == "big_skill" then
x = proofread_list[1].x
total_lenght = proofread_list[1].total_lenght
else
x = proofread_list[2].x
total_lenght = proofread_list[2].total_lenght
end
self.view = SGK.UIReference.Setup(self.gameObject)
self.Tween = self.view[CS.DG.Tweening.DOTweenAnimation]
self.bar = self.view.total.bars.bar
end
function Sing_bar:CreateSingBar(type, total, current, certainly_increase, beat_back)
self.current_count = 0
self.bar_width = (total_lenght / total) - x
self.sing_type = type
self.total_count = total
self.view.type.text[CS.UGUISpriteSelector].index = self.sing_type - 1
self.view.total.bars[UI.GridLayoutGroup].cellSize = CS.UnityEngine.Vector2(self.bar_width, 5)
self.bar.barvalue_1[UnityEngine.RectTransform].sizeDelta = CS.UnityEngine.Vector2(self.bar_width, 5)
self.bar.barvalue_2[UnityEngine.RectTransform].sizeDelta = CS.UnityEngine.Vector2(self.bar_width, 5)
self.bar.barvalue_2[CS.UGUISpriteSelector].index = self.sing_type - 1
for i = 1, total, 1 do
self["bar_"..i] = SGK.UIReference.Instantiate(self.bar.gameObject, self.view.total.bars.transform)
self["bar_"..i]:SetActive(true)
self["bar_"..i].Status = "Null"
self["bar_"..i].dotween = self["bar_"..i].barvalue_1[CS.DG.Tweening.DOTweenAnimation]
end
self:SetSingBar(current, certainly_increase, beat_back)
end
function Sing_bar:SetSingBar(current, certainly_increase, beat_back)
if self.current_count > current then
print("=========@@@@!!!!!!!!!!!!!!!! 蓄力条不予许倒退")
return
end
self.current_count = math.min(current, self.total_count)
for i = 1, self.total_count, 1 do
local obj = self["bar_" .. i]
if i <= current then
obj.To_Status = "Current"
elseif i > current and i <= (current + certainly_increase) then
obj.To_Status = "Certainly_Increase"
elseif i > (current + certainly_increase) and i <= (current + certainly_increase + beat_back) then
obj.To_Status = "Beat_Back"
else
obj.To_Status = "Null"
end
end
self:SetSingBarStatus(self.total_count)
end
local _total = 0
local _index = 0
function Sing_bar:SetSingBarStatus(total_count)
if total_count then
_total = total_count
_index = 0
end
if _index == _total then
for i = 1, self.total_count, 1 do
local obj = self["bar_" .. i]
obj.Status = obj.To_Status
end
return
end
_index = _index + 1
local obj = self["bar_" .. _index]
if obj.To_Status ~= obj.Status then
if obj.To_Status == "Current" then
obj.barvalue_2.transform:DOScale(Vector3(1, 1, 1), animate_time):OnComplete(function()
obj.barvalue_1:SetActive(false)
self:SetSingBarStatus()
end)
return
end
if obj.To_Status == "Certainly_Increase" then
obj.dotween:DORewind()
obj.dotween:DOPause()
obj.barvalue_1.transform:DOScale(Vector3(1, 1, 1), animate_time):OnComplete(function()
self:SetSingBarStatus()
end)
return
end
if obj.To_Status == "Beat_Back" and obj.Status == "Null" then
obj.barvalue_1.transform:DOScale(Vector3(1, 1, 1), animate_time):OnComplete(function()
obj.dotween:DORestart(true)
self:SetSingBarStatus()
end)
return
end
if obj.To_Status == "Null" and obj.Status == "Beat_Back" then
obj.dotween:DORewind()
obj.dotween:DOPause()
self.Tween:DORestart(true)
obj.barvalue_1.transform:DOScale(Vector3(0, 1, 1), animate_time * 2):OnComplete(function()
self:SetSingBarStatus()
end)
return
end
end
self:SetSingBarStatus()
end
return Sing_bar |
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st, jid = require "util.stanza", require "util.jid";
local hosts = prosody.hosts;
local is_admin = require "core.usermanager".is_admin;
function send_to_online(message, host)
local sessions;
if host then
sessions = { [host] = hosts[host] };
else
sessions = hosts;
end
local c = 0;
for hostname, host_session in pairs(sessions) do
if host_session.sessions then
message.attr.from = hostname;
for username in pairs(host_session.sessions) do
c = c + 1;
message.attr.to = username.."@"..hostname;
module:send(message);
end
end
end
return c;
end
-- Old <message>-based jabberd-style announcement sending
function handle_announcement(event)
local stanza = event.stanza;
local node, host, resource = jid.split(stanza.attr.to);
if resource ~= "announce/online" then
return; -- Not an announcement
end
if not is_admin(stanza.attr.from) then
-- Not an admin? Not allowed!
module:log("warn", "Non-admin '%s' tried to send server announcement", stanza.attr.from);
return;
end
module:log("info", "Sending server announcement to all online users");
local message = st.clone(stanza);
message.attr.type = "headline";
message.attr.from = host;
local c = send_to_online(message, host);
module:log("info", "Announcement sent to %d online users", c);
return true;
end
module:hook("message/host", handle_announcement);
-- Ad-hoc command (XEP-0133)
local dataforms_new = require "util.dataforms".new;
local announce_layout = dataforms_new{
title = "Making an Announcement";
instructions = "Fill out this form to make an announcement to all\nactive users of this service.";
{ name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" };
{ name = "subject", type = "text-single", label = "Subject" };
{ name = "announcement", type = "text-multi", required = true, label = "Announcement" };
};
function announce_handler(_, data, state)
if state then
if data.action == "cancel" then
return { status = "canceled" };
end
local fields = announce_layout:data(data.form);
module:log("info", "Sending server announcement to all online users");
local message = st.message({type = "headline"}, fields.announcement):up()
:tag("subject"):text(fields.subject or "Announcement");
local count = send_to_online(message, data.to);
module:log("info", "Announcement sent to %d online users", count);
return { status = "completed", info = ("Announcement sent to %d online users"):format(count) };
else
return { status = "executing", actions = {"next", "complete", default = "complete"}, form = announce_layout }, "executing";
end
end
module:depends "adhoc";
local adhoc_new = module:require "adhoc".new;
local announce_desc = adhoc_new("Send Announcement to Online Users", "http://jabber.org/protocol/admin#announce", announce_handler, "admin");
module:provides("adhoc", announce_desc);
|
local make_map = require 'common.make_map'
local pickups = require 'common.pickups'
local api = {}
function api:start(episode, seed)
make_map.seedRng(seed)
api._count = 0
end
function api:commandLine(oldCommandLine)
return make_map.commandLine(oldCommandLine)
end
function api:createPickup(className)
return pickups.defaults[className]
end
function api:nextMap()
map = "G I A P"
api._count = api._count + 1
for i = 0, api._count do
map = map.." A"
end
return make_map.makeMap("demo_map_" .. api._count, map)
end
return api
|
if a then
print("separate")
if x == y then
-- empty
end
end
|
SanieUI.lib = {}
-- Create, colorize, and return a money string.
SanieUI.lib.ColorMoney = function(coppers)
local gold = floor(coppers / 10000)
local remaining = coppers % 10000
local silver = floor(remaining / 100)
remaining = coppers % 100
local cop = remaining
local moneyString = ""
if(gold > 0) then
moneyString = moneyString .. "|cFFFFFF32"..gold.."|r."
end
if(silver > 0 or gold > 0) then
moneyString = moneyString .. "|cFFE6E8FA"..silver.."|r."
end
moneyString = moneyString .. "|cFFB87333"..cop.."|r"
return moneyString
end
|
local ObjBaseUnit = require "objects.ObjBaseUnit"
local Inventory = require "xl.Inventory"
-- local Sound = require "xl.Sound"
local ObjChar = Class.create("ObjChar", ObjBaseUnit)
--util.transient( ObjChar, "healthbar", "guardbar" , "equipIcons" , "equipIcon2" , "sprite")
-- Initializes values of ObjChar, only runs once at the start of the game
-- sets up values which initial conditions
function ObjChar:init( )
-- inventory initialization
self.inventory = Inventory(3,3)
-- init other data
self.max_health = 100
self.health = 100
--initialize movement data
self.maxJumpTime = 9
self.currentJumpTime = 0
self.jumpSpeed = 990
self.maxAirJumps = 1
self.airJumps = 0
self.deceleration = -9
self.maxSpeed = 6 * 32
self.acceleration = 20 * 32
self.currentEquips = self.currentEquips or {}
self.currentPrimary = nil
self.x = 0
self.y = 0
self.persistent = true
self.attackTimer = 0
-- self.charHeight = 22
self.canControl = true
self.deflectable = true
self.inventoryLocked = self.inventoryLocked or false
self.faction = "player"
Game.savedata["count_deaths"] = 0
end
--Initializes values of ObjChar which will occur at the beginning of every room
--Recreates b2 body in every room.
function ObjChar:create()
ObjBaseUnit.create(self)
self:addModule(require "modules.ModControllable")
self:addModule(require "modules.ModCharacter")
self:addModule(require "modules.ModHasHUD")
self:addModule(require "modules.ModShield")
self:addModule(require "modules.ModDash")
self:addSpritePiece(require("assets.spr.scripts.SprLegPeridot"))
self:addSpritePiece(require("assets.spr.scripts.SprBodyPeridot"))
self:addSpritePiece(require("assets.spr.scripts.SprHeadPeridot"))
-- self:addSpritePiece(require("assets.spr.scripts.SprLegBoots"))
-- self:addSpritePiece(require("assets.spr.scripts.SprBodyUniform"))
-- self:addSpritePiece(require("assets.spr.scripts.SprHeadGeneric"))
-- self:addSpritePiece(require("assets.spr.scripts.SprHatHelmet"))
--if set to true, the game will maintain a hitbox that displays "!" when
-- near an interactable object (NOT IMPLEMENTED)
-- self.detectBox = true
Game:setPlayer(self)
--initialize player hitboxes
self:createBody( "dynamic" ,true, true)
self.shape = love.physics.newRectangleShape(12, 4)
self.shapeCrouch = love.physics.newRectangleShape(8,20)
self.fixture = love.physics.newFixture(self.body, self.shape, 1)
self:setFixture(self.shape, 22.6)
self.fixture:setCategory(CL_CHAR)
--initialize Inventory
-- self:addModule(require "modules.ModInventory")
-- self:setEquipCreateItem("ObjTorch")
self:setEquipCreateItem("EqpHandgun")
end
--
function ObjChar:die()
self.isAlive = false
local function death( player, frame )
lume.trace(frame)
if frame == 1 then
Game.worldManager:fade(2)
Game.savedata["count_deaths"] = Game.savedata["count_deaths"] + 1
elseif frame > 120 then
Game.worldManager:respawnFromDeath(self)
player.exit = true
end
end
if not self.onDeath then
lume.trace("on death")
self.onDeath = true
self:setSpecialState(death,false,true)
end
end
return ObjChar
|
local model_factories = {}
TEST_INTERVAL = '1 hour'
-- quorum_num / 100
function model_factories.build_policy(index, name, quorum_num)
p = Policy:new()
p.index = index
p.name = name
p.initiative_quorum_den = 100
p.initiative_quorum_num = quorum_num
p.issue_quorum_den = 100
p.issue_quorum_num = quorum_num
p.min_admission_time = '0 seconds'
p.max_admission_time = TEST_INTERVAL
p.discussion_time = TEST_INTERVAL
p.verification_time = TEST_INTERVAL
p.voting_time = TEST_INTERVAL
p:save()
return p
end
function model_factories.build_unit(name)
u = Unit:new()
u.name = name
u:save()
return u
end
function model_factories.build_area(unit_id, name, external_reference)
a = Area:new()
a.unit_id = unit_id
a.name = name
a.external_reference = external_reference
a:save()
return a
end
function model_factories.build_allowed_policy(area_id, policy_id, is_default_policy)
ap = AllowedPolicy:new()
ap.area_id = area_id
ap.policy_id = policy_id
ap.default_policy = is_default_policy
ap:save()
return ap
end
function model_factories.build_member(login, name)
m = Member:new()
m.login = login
m.active = true
m.activated = 'now'
m.last_activity = 'now'
m.name = name
m:set_password('login')
m:save()
return m
end
function model_factories.build_privilege(unit_id, member_id)
p = Privilege:new()
p.unit_id = unit_id
p.member_id = member_id
p.voting_right = true
p.initiative_right = true
p:save()
return p
end
function model_factories.build_membership(area_id, member_id)
m = Membership:new()
m.area_id = area_id
m.member_id = member_id
m:save()
return m
end
function model_factories.build_interest(issue_id, member_id)
i = Interest:new()
i.issue_id = issue_id
i.member_id = member_id
i:save()
return i
end
return model_factories
|
local SPUtil = require(game.ReplicatedStorage.Shared.SPUtil)
local SPDict = require(game.ReplicatedStorage.Shared.SPDict)
local SPList = require(game.ReplicatedStorage.Shared.SPList)
local SPUISystem = require(game.ReplicatedStorage.Shared.SPUISystem)
local MenuBase = require(game.ReplicatedStorage.Menu.MenuBase)
local SPUIChild = require(game.ReplicatedStorage.Shared.SPUIChild)
local SPUIChildButton = require(game.ReplicatedStorage.Menu.SPUIChildButton)
local DebugOut = require(game.ReplicatedStorage.Local.DebugOut)
local PropChange = require(game.ReplicatedStorage.Shared.PropChange)
local SFXManager = require(game.ReplicatedStorage.Local.SFXManager)
local PopupMessageUI = {}
PopupMessageUI.Type = "PopupMessageUI"
function PopupMessageUI:new(_local_services,_spui,_menus)
local self = MenuBase:new(_spui,_menus)
self.Type = PopupMessageUI.Type
local _obj = nil
local _alpha = 1
local _scale = 1
local _close_button = nil
local _on_close_fn = nil
local _prop_changes = PropChange.List:new()
function self:cons()
_obj = game.ReplicatedStorage.LobbyElementProtos.WorldUIProto.PopupMessageV2UI:Clone()
_obj.Parent = game.Workspace.WorldUI
self._native_size = _obj.PrimaryPart.Size
self._size = self._native_size
_close_button = self:add_cycle_element(_local_services, 1, SPUIChildButton:new(
SPUIChild:new(self, _obj.PrimaryPart, _obj.BackButtonSurface),
_spui,
function() self:on_back_button() end
))
_prop_changes:add(PropChange:new(function()
return SPUtil:tra(_obj.MainSurface.SurfaceGui.Frame.Title.BackgroundTransparency)
end, function(updated_alpha)
local setval = updated_alpha * 0.35
_obj.MainSurface.SurfaceGui.Frame.Title.BackgroundTransparency = SPUtil:tra(setval)
_obj.MainSurface.SurfaceGui.Frame.Sub.BackgroundTransparency = SPUtil:tra(setval)
end))
self:reset_selected_item()
self:transition_update_visual(0)
self:layout()
end
function self:set_on_close_fn(fn)
_on_close_fn = fn
return self
end
function self:set_close_button_visible(val)
_close_button:set_visible(val)
return self
end
--[[Override--]] function self:do_remove(_local_services)
_obj:Destroy()
end
function self:set_text(title,sub)
_obj.MainSurface.SurfaceGui.Frame.Title.TextLabel.Text = title
_obj.MainSurface.SurfaceGui.Frame.Sub.TextLabel.Text = sub
return self
end
function self:on_back_button()
_menus:remove_menu(self)
_local_services._sfx_manager:play_sfx(SFXManager.SFX_MENU_CLOSE)
if _on_close_fn ~= nil then
_on_close_fn()
_on_close_fn = nil
end
end
--[[Override--]] function self:visual_update(dt_scale, _local_services)
self:visual_update_base(dt_scale,_local_services)
_prop_changes:force_update()
end
--[[Override--]] function self:layout()
_spui:uiobj_rescale_to_max_nxy(self, 0.85, 0.75,_scale)
_obj:SetPrimaryPartCFrame(_spui:get_cframe({
PositionNXY = Vector2.new(0.5,0.5);
OffsetXYZ = self:anchored_offset(0.5,0.5);
LocalRotationOffset = Vector3.new(0,0,0);
}))
end
--[[Override--]] function self:set_alpha(val)
if _alpha ~= val then
_alpha = val
SPUtil:r_set_alpha(_obj,_alpha)
end
end
--[[Override--]] function self:get_alpha() return _alpha end
--[[Override--]] function self:set_scale(val) _scale = val end
--[[Override--]] function self:get_scale() return _scale end
--[[Override--]] function self:get_native_size()
return self._native_size
end
--[[Override--]] function self:get_size()
return self._size
end
--[[Override--]] function self:set_size(size)
self._size = size
_obj.PrimaryPart.Size = Vector3.new(size.X,size.Y,0.2)
end
--[[Override--]] function self:get_pos()
return _obj.PrimaryPart.Position
end
--[[Override--]] function self:get_sgui()
return _obj.PrimaryPart.SurfaceGui
end
self:cons()
return self
end
return PopupMessageUI
|
-- Generated by CSharp.lua Compiler
local System = System
local SlipeClientGui
local SlipeMtaDefinitions
local SlipeSharedElements
local SystemNumerics
System.import(function (out)
SlipeClientGui = Slipe.Client.Gui
SlipeMtaDefinitions = Slipe.MtaDefinitions
SlipeSharedElements = Slipe.Shared.Elements
SystemNumerics = System.Numerics
end)
System.namespace("Slipe.Client.Gui", function (namespace)
namespace.class("GuiElement", function (namespace)
local getVisible, setVisible, getAlpha, setAlpha, getEnabled, setEnabled, getStandardFont, setStandardFont,
getCustomFont, setCustomFont, getPosition, setPosition, getRelativePosition, setRelativePosition, getSize, setSize,
getRelativeSize, setRelativeSize, getContent, setContent, BringToFront, MoveToBack, Blur, Focus,
SetProperty, GetProperty, class, __ctor__
__ctor__ = function (this, element)
SlipeSharedElements.Element.__ctor__[2](this, element)
end
getVisible = function (this)
return SlipeMtaDefinitions.MtaClient.GuiGetVisible(this.element)
end
setVisible = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetVisible(this.element, value)
end
getAlpha = function (this)
return SlipeMtaDefinitions.MtaClient.GuiGetAlpha(this.element)
end
setAlpha = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetAlpha(this.element, value)
end
getEnabled = function (this)
return SlipeMtaDefinitions.MtaClient.GuiGetEnabled(this.element)
end
setEnabled = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetEnabled(this.element, value)
end
getStandardFont = function (this)
local s, _ = SlipeMtaDefinitions.MtaClient.GuiGetFont(this.element):Deconstruct()
return System.cast(System.Int32, System.Enum.Parse(System.typeof(SlipeClientGui.StandardGuiFont), s:Replace("-", "_"), true))
end
setStandardFont = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetFont(this.element, value:ToEnumString(SlipeClientGui.StandardGuiFont):ToLower():Replace("_", "-"))
end
getCustomFont = function (this)
local _, e = SlipeMtaDefinitions.MtaClient.GuiGetFont(this.element):Deconstruct()
return SlipeSharedElements.ElementManager.getInstance():GetElement(e, SlipeClientGui.GuiFont)
end
setCustomFont = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetFont(this.element, value:getMTAElement())
end
getPosition = function (this)
local x, y = SlipeMtaDefinitions.MtaClient.GuiGetPosition(this.element, false):Deconstruct()
return SystemNumerics.Vector2(x, y)
end
setPosition = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetPosition(this.element, value.X, value.Y, false)
end
getRelativePosition = function (this)
local x, y = SlipeMtaDefinitions.MtaClient.GuiGetPosition(this.element, true):Deconstruct()
return SystemNumerics.Vector2(x, y)
end
setRelativePosition = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetPosition(this.element, value.X, value.Y, true)
end
getSize = function (this)
local x, y = SlipeMtaDefinitions.MtaClient.GuiGetSize(this.element, false):Deconstruct()
return SystemNumerics.Vector2(x, y)
end
setSize = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetSize(this.element, value.X, value.Y, false)
end
getRelativeSize = function (this)
local x, y = SlipeMtaDefinitions.MtaClient.GuiGetSize(this.element, true):Deconstruct()
return SystemNumerics.Vector2(x, y)
end
setRelativeSize = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetSize(this.element, value.X, value.Y, true)
end
getContent = function (this)
return SlipeMtaDefinitions.MtaClient.GuiGetText(this.element)
end
setContent = function (this, value)
SlipeMtaDefinitions.MtaClient.GuiSetText(this.element, value)
end
-- <summary>
-- This function brings a Gui element on top of others.
-- </summary>
BringToFront = function (this)
return SlipeMtaDefinitions.MtaClient.GuiBringToFront(this.element)
end
-- <summary>
-- This function moves a GUI element to the very back of all other GUI elements.
-- </summary>
MoveToBack = function (this)
return SlipeMtaDefinitions.MtaClient.GuiMoveToBack(this.element)
end
-- <summary>
-- Blur this Gui Element
-- </summary>
Blur = function (this)
return SlipeMtaDefinitions.MtaClient.GuiBlur(this.element)
end
-- <summary>
-- Focus on this Gui Element
-- </summary>
Focus = function (this)
return SlipeMtaDefinitions.MtaClient.GuiFocus(this.element)
end
-- <summary>
-- Set a Cegui property
-- </summary>
SetProperty = function (this, property, value)
return SlipeMtaDefinitions.MtaClient.GuiSetProperty(this.element, property, value)
end
-- <summary>
-- Get a Cegui property
-- </summary>
GetProperty = function (this, property)
return SlipeMtaDefinitions.MtaClient.GuiGetProperty(this.element, property)
end
class = {
__inherits__ = function (out)
return {
out.Slipe.Shared.Elements.Element
}
end,
getVisible = getVisible,
setVisible = setVisible,
getAlpha = getAlpha,
setAlpha = setAlpha,
getEnabled = getEnabled,
setEnabled = setEnabled,
getStandardFont = getStandardFont,
setStandardFont = setStandardFont,
getCustomFont = getCustomFont,
setCustomFont = setCustomFont,
getPosition = getPosition,
setPosition = setPosition,
getRelativePosition = getRelativePosition,
setRelativePosition = setRelativePosition,
getSize = getSize,
setSize = setSize,
getRelativeSize = getRelativeSize,
setRelativeSize = setRelativeSize,
getContent = getContent,
setContent = setContent,
BringToFront = BringToFront,
MoveToBack = MoveToBack,
Blur = Blur,
Focus = Focus,
SetProperty = SetProperty,
GetProperty = GetProperty,
__ctor__ = __ctor__,
__metadata__ = function (out)
return {
properties = {
{ "Alpha", 0x106, System.Single, getAlpha, setAlpha },
{ "Content", 0x106, System.String, getContent, setContent },
{ "CustomFont", 0x106, out.Slipe.Client.Gui.GuiFont, getCustomFont, setCustomFont },
{ "Enabled", 0x106, System.Boolean, getEnabled, setEnabled },
{ "Position", 0x106, System.Numerics.Vector2, getPosition, setPosition },
{ "RelativePosition", 0x106, System.Numerics.Vector2, getRelativePosition, setRelativePosition },
{ "RelativeSize", 0x106, System.Numerics.Vector2, getRelativeSize, setRelativeSize },
{ "Size", 0x106, System.Numerics.Vector2, getSize, setSize },
{ "StandardFont", 0x106, System.Int32, getStandardFont, setStandardFont },
{ "Visible", 0x106, System.Boolean, getVisible, setVisible }
},
methods = {
{ ".ctor", 0x106, nil, out.Slipe.MtaDefinitions.MtaElement },
{ "Blur", 0x86, Blur, System.Boolean },
{ "BringToFront", 0x86, BringToFront, System.Boolean },
{ "Focus", 0x86, Focus, System.Boolean },
{ "GetProperty", 0x186, GetProperty, System.String, System.String },
{ "MoveToBack", 0x86, MoveToBack, System.Boolean },
{ "SetProperty", 0x286, SetProperty, System.String, System.String, System.Boolean }
},
events = {
{ "OnBlur", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnBlurEventArgs, System.Void) },
{ "OnFocus", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnFocusEventArgs, System.Void) },
{ "OnClick", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnClickEventArgs, System.Void) },
{ "OnDoubleClick", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnDoubleClickEventArgs, System.Void) },
{ "OnMouseDown", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnMouseDownEventArgs, System.Void) },
{ "OnMouseUp", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnMouseUpEventArgs, System.Void) },
{ "OnMove", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnMoveEventArgs, System.Void) },
{ "OnResize", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnResizeEventArgs, System.Void) },
{ "OnMouseEnter", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnMouseEnterEventArgs, System.Void) },
{ "OnMouseLeave", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnMouseLeaveEventArgs, System.Void) },
{ "OnMouseMove", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnMouseMoveEventArgs, System.Void) },
{ "OnMouseWheel", 0x6, System.Delegate(class, out.Slipe.Client.Gui.Events.OnMouseWheelEventArgs, System.Void) }
},
class = { 0x6 }
}
end
}
return class
end)
end)
|
vim.api.nvim_create_autocmd({ "BufEnter" }, {
pattern = { "*" },
nested = true,
callback = function()
-- if winnr('$') == 1 && bufname() == 'NvimTree_' . tabpagenr() | quit | endif,
print("test")
end
})
-- vim.api.nvim_create_autocmd({"TextYankPost"}, {
-- callback = function() vim.highlight.on_yank({higroup = 'Visual', timeout = 200}) end, -- Or myvimfun
-- })
|
local spawn1 = false -- Variable pour vérifier si déjà spawn
AddEventHandler("playerSpawned", function () -- Attendre que le joueur spawn
if not spawn1 then
ShutdownLoadingScreenNui() -- Fermer la ressource d'écran de chargement
spawn1 = true
end
end) |
--=========== Copyright © 2020, Planimeter, All rights reserved. ===========--
--
-- Purpose:
--
--==========================================================================--
local ffi = require( "ffi" )
io.input( framework.execdir .. "include/opus.h" )
ffi.cdef( io.read( "*all" ) )
return ffi.load( "opus" )
|
--
-- Auctionator.Search.Categories is an empty table on load, need to populate
-- with the possible categories
--
-- Here's what one entry looks like:
-- {
-- classID = integer (corresponding to ITEM_CLASS_IDS )
-- name = string (resolved by GetItemClassInfo( classID ))
-- category = table (new QueryAuctionItems categoryData format, { classID, subClassID (nil), inventoryType (nil) } )
-- subClasses = {
-- classID = integer (subClassID)
-- name = string (resolved by GetItemSubClassInfo( subClassID ))
-- category = table (new QueryAuctionItems categoryData format, { classID, subClassID, inventoryType? } )
-- }
-- }
local ITEM_CLASS_IDS = {
LE_ITEM_CLASS_WEAPON,
LE_ITEM_CLASS_ARMOR,
LE_ITEM_CLASS_CONTAINER,
LE_ITEM_CLASS_GEM,
LE_ITEM_CLASS_ITEM_ENHANCEMENT,
LE_ITEM_CLASS_CONSUMABLE,
LE_ITEM_CLASS_GLYPH,
LE_ITEM_CLASS_TRADEGOODS,
LE_ITEM_CLASS_RECIPE,
LE_ITEM_CLASS_BATTLEPET,
LE_ITEM_CLASS_QUESTITEM,
LE_ITEM_CLASS_MISCELLANEOUS
}
local INVENTORY_TYPE_IDS = Auctionator.Constants.INVENTORY_TYPE_IDS
Auctionator.Search.Category = {
classID = 0,
name = Auctionator.Constants.CategoryDefault,
key = 0,
parentKey = nil,
category = {},
subClasses = {}
}
function Auctionator.Search.Category:new( options )
options = options or {}
setmetatable( options, self )
self.__index = self
return options
end
--Given a key and category (classID and subClassID supplied, assumed to be for
--armor), creates a new category for each possible inventory slot.
--Returns array of new categories
local function GenerateArmorInventorySlots(parentKey, parentCategory)
local inventorySlots = {}
for index = 1, #INVENTORY_TYPE_IDS do
local name = GetItemInventorySlotInfo(INVENTORY_TYPE_IDS[index])
local category = {
classID = parentCategory.classID,
subClassID = parentCategory.subClassID,
inventoryType = INVENTORY_TYPE_IDS[index],
}
local subSubClass = Auctionator.Search.Category:new({
classID = INVENTORY_TYPE_IDS[index],
name = name,
key = parentKey .. [[/]] .. name,
parentKey = parentKey,
category = { category }
})
table.insert( inventorySlots, subSubClass )
end
return inventorySlots
end
local function GenerateSubClasses( classID, parentKey )
local subClassesTable = C_AuctionHouse.GetAuctionItemSubClasses( classID )
local subClasses = {}
for index = 1, #subClassesTable do
local subClassID = subClassesTable[ index ]
local name = GetItemSubClassInfo( classID, subClassID )
local category = { classID = classID, subClassID = subClassID }
local subClass = Auctionator.Search.Category:new({
classID = subClassID,
name = name,
key = parentKey .. [[/]] .. name,
parentKey = parentKey,
category = { category }
})
table.insert( subClasses, subClass )
--Armor special case, adds inventory slot categories
if classID == LE_ITEM_CLASS_ARMOR then
local inventorySlots = GenerateArmorInventorySlots(subClass.key, category)
for _, slot in ipairs(inventorySlots) do
table.insert(subClasses, slot)
end
end
end
return subClasses
end
for _, classID in ipairs( ITEM_CLASS_IDS ) do
local key = GetItemClassInfo( classID )
local subClasses = GenerateSubClasses( classID, key )
local category = {classID = classID}
local categoryCategory = Auctionator.Search.Category:new({
classID = classID,
name = name,
key = key,
category = {category},
subClasses = subClasses
})
table.insert( Auctionator.Search.Categories, categoryCategory )
end
for _, category in ipairs( Auctionator.Search.Categories ) do
Auctionator.Search.CategoryLookup[ category.key ] = category
for i = 1, #category.subClasses do
local subCategory = category.subClasses[ i ]
Auctionator.Search.CategoryLookup[ subCategory.key ] = subCategory
end
end
|
local class = require 'middleclass'
local cjson = require 'cjson.safe'
local logger = require 'hj212.logger'
local types = require 'hj212.types'
local param_tag = require 'hj212.params.tag'
local calc_mgr_m = require 'hj212.calc.manager'
local poll_info = require 'hj212.client.info'
local poll = class('hj212.client.poll')
--- Calc name
-- Has COU is nil will using auto detect
function poll:initialize(station, id, options, info_creator)
assert(station)
assert(id, "Poll Id missing")
self._station = station
self._meter = nil
-- Options
self._id = id
self._min = options.min
self._max = options.max
self._cou = options.cou -- {calc='simple', cou=0, params = {...}}
self._fmt = options.fmt
self._zs_calc = options.zs_calc
self._info_creator = info_creator
-- Data current
self._value = nil
self._flag = types.FLAG.Normal
self._timestamp = nil
self._quality = nil
self._flag = nil
-- COU calculator
self._cou_calc = nil
self._inited = false
-- Info
self._info = nil
end
--- Guess the proper calculator name
local function guess_calc_name(poll_id)
if string.sub(poll_id, 1, 1) == 'w' then
return 'water'
elseif string.sub(poll_id, 1, 1) == 'a' then
return 'air'
elseif string.sub(poll_id, 1, 2) == 'LA' then
return 'LA'
else
-- Default is simple calculator
return 'simple'
end
end
function poll:init()
if self._inited then
return
end
local calc_mgr = self._station:calc_mgr()
local poll_id = self._id
assert(poll and poll_id)
local calc_name = self._cou.calc or guess_calc_name(poll_id)
assert(calc_name)
local m = assert(require('hj212.calc.'..calc_name))
local msg = string.format('TAG [%06s] COU:%s ZS:%d', poll_id, calc_name, self._zs_calc and 1 or 0)
local params = self._cou.params or {}
if #params > 0 then
msg = msg .. ' with '..cjson.encode(params)
end
logger.log('info', msg)
local cou_base = upper_poll and upper_poll:cou_calc() or nil
local mask = calc_mgr_m.TYPES.ALL
local cou_calc = m:new(self._station, poll_id, mask, self._min, self._max, self._zs_calc, table.unpack(params))
cou_calc:set_callback(function(type_name, val, timestamp, quality)
if val.cou ~= nil and type(self._cou.cou) == 'number' then
val.cou = has_cou
end
return self:on_calc_value(type_name, val, timestamp, quality)
end)
self._cou_calc = cou_calc
calc_mgr:reg(self._cou_calc)
self._inited = true
return true
end
function poll:inited()
return self._inited
end
function poll:set_meter(mater)
self._meter = mater
end
function poll:meter()
return self._meter
end
function poll:station()
return self._station
end
function poll:id()
return assert(self._id)
end
function poll:cou_calc()
return self._cou_calc
end
function poll:upload()
assert(nil, "Not implemented")
end
function poll:on_calc_value(type_name, val, timestamp)
assert(nil, "Not implemented")
end
--- Ex vals will not be saved
function poll:set_value(value, timestamp, value_z, flag, quality, ex_vals)
local flag = flag == nil and self._meter:get_flag() or nil
self._value = value
self._value_z = value_z
self._timestamp = timestamp
self._flag = flag
self._quality = quality
self._ex_vals = ex_vals and cjson.encode(ex_vals) or nil
return self._cou_calc:push(value, timestamp, value_z, flag, quality, self._ex_vals)
end
function poll:get_value()
return self._value, self._timestamp, self._value_z, self._flag, self._quality, self._ex_vals and cjson.decode(self._ex_vals) or nil
end
function poll:query_rdata(timestamp, readonly)
local val, err = self._cou_calc:query_rdata(timestamp, readonly)
if not val then
logger.log('warning', self._id..' rdata missing', err)
return nil, err
end
local rdata = {
Rtd = val.value,
Flag = val.flag,
ZsRtd = val.value_z,
--- EFlag is optional
SampleTime = val.src_time or val.timestamp,
}
if val.ex_vals then
local ex_vals = cjson.decode(val.ex_vals)
for k, v in pairs(ex_vals) do
rdata[k] = v
end
end
return param_tag:new(self._id, rdata, timestamp, self._fmt)
end
function poll:convert_data(data)
if self._id == 'LA' then
return self:convert_data_la(data)
end
local rdata = {}
local has_cou = self._cou.cou
for k, v in ipairs(data) do
if has_cou ~= false then
rdata[#rdata + 1] = param_tag:new(self._id, {
Cou = v.cou,
Avg = v.avg,
Min = v.min,
Max = v.max,
ZsAvg = v.avg_z,
ZsMin = v.min_z,
ZsMax = v.max_z,
Flag = v.flag,
}, v.stime, self._fmt)
else
rdata[#rdata + 1] = param_tag:new(self._id, {
Avg = v.avg,
Min = v.min,
Max = v.max,
ZsAvg = v.avg_z,
ZsMin = v.min_z,
Flag = v.flag,
}, v.stime, self._fmt)
end
end
return rdata
end
function poll:convert_data_la(data)
local rdata = {}
for k, v in ipairs(data) do
-- print('convert_data_la', cjson.encode(data))
if not v.ex_vals or not v.ex_vals.DAY then
rdata[#rdata + 1] = param_tag:new('Leq', { Data = v.avg }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('LMn', { Data = v.min }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('LMx', { Data = v.max }, v.stime, self._fmt)
else
rdata[#rdata + 1] = param_tag:new('Ldn', { Data = v.avg }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('LMn', { Data = v.min }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('LMx', { Data = v.max }, v.stime, self._fmt)
end
--- Convert ex_vals
if v.ex_vals then
local ex_vals = cjson.decode(v.ex_vals)
rdata[#rdata + 1] = param_tag:new('L5', { Data = ex_vals.L5 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L10', { Data = ex_vals.L10 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L50', { Data = ex_vals.L50 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L90', { Data = ex_vals.L90 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L95', { Data = ex_vals.L95 }, v.stime, self._fmt)
if ex_vals.DAY then
rdata[#rdata + 1] = param_tag:new('L5', { DayData = ex_vals.DAY.L5 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L10', { DayData = ex_vals.DAY.L10 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L50', { DayData = ex_vals.DAY.L50 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L90', { DayData = ex_vals.DAY.L90 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L95', { DayData = ex_vals.DAY.L95 }, v.stime, self._fmt)
end
if ex_vals.NIGHT then
rdata[#rdata + 1] = param_tag:new('L5', { NightData = ex_vals.NIGHT.L5 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L10', { NightData = ex_vals.NIGHT.L10 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L50', { NightData = ex_vals.NIGHT.L50 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L90', { NightData = ex_vals.NIGHT.L90 }, v.stime, self._fmt)
rdata[#rdata + 1] = param_tag:new('L95', { NightData = ex_vals.NIGHT.L95 }, v.stime, self._fmt)
end
end
end
return rdata
end
function poll:query_min_data(start_time, end_time)
local data = self._cou_calc:query_min_data(start_time, end_time)
return self:convert_data(data)
end
function poll:query_hour_data(start_time, end_time)
local data = self._cou_calc:query_hour_data(start_time, end_time)
return self:convert_data(data)
end
function poll:query_day_data(start_time, end_time)
local data = self._cou_calc:query_day_data(start_time, end_time)
return self:convert_data(data)
end
function poll:set_info_value(value, timestamp, quality)
if not self._info then
self._info = self._info_creator(self)
end
return self._info:set_value(value, timestamp, quality)
end
function poll:info_data(...)
if not self._info then
return nil, "No info found"
end
return self._info:data(...)
end
function poll:info()
return self._info
end
return poll
|
server_scripts 'server.lua'
client_script 'call.lua' |
require('..')
local tensor = torch.rand(8, 2)
local indices = {dmn.constants.TRAIN_INDEX,
dmn.constants.TRAIN_INDEX,
dmn.constants.VAL_INDEX,
dmn.constants.TEST_INDEX,
dmn.constants.TEST_INDEX,
dmn.constants.TRAIN_INDEX,
dmn.constants.VAL_INDEX,
dmn.constants.TEST_INDEX}
local train_tensor, val_tensor, test_tensor =
dmn.functions.partition_tensor(tensor, indices)
print(train_tensor)
print(val_tensor)
print(test_tensor)
print(tensor) |
local Settings = require "Settings"
local class = {}
local keyMusicVolume = "com.cronlygames.music.volume"
local keySoundVolume = "com.cronlygames.sound.volume"
local loadAllSounds = function()
class.curEffectVolume = -1
end
class.loadAllSounds = loadAllSounds
local playEffect = function(key)
if not Settings.isSoundOn() then
return
end
local engine = cc.SimpleAudioEngine:getInstance()
engine:playEffect(key)
local vol = class.getEffectsVolume()
if math.abs((class.curEffectVolume or -1) - vol) > 0.01 then
engine:setEffectsVolume(vol)
class.curEffectVolume = vol
end
end
class.playEffect = playEffect
local unloadEffect = function(key)
cc.SimpleAudioEngine:getInstance():unloadEffect(key)
end
class.unloadEffect = unloadEffect
local isBackMusicPlaying = function()
return cc.SimpleAudioEngine:getInstance():isMusicPlaying()
end
class.isBackMusicPlaying = isBackMusicPlaying
local stopBackMusic = function()
if cc.SimpleAudioEngine:getInstance():isMusicPlaying() then
cc.SimpleAudioEngine:getInstance():stopMusic()
end
end
class.stopBackMusic = stopBackMusic
local playBackMusic = function(back, isLoop)
if isLoop == nil then
isLoop = true
end
class.stopBackMusic()
if not Settings.isMusicOn() then
return
end
local engine = cc.SimpleAudioEngine:getInstance()
engine:playMusic(back, isLoop)
local vol = class.getMusicVolume()
class.setMusicVolume(vol)
end
class.playBackMusic = playBackMusic
class.getMusicVolume = function()
local t = cc.UserDefault:getInstance():getFloatForKey(keyMusicVolume, 1.0)
return t
end
class.setMusicVolume = function(vol)
local engine = cc.SimpleAudioEngine:getInstance()
engine:setMusicVolume(vol)
cc.UserDefault:getInstance():setFloatForKey(keyMusicVolume, vol)
cc.UserDefault:getInstance():flush()
end
class.getEffectsVolume = function()
local t = cc.UserDefault:getInstance():getFloatForKey(keySoundVolume, 1.0)
return t
end
class.setEffectsVolume = function(vol)
cc.UserDefault:getInstance():setFloatForKey(keySoundVolume, vol)
cc.UserDefault:getInstance():flush()
end
return class
|
-- Petit script pour configurer le client WIFI du NodeMCU
function wifi_cli_conf()
print("\n wifi_cli_conf.lua zf190726.1912 \n")
-- les secrets sont maintenant initialisés par boot.lua !
wifi.sta.config{ssid=cli_ssid, pwd=cli_pwd, save=true}
end
wifi_cli_conf()
wifi_cli_conf=nil
|
--- @module NpcEnemyMgr 服务端敌人NPC管理模块
--- @copyright Lilith Games, Avatar Team
--- @author Sharif Ma
local NpcEnemyMgr, this = ModuleUtil.New('NpcEnemyMgr', ServerBase)
--- 初始化
function NpcEnemyMgr:Init()
self.npcList = {}
self.npcFolder = world.Npc or world:CreateObject('FolderObject', 'Npc', world)
self.teamMinNum = Config.GlobalConfig.TeamMinNum
self.m_enable = false
self.m_sceneId = -1
world.OnPlayerRemoved:Connect(
function(_player)
--self:PlayerRemove(_player)
end
)
end
---游戏开始后调用
function NpcEnemyMgr:Start(_sceneId)
self.m_sceneId = _sceneId
self.pos1_A = Config.Scenes[_sceneId].BornArea[1][1]
self.pos2_A = Config.Scenes[_sceneId].BornArea[1][2]
self.pos1_B = Config.Scenes[_sceneId].BornArea[2][1]
self.pos2_B = Config.Scenes[_sceneId].BornArea[2][2]
end
---游戏正式开始
function NpcEnemyMgr:StartGame()
self.m_enable = true
local teamA_num, teamB_num = 0, 0
local teamA_npcNum, teamB_npcNum = 0, 0
for i, v in pairs(FindAllPlayers()) do
if v.PlayerType then
if v.PlayerType.Value == Const.TeamEnum.Team_A then
teamA_num = teamA_num + 1
elseif v.PlayerType.Value == Const.TeamEnum.Team_B then
teamB_num = teamB_num + 1
end
end
end
teamA_npcNum = self.teamMinNum - teamA_num
teamB_npcNum = self.teamMinNum - teamB_num
teamA_npcNum = teamA_npcNum <= 0 and 0 or teamA_npcNum
teamB_npcNum = teamB_npcNum <= 0 and 0 or teamB_npcNum
for i = 1, teamA_npcNum do
self:CreateNpc(Const.TeamEnum.Team_A, self.m_sceneId)
end
for i = 1, teamB_npcNum do
self:CreateNpc(Const.TeamEnum.Team_B, self.m_sceneId)
end
end
--- Update函数
--- @param dt number delta time 每帧时间AS
function NpcEnemyMgr:Update(dt, tt)
if not self.m_enable then
return
end
for i, v in pairs(self.npcList) do
v:Update(dt, tt)
end
end
---创建NPC
function NpcEnemyMgr:CreateNpc(_team, _sceneId)
local area = {}
if _team == Const.TeamEnum.Team_A then
area[1] = self.pos1_A
area[2] = self.pos2_A
else
area[1] = self.pos1_B
area[2] = self.pos2_B
end
---@type NpcEnemyBase
local npc = NpcEnemyBase:new(_team, area, self.npcFolder, _sceneId)
self.npcList[npc.uuid] = npc
npc:Born()
NetUtil.Fire_S('NpcCreateEvent', npc.model)
NetUtil.Broadcast('NpcCreateEvent', npc.model, npc.cloths, _team)
return npc.uuid
end
---游戏状态重置为大厅状态时候调用
function NpcEnemyMgr:Reset()
for i, v in pairs(self.npcList) do
NetUtil.Fire_S('NpcDestroyEvent', v.model)
invoke(
function()
wait()
v:Destroy()
end
)
end
self.npcList = {}
end
---一局游戏结束后调用
function NpcEnemyMgr:GameOver()
self.m_enable = false
end
--- 有玩家离开游戏,需要动态补齐NPC,游戏在进行中才会执行
---@param _player PlayerInstance 离开游戏的玩家
function NpcEnemyMgr:OnPlayerLeaveEventHandler(_player)
if
GameFlowMgr.gameFms.current ~= Const.GameStateEnum.OnGame and
GameFlowMgr.gameFms.current ~= Const.GameStateEnum.OnReady
then
return
end
print('玩家退出游戏,补全机器人')
local team = _player.PlayerType.Value
self:CreateNpc(team, self.m_sceneId)
end
---玩家开场运镜完成,只要一个玩家完成运镜,NPC就创建
function NpcEnemyMgr:CameraMoveEndEventHandler(_player)
if self.m_enable then
return
end
if
GameFlowMgr.gameFms.current ~= Const.GameStateEnum.OnGame and
GameFlowMgr.gameFms.current ~= Const.GameStateEnum.OnReady
then
return
end
self:StartGame()
end
return NpcEnemyMgr
|
return {
_VERSION = 'v1.0.0',
_DESCRIPTION = 'A Lua library that tries to fill the gaps',
_URL = 'https://github.com/roobie/lute',
_LICENSE = [[
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
]]
}
|
require "scripts.core.ability"
require "gamemode.Spark.modifiers.modifier_arcane";
local arcane_rune = class(Ability)
function arcane_rune:OnCreated ()
self:RegisterVariable("max_range", 0.5)
self:RegisterVariable("cast_time", 0.1)
self:RegisterVariable("cast_point", 0.0)
self:SetCastingBehavior(CastingBehavior(CastingBehavior.UNIT_TARGET));
self:SetLevel(1)
end
function arcane_rune:OnSpellStart ()
self.arcaneModifier = self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_arcane", {duration = self:GetSpecialValue("arcane_duration")})
GameManagerRequestBus.Broadcast.DestroyEntity(GetId(self:GetCursorTarget()))
self:DetachAndDestroy();
end
return arcane_rune
|
return {
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65721
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65731,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65741,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65751,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65761,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65722
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65732,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65742,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65752,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65762,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65723
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65733,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65743,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65753,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65763,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65724
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65734,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65744,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65754,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65764,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65725
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65735,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65745,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65755,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65765,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65726
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65736,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65746,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65756,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65766,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65727
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65737,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65747,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65757,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65767,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65728
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65738,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65748,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65758,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65768,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65729
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65739,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65749,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65759,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65769,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
{
effect_list = {
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65730
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65740,
delay = 0.2
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65750,
delay = 0.3
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65760,
delay = 0.4
}
},
{
type = "BattleSkillFire",
casterAniEffect = "",
target_choise = "TargetNil",
targetAniEffect = "",
arg_list = {
weapon_id = 65770,
delay = 0.5
}
},
{
type = "BattleSkillAddBuff",
casterAniEffect = "",
target_choise = "TargetSelf",
targetAniEffect = "",
arg_list = {
buff_id = 14158
}
}
}
},
uiEffect = "",
name = "苏维埃贝拉罗斯-弹幕-PVP",
cd = 0,
painting = 1,
id = 14155,
picture = "0",
castCV = "skill",
desc = "苏维埃贝拉罗斯-弹幕",
aniEffect = {
effect = "jineng",
offset = {
0,
-2,
0
}
},
effect_list = {}
}
|
require("lualib_bundle");
__TS__SourceMapTraceBack(debug.getinfo(1).short_src, {["4"] = 1,["5"] = 1,["6"] = 3,["7"] = 3,["8"] = 3,["9"] = 3,["11"] = 3,["12"] = 4,["13"] = 5,["14"] = 4,["15"] = 3,["16"] = 3});
local ____exports = {}
local ____YieldType = require("Lilac.Scheduling.YieldType")
local YieldType = ____YieldType.YieldType
____exports.default = (function()
____exports.default = __TS__Class()
local Coroutine = ____exports.default
Coroutine.name = "Coroutine"
function Coroutine.prototype.____constructor(self)
end
function Coroutine.prototype.YieldForSeconds(self, time)
coroutine.yield(YieldType.Update)
end
return Coroutine
end)()
return ____exports
|
function element_2(shader, t_base, t_second, t_detail)
shader:begin("null", "vignette")
:fog (false)
:zb (false, false)
shader:sampler ("s_image") :texture("$user$albedo") :clamp() :f_none()
end
--// Chromatic Aberration
function element_0(shader, t_base, t_second, t_detail)
shader:begin("null", "chromatic_aberration")
:fog (false)
:zb (false, false)
shader:sampler ("s_image") :texture("$user$albedo") :clamp() :f_none()
end
--// Color grading
local tex_color = "shaders\\color_chart"
function element_1(shader, t_base, t_second, t_detail)
shader:begin("null", "color_grading")
:fog (false)
:zb (false, false)
shader:sampler ("s_image") :texture("$user$albedo") :clamp() :f_none()
shader:sampler ("color_chart_sampler") :texture(tex_color) :clamp() :f_linear()
end |
--SYMBOLS
local ft = ".dat" --type of file to write
local eq = " = " -- how equals is represented in-file
local nl = "\r\n" --newline symbol
local td = "@@" --table reference symbol
local gd = "##" --grid reference symbol
local gv = "," --grid value divider
function sset(line, target, value)
if type(target) == "boolean" then
value = Util.sbool(value)
end
if type(target) == type(value) then
target = value
else
print("Type mismatch, ignoring "..line)
end
end
--loop recursively over a directory, perform function on files
function Util.fordir(dir, func, behavior)
local list = {}
local dir_items = love.filesystem.getDirectoryItems(dir)
for _, item in ipairs(dir_items) do
local file = dir .. "/" .. item
local info = love.filesystem.getInfo(file)
if info.type == "file" then
func(file, item)
elseif info.type == "directory"
and behavior == "recursive" then
Util.fordir(file, func)
end
end
return list
end
--load in an object in the form of name = value
function Util.load(object, filename)
if love.filesystem.getInfo(filename) == nil or object == nil then
print("File not found: "..filename)
return object
end
for line in love.filesystem.lines(filename) do
if line == nil then break
elseif line:find(eq) then
local bef_eq = Util.bef(line, eq)
local aft_eq = Util.snum(Util.aft(line, eq))
--if its a table reference, recursively load it
if bef_eq:find(td) then
--remove the table deliminator and load
bef_eq = Util.snum(string.gsub(bef_eq, td, ""))
sset(line, object[bef_eq], Util.load(object[bef_eq], aft_eq))
else
bef_eq = Util.snum(bef_eq)
sset(line, object[bef_eq], aft_eq)
end
else
print("Invalid line "..line)
end
end
return object
end
--save an object in the form of name = value
function Util.save(object, filename)
love.filesystem.newFile(filename)
local content = ""
for name, value in pairs(object) do
if type(value) ~= "table" then
content = content .. name .. eq .. tostring(value) .. nl
else
--tables recursively get their own files
local folder = string.gsub(filename, ft, "")
local tfn = folder .. "/" .. name .. ft
love.filesystem.createDirectory(folder)
content = content .. td .. name .. eq .. tfn .. nl
Util.save(value, tfn)
end
end
love.filesystem.write(filename, content)
end
|
function Header(el)
local id = el.identifier
if id == '' then return el end
local link = pandoc.Link('', '#'..id, '',
{['class'] = 'anchor icon-link', ['aria-hidden'] = 'true'})
el.content:insert(link)
el.attributes['onclick'] = ''
return el
end
|
---
--- object.lua
---
--- Copyright (C) 2018 Xrysnow. All rights reserved.
---
--region 对象控制函数
---获取对象池中对象个数。
---@return number
function GetnObj()
end
---更新对象池。此时将所有对象排序并归类。
---排序规则:uid越小越靠前
--- 细节
--->luaSTG+中该函数不再起任何作用,对象表总是保持有序的。
function UpdateObjList()
end
---更新对象列表中所有对象,并更新属性。
---禁止在协程上调用该方法。
--- 细节
--->按照下列顺序更新这些属性:
--->vx += ax
--->vy += ay
--->x += vx
--->y += vy
--->rot += omiga
--->更新绑定的粒子系统(若有)
function ObjFrame()
end
---渲染所有对象。此时将所有对象排序。
---禁止在协程上调用该方法。
---排序规则:layer小的先渲染,若layer相同则按照uid
--- 细节
--- luaSTG+中渲染列表总是保持有序的,将不会每次排序。
function ObjRender()
end
---SetBound(left,right,bottom,top)
---设置舞台边界
function SetBound(left, right, bottom, top)
end
---执行边界检查。注意BoundCheck只保证对象中心还在范围内,不进行碰撞盒检查。
---禁止在协程上调用该方法。
function BoundCheck()
end
---对组A和B进行碰撞检测。如果组A中对象与组B中对象发生碰撞,将执行A中对象的碰撞回调函数。
---禁止在协程上调用该方法。
function CollisionCheck(A, B)
end
---刷新对象的dx,dy,lastx,lasty,rot(若navi=true)值。
---禁止在协程上调用该方法。
function UpdateXY()
end
---刷新对象的timer和ani_timer,若对象被标记为del或kill将删除对象并回收资源。
---禁止在协程上调用该方法。
--- 细节
--- 对象只有在AfterFrame调用后才会被清理,在此之前可以通过设置对象的status字段取消删除标记。
function AfterFrame()
end
---创建新对象。将累加uid值。
---> 细节:该方法使用class创建一个对象,并在构造对象后调用class的构造方法(init)构造对象。
--- 被创建的对象具有如下属性:
--->x, y 坐标
--->dx, dy (只读)距离上一次更新的坐标增量
--->rot 角度
--->omiga 角度增量
--->timer 计数器
--->vx, vy 速度
--->ax, ay 加速度
--->layer 渲染层级
--->group 碰撞组
--->hide 是否隐藏
--->bound 是否越界销毁
--->navi 是否自动更新朝向
--->colli 是否允许碰撞
--->status 对象状态,返回del kill normal
--->hscale, vscale 横向、纵向的缩放
--->class 对象的父类
--->a, b 碰撞盒大小
--->rect 是否为矩形碰撞盒
--->img
--->ani (只读)动画计数器
--- 被创建对象的索引1和2被用于存放类和id【请勿修改】
--- 其中父类class需满足如下形式:
--->is_class = true
--->[1] = 初始化函数 (object, ...)
--->[2] = 删除函数(DEL) (object, ...)
--->[3] = 帧函数 (object)
--->[4] = 渲染函数 (object)
--->[5] = 碰撞函数 (object, object)
--->[6] = 消亡函数(KILL) (object, ...)
--- 上述回调函数将在对象触发相应事件时被调用
--- luastg+提供了至多32768个空间共object使用。超过这个大小后将报错。
function New(class, ...)
end
---通知删除一个对象。将设置标志并调用回调函数。
---若在object后传递多个参数,将被传递给回调函数。
function Del(object, ...)
end
---通知杀死一个对象。将设置标志并调用回调函数。
---若在object后传递多个参数,将被传递给回调函数。
function Kill(object, ...)
end
---IsValid(obj)
---检查对象是否有效
---对象为table,且具有正确的资源池id
---@return boolean
function IsValid(obj)
end
---SetV(obj,v,a,updateRot)
---设置速度方向和大小(C++对象)
---obj:要设置的对象
---v:速度大小
---a:速度方向(角度)
---updateRot:是否更新自转,默认为false
function SetV(obj, v, a, updateRot)
end
---获取速度方向和大小(从C++对象中)
---返回:速度大小,速度方向(角度)
function GetV(obj)
end
---SetImgState(object, blend, a, r, g, b)
---设置资源状态
---blend:混合模式
---a,r,g,b:颜色。
---该函数将会设置和对象绑定的精灵、动画资源的混合模式,该设置对所有同名资源都有效果。
function SetImgState(object, blend, a, r, g, b)
end
---Angle(objA,objB)
---Angle(x1,y1,x2,y2)
---计算两点连线角度
---@return number
function Angle(objA, objB)
end
---Dist(objA,objB)
---计算两点距离
---@return number
function Dist(objA, objB)
end
---BoxCheck(object,left,right,bottom,top)
---检查对象中心是否在所给范围内。
---@return boolean
function BoxCheck(object, left, right, top, bottom)
end
---清空并回收所有对象。
function ResetPool()
end
---DefaultRenderFunc(obj)
---在对象上调用默认渲染方法。
function DefaultRenderFunc(obj)
end
---获取组中的下一个元素。若groupid为无效的碰撞组则返回所有对象。
---返回的第一个参数为id(luastg中为idx),第二个参数为对象
--- 细节
--- luastg中NextObject接受的第二个参数为组中的元素索引而非id。
--- 出于效率考虑,luastg+中接受id查询下一个元素并返回下一个元素的id。
function NextObject(groupid, id)
end
---产生组遍历迭代器
--- 细节
--- 由于NextObject行为发生变更,ObjList只在for循环中使用时可以获得兼容性。
function ObjList(groupid)
end
---获取C++对象属性
---用于 enemybase laser_bent
function GetAttr(obj, key)
end
---设置属性,视情况设置C++对象的属性或lua对象的属性
---用于 boss enemybase laser_bent
function SetAttr(obj, key, v)
end
---启动绑定在对象上的粒子发射器
function ParticleFire(object)
end
---停止绑定在对象上的粒子发射器
function ParticleStop(object)
end
---返回绑定在对象上的粒子发射器的存活粒子数
function ParticleGetn(object)
end
---获取绑定在对象上粒子发射器的发射密度(个/秒)
--- 细节
--- luastg/luastg+更新粒子发射器的时钟始终为1/60s。
function ParticleGetEmission(object)
end
---设置绑定在对象上粒子发射器的发射密度(个/秒)
function ParticleSetEmission(object, count)
end
--endregion
|
-- Faxanadu (U) (PRG0) [!].nes
-- Faxanadu (U) (PRG1) [!].nes
-- Written by sleepy - Shawn M. Crawford
-- 6 January 2014
-- Displays Player Coordinates, HP, and Sprite HP stats on screen. The
-- HP stats are displayed in the upper left.
local function text(x,y,str)
--NES Resolution 256x240
if (x >= 0 and x < 256 and y >= 0 and y < 240) then
gui.text(x,y,str);
end;
end;
while (true) do
-- Player 1 Coordinates
local p1xcoordinate = memory.readbyte(0x009E);
local p1ycoordinate = memory.readbyte(0x00A1);
text(10,35,"P C: " .. p1xcoordinate .. "," .. 240 - p1ycoordinate);
-- Player HPs
local p1hp = memory.readbyte(0x0431);
text(10,45,"P HP: " .. p1hp);
-- Player MPs:
local p1mp = memory.readbyte(0x039A);
text(10,55,"P MP: " .. p1mp);
-- Sprite 1 HPs
local e1hp = memory.readbyte(0x034B);
text(10,65,"S1 HP: " .. e1hp);
-- Sprite 2 HPs
local e2hp = memory.readbyte(0x034A);
text(10,75,"S2 HP: " .. e2hp);
-- Sprite 3 HPs
local e3hp = memory.readbyte(0x0349);
text(10,85,"S3 HP: " .. e3hp);
FCEU.frameadvance();
end;
|
PrefabFiles = {
"xenoth",
"xenoth_none",
}
Assets = {
Asset( "IMAGE", "images/saveslot_portraits/xenoth.tex" ),
Asset( "ATLAS", "images/saveslot_portraits/xenoth.xml" ),
Asset( "IMAGE", "images/selectscreen_portraits/xenoth.tex" ),
Asset( "ATLAS", "images/selectscreen_portraits/xenoth.xml" ),
Asset( "IMAGE", "images/selectscreen_portraits/xenoth_silho.tex" ),
Asset( "ATLAS", "images/selectscreen_portraits/xenoth_silho.xml" ),
Asset( "IMAGE", "bigportraits/xenoth.tex" ),
Asset( "ATLAS", "bigportraits/xenoth.xml" ),
Asset( "IMAGE", "images/map_icons/xenoth.tex" ),
Asset( "ATLAS", "images/map_icons/xenoth.xml" ),
Asset( "IMAGE", "images/avatars/avatar_xenoth.tex" ),
Asset( "ATLAS", "images/avatars/avatar_xenoth.xml" ),
Asset( "IMAGE", "images/avatars/avatar_ghost_xenoth.tex" ),
Asset( "ATLAS", "images/avatars/avatar_ghost_xenoth.xml" ),
Asset( "IMAGE", "images/avatars/self_inspect_xenoth.tex" ),
Asset( "ATLAS", "images/avatars/self_inspect_xenoth.xml" ),
Asset( "IMAGE", "images/names_xenoth.tex" ),
Asset( "ATLAS", "images/names_xenoth.xml" ),
Asset( "IMAGE", "bigportraits/xenoth_none.tex" ),
Asset( "ATLAS", "bigportraits/xenoth_none.xml" ),
}
local require = GLOBAL.require
local STRINGS = GLOBAL.STRINGS
-- The character select screen lines
STRINGS.CHARACTER_TITLES.xenoth = "The Blue Dragon"
STRINGS.CHARACTER_NAMES.xenoth = "Xenoth"
STRINGS.CHARACTER_DESCRIPTIONS.xenoth = "*Nudist\n*Vegetarian Derg\n*Used to Obscurity\n*Animals Lover"
STRINGS.CHARACTER_QUOTES.xenoth = "\"Don't boop me!\""
-- Custom speech strings
STRINGS.CHARACTERS.XENOTH = require "speech_xenoth"
-- The character's name as appears in-game
STRINGS.NAMES.XENOTH = "Xen"
AddMinimapAtlas("images/map_icons/xenoth.xml")
-- Add mod character to mod character list. Also specify a gender. Possible genders are MALE, FEMALE, ROBOT, NEUTRAL, and PLURAL.
AddModCharacter("xenoth", "MALE")
|
local oo = require 'lualib.oo'
local bigint = require 'lualib.bigint'
local RSA = oo.class()
function RSA:_init(opts)
-- public key is (e, n), required for encrypting messages:
self.e = opts.e or bigint.new(65537)
self.n = opts.n
-- private key component d:
self.d = opts.d
-- p&q (the prime factors of n) are optional, but they can accelerate decryption:
self.p = opts.p
self.q = opts.q
end
function RSA.setup(p, q, e)
-- p&q are prime numbers, default exponent is usually either 3 (unsafe?) or 2^16+1
e = e or bigint.new(65537)
-- Charmichael's Totien of n, used for computing d:
local pm1, qm1 = p-bigint.one, q-bigint.one
local ctn = pm1 / pm1:gcd(qm1) * qm1
return RSA:new{e=e, d=e:invmod(ctn), n=p*q, p=p, q=q}
end
function RSA:bigint_encrypt(m)
return m:powmod(self.e, self.n)
end
function RSA:bigint_sign(m)
-- signing in RSA is powmodding with the private key (aka decryption):
return self:bigint_decrypt(m)
end
function RSA:bigint_is_signature_valid(m, s)
-- to verify the signature is powmodding with the public key (aka encryption):
return m == self:bigint_encrypt(s)
end
function RSA:bigint_decrypt(c)
-- using the Chinese Remainder Theorem:
if self.p and self.q then
if not self.qinv then
self.dp = self.d % (self.p-bigint.one)
self.dq = self.d % (self.q-bigint.one)
self.qinv = self.q:invmod(self.p)
end
local m1 = c:powmod(self.dp, self.p)
local m2 = c:powmod(self.dq, self.q)
local h = self.qinv * (m1 - m2) % self.p
return (m2 + h * self.q) % self.n
end
-- simplified slower computation:
return c:powmod(self.d, self.n)
end
return RSA
|
RandomMerchantNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
local choices = {"Follow him", "Attack him", "Ignore him"}
local choice = player:menuSeq(
"A scraggly dressed fellow subtly motions for you to follow him.",
choices,
{}
)
if choice == 1 then
player:dialogSeq({t, "You follow him into a quiet alley."}, 1)
local chance = math.random(1, 100)
if chance >= 1 and chance < 50 then
--attack/evade
player.attacker = player.ID
player:sendAnimation(6, 30)
player:sendMinitext("THUD!")
player:removeHealthExtend(
math.floor(player.baseHealth * 0.25),
0,
0,
0,
0,
0
)
player:dialogSeq({t, "The thief ducks into the shadows."}, 0)
return
elseif chance >= 50 then
RandomMerchantNpc.presentDeal(player, npc)
end
elseif choice == 2 then
--attack
player:dialogSeq(
{
t,
"As you move aggressively towards him, he ducks into the shadows and vanishes from sight."
},
1
)
return
elseif choice == 3 then
--ignore
player:dialogSeq({t, "He vanishes as suddenly as he appeared."}, 0)
return
end
end),
presentDeal = function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
local goldChoices = {}
for i = 1, 6 do
table.insert(goldChoices, 1000)
end
for i = 1, 4 do
table.insert(goldChoices, 5000)
end
for i = 1, 2 do
table.insert(goldChoices, 8000)
end
for i = 1, 1 do
table.insert(goldChoices, 50000)
end
local goldChoice = goldChoices[math.random(1, #goldChoices)]
if player.ID == 2 then
goldChoice = 1000
end
local choice = 0
if goldChoice == 1000 then
-- message
choice = player:menuSeq(
"He looks at you eagerly, 'I got some information you might be interested in. Give me " .. Tools.formatNumber(goldChoice) .. " gold for it?'",
{"Yes, I'll pay.", "No thanks."},
{}
)
else
choice = player:menuSeq(
"The thief takes a shiny object from his pocket. 'I got some information you might be interested in. Give me " .. Tools.formatNumber(goldChoice) .. " gold for it?'",
{"Yes, I'll pay.", "No thanks."},
{}
)
end
if choice == 1 then
-- yes
if player.money < goldChoice then
-- not enough money
player:dialogSeq({t, "You don't have enough gold."}, 0)
return
end
player:removeGold(goldChoice)
if math.random(1, 3) <= 2 then
-- get hussled 50% chance to have the thief take your money
player:dialogSeq(
{
t,
"'Thanks for the money, sucker!' The merchant disappears with your gold."
},
0
)
return
else
-- give item or message
local item = ""
if goldChoice == 1000 then
local messages = {}
table.insert(
messages,
"There is some old sewers that are beneath the library in Buya."
)
local bosses = {"Horse", "Ox", "Pig"}
local i = math.random(3)
local boss = bosses[i]
table.insert(messages, boss .. " Avenger may drop something special.")
-- check for strange thing spawn
local mobs = player:getObjectsInMap(2500, BL_MOB)
local mobs2 = player:getObjectsInMap(1009, BL_MOB)
if #mobs > 0 then
for i = 1, #mobs do
if mobs[i].yname == "strange_thing" then
table.insert(
messages,
"I recently spotted a strange creature in Nagnang around coordinates X: " .. mobs[
i
].x .. " Y: " .. mobs[i].y
)
break
end
end
end
if #mobs2 > 0 then
for i = 1, #mobs2 do
if mobs2[i].yname == "strange_thing" then
table.insert(
messages,
"I recently spotted a strange creature in Southern Koguryo around coordinates X: " .. mobs2[
i
].x .. " Y: " .. mobs2[i].y
)
break
end
end
end
player:dialogSeq(
{t, messages[math.random(1, #messages)]},
0
)
return
elseif goldChoice == 5000 then
item = "sea_poems"
-- gives sea poem
elseif goldChoice == 8000 then
local weaps = {"electra", "titanium_lance", "steelthorn", "star_staff"}
item = weaps[math.random(1, #weaps)]
elseif goldChoice == 50000 then
if math.random(1, 250) == 1 then
item = Item("chaos_blade")
local tfb = {
graphic = item.icon,
color = item.iconColor
}
player:addItem("chaos_blade", 1)
broadcast(
-1,
"[SYSTEM]: " .. player.name .. " has just received a Chaos blade from the Random Merchant!"
)
player:dialogSeq(
{
tfb,
"He holds up the shiny object and begins to twirl it around. The merchant decides to be generous and hands you the blade before disappearing."
},
0
)
return
else
local elements = {
"Earth",
"Fire",
"Metal",
"Water",
"Wood"
}
local animals = {
"Dragon",
"Tiger",
"Ox",
"Snake",
"Horse",
"Rabbit",
"Rat",
"Monkey",
"Sheep",
"Pig",
"Dog",
"Rooster"
}
local elementChoice = math.random(1, #elements)
local animalChoice = math.random(1, #animals)
if player.quest["soe_elementChoice"] == 0 then
-- only set these if people have not did it before
player.quest["soe_elementChoice"] = elementChoice
player.quest["soe_animalChoice"] = animalChoice
end
player:dialogSeq(
{
t,
"He holds up the shiny object and begins to twirl it around. Its softly twinkling lights lull you into a gentle, peaceful trance. A vision of a " .. elements[
elementChoice
] .. " " .. animals[animalChoice] .. " appears before you and says, 'Do not be afraid my child. I am here to protect you.'",
"You snap out of the trance as the thief puts the object away. He seems disappointed. 'Seems that damn gypsy sold me a dud! Well thanks for the money, sucker!' He vanishes as suddenly as he had appeared."
},
0
)
return
end
end
if item ~= "" then
player:addItem(item, 1)
player:dialogSeq(
{t, "You receive a " .. Item(item).name .. "!"},
1
)
player:dialogSeq(
{t, "The merchant vanishes as quickly as he appeared."},
0
)
return
end
end
elseif choice == 2 then
-- no
player:dialogSeq(
{t, "'Suit yourself.' He vanishes as suddenly as he appeared."},
0
)
return
end
end
}
|
return {'akyol'} |
local f = function()
end
local function f2()
-- body
end
local function f3()
-- body
end
local function f4()
local t = 13
end
local function f5()
f4(function()
local d = 13
end)
end
|
ITEM.name = "9x18mm +P"
ITEM.model = "models/lostsignalproject/items/ammo/9x18.mdl"
ITEM.ammo = "9x18MM -HP-" // type of the ammo
ITEM.ammoAmount = 60 // amount of the ammo
ITEM.description = ""
ITEM.quantdesc = "A box that contains %s rounds of Hollow-Point 9x18mm ammo. "
ITEM.longdesc = "This repurposed 9x18mm round contains full metal jacket rounds with a steel penetrator and a lead core under a metal jacket."
ITEM.price = 600
ITEM.img = ix.util.GetMaterial("cotz/icons/ammo/ammo_short_3_2.png")
ITEM.weight = 0.010
ITEM.flatweight = 0.05
function ITEM:GetWeight()
return self.flatweight + (self.weight * self:GetData("quantity", self.ammoAmount))
end
|
local oc = oc or function(...) return ... end
function weld(p0,p1,c0,c1,par)
local w = Instance.new("Weld",p0 or par)
w.Part0 = p0
w.Part1 = p1
w.C0 = c0 or CFrame.new()
w.C1 = c1 or CFrame.new()
return w
end
function lerp(a, b, t)
return a + (b - a)*t
end
do
local function QuaternionFromCFrame(cf) local mx, my, mz, m00, m01, m02, m10, m11, m12, m20, m21, m22 = cf:components() local trace = m00 + m11 + m22 if trace > 0 then local s = math.sqrt(1 + trace) local recip = 0.5/s return (m21-m12)*recip, (m02-m20)*recip, (m10-m01)*recip, s*0.5 else local i = 0 if m11 > m00 then i = 1 end if m22 > (i == 0 and m00 or m11) then i = 2 end if i == 0 then local s = math.sqrt(m00-m11-m22+1) local recip = 0.5/s return 0.5*s, (m10+m01)*recip, (m20+m02)*recip, (m21-m12)*recip elseif i == 1 then local s = math.sqrt(m11-m22-m00+1) local recip = 0.5/s return (m01+m10)*recip, 0.5*s, (m21+m12)*recip, (m02-m20)*recip elseif i == 2 then local s = math.sqrt(m22-m00-m11+1) local recip = 0.5/s return (m02+m20)*recip, (m12+m21)*recip, 0.5*s, (m10-m01)*recip end end end
local function QuaternionToCFrame(px, py, pz, x, y, z, w) local xs, ys, zs = x + x, y + y, z + z local wx, wy, wz = w*xs, w*ys, w*zs local xx = x*xs local xy = x*ys local xz = x*zs local yy = y*ys local yz = y*zs local zz = z*zs return CFrame.new(px, py, pz,1-(yy+zz), xy - wz, xz + wy,xy + wz, 1-(xx+zz), yz - wx, xz - wy, yz + wx, 1-(xx+yy)) end
local function QuaternionSlerp(a, b, t) local cosTheta = a[1]*b[1] + a[2]*b[2] + a[3]*b[3] + a[4]*b[4] local startInterp, finishInterp; if cosTheta >= 0.0001 then if (1 - cosTheta) > 0.0001 then local theta = math.acos(cosTheta) local invSinTheta = 1/math.sin(theta) startInterp = math.sin((1-t)*theta)*invSinTheta finishInterp = math.sin(t*theta)*invSinTheta else startInterp = 1-t finishInterp = t end else if (1+cosTheta) > 0.0001 then local theta = math.acos(-cosTheta) local invSinTheta = 1/math.sin(theta) startInterp = math.sin((t-1)*theta)*invSinTheta finishInterp = math.sin(t*theta)*invSinTheta else startInterp = t-1 finishInterp = t end end return a[1]*startInterp + b[1]*finishInterp, a[2]*startInterp + b[2]*finishInterp, a[3]*startInterp + b[3]*finishInterp, a[4]*startInterp + b[4]*finishInterp end
function clerp(a,b,t)
local qa = {QuaternionFromCFrame(a)}
local qb = {QuaternionFromCFrame(b)}
local ax, ay, az = a.x, a.y, a.z
local bx, by, bz = b.x, b.y, b.z
local _t = 1-t
return QuaternionToCFrame(_t*ax + t*bx, _t*ay + t*by, _t*az + t*bz,QuaternionSlerp(qa, qb, t))
end
end
local his = {}
function ctween(tar,prop,c2,t,b)
local function doIt()
local now = tick()
his[tar] = now
local c1 = tar[prop]
for i=1,t do
if his[tar] ~= now then return end
tar[prop] = clerp(c1,c2,1/t*i)
wait(1/60)
end
end
if b then coroutine.wrap(doIt)() else doIt() end
end
function tickwave(time,length,offset)
return (math.abs((tick()+(offset or 0))%time-time/2)*2-time/2)/time/2*length
end
function playSound(id,parent,volume,pitch)
local sound = Instance.new("Sound",parent or workspace)
sound.SoundId = "http://www.roblox.com/asset?id="..id
sound.Volume = volume or 1
sound.Pitch = pitch or 1
coroutine.wrap(function()
wait()
sound:Play()
wait(10)
sound:Stop()
sound:Destroy()
end)()
return sound
end
local plr = game.Players.LocalPlayer
local char = plr.Character
local mouse = plr:GetMouse()
local nk = char.Torso.Neck
local nk0 = CFrame.new(0,1,0) * CFrame.Angles(-math.pi/2,0,math.pi)
local ra,la = char["Right Arm"], char["Left Arm"]
ra:BreakJoints()
la:BreakJoints()
local rs = weld(char.Torso,ra,CFrame.new(1.25,.5,0), CFrame.new(-.25,.5,0),stuff)
local ls = weld(char.Torso,la,CFrame.new(-1.25,.5,0), CFrame.new(.25,.5,0),stuff)
ls.Part1.FrontSurface = "Hinge"
rs.Part1.FrontSurface = "Hinge"
local rs0 = rs.C0
local ls0 = ls.C0
local color1 = BrickColor.new("Dark gray")
local color2 = BrickColor.new("Navy blue")
local stuff = Instance.new("Model",char)
pcall(function() char["Hammur"]:Destroy() end)
stuff.Name = "Hammur"
wait(.5)
local handle = Instance.new("Part")
handle.FormFactor = "Custom"
handle.BrickColor = color1
handle.Reflectance = .25
handle.Size = Vector3.new(.5,5,.5)
handle.TopSurface = "Smooth"
handle.BottomSurface = "Smooth"
handle.CanCollide = false
handle.Parent = stuff
local grip = weld(char["Right Arm"],handle,CFrame.new(0,-.95,0)*CFrame.Angles(math.rad(-90),0,0),CFrame.new(0,-1.4,0))
local grip0 = grip.C0
local hamend = handle:Clone()
Instance.new("BlockMesh",hamend)
hamend.Parent = stuff
hamend.Size = Vector3.new(2,2,3.5)
local hamwel = weld(handle,hamend,CFrame.new(0,3,0))
local hamsd1 = hamend:Clone()
hamsd1.Mesh.Scale = Vector3.new(1,1,1)
hamsd1.Parent = stuff
hamsd1.Size = Vector3.new(2.3,2.3,.3)
weld(hamend,hamsd1,CFrame.new(0,0,1.75))
local hamsd2 = hamsd1:Clone()
hamsd2.Parent = stuff
weld(hamend,hamsd2,CFrame.new(0,0,-1.75))
local hamp = hamsd1:Clone()
hamp.Parent = stuff
hamp.Size = Vector3.new(.2,.2,3.5)
weld(hamend,hamp,CFrame.new(.95,.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.95,-.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.95,-.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.95,.95,0))
hamp = hamp:Clone()
hamp.BrickColor = color2
hamp.Reflectance = .2
hamp.Size = Vector3.new(.2,.2,2.5)
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(0,.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(0,-.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.95,0,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.95,0,0))
hamp = handle:Clone()
hamp.BrickColor = color2
hamp.Reflectance = .2
hamp.Parent = stuff
hamp.Size = Vector3.new(.4,.2,.4)
Instance.new("CylinderMesh",hamp)
weld(hamend,hamp,CFrame.new(0,-.955,1.2))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(0,-.955,-1.2))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(0,.955,1.2))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(0,.955,-1.2))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.955,0,-1.2) * CFrame.Angles(0,0,math.rad(90)))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.955,0,1.2) * CFrame.Angles(0,0,math.rad(90)))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.955,0,-1.2) * CFrame.Angles(0,0,math.rad(90)))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.955,0,1.2) * CFrame.Angles(0,0,math.rad(90)))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.6,.955,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.6,.955,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.6,-.955,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.6,-.955,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.955,.6,0) * CFrame.Angles(0,0,math.rad(90)))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.955,-.6,0) * CFrame.Angles(0,0,math.rad(90)))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.955,.6,0) * CFrame.Angles(0,0,math.rad(90)))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.955,-.6,0) * CFrame.Angles(0,0,math.rad(90)))
local luacyl = hamp:Clone()
luacyl.BrickColor = BrickColor.Blue()
luacyl.Parent = stuff
luacyl.Mesh.Scale = Vector3.new(1,.2,1)
luacyl.Size = Vector3.new(2,.2,2)
weld(hamsd1,luacyl,CFrame.new(0,0,.14) * CFrame.Angles(math.rad(90),0,0))
hamp = luacyl:Clone()
hamp.BrickColor = BrickColor.White()
hamp.Parent = stuff
hamp.Size = Vector3.new(.7,.2,.7)
weld(luacyl,hamp,CFrame.new(.35,.01,-.35))
local luamoon = luacyl:Clone()
luamoon.Parent = stuff
luamoon.Size = Vector3.new(.7,.2,.7)
local mnw = weld(luacyl,luamoon,CFrame.new(1.2,.02,-1.2))
for r = 1,180,10 do
local r2 = 2 * (math.pi/180*r)
local l = hamsd1:Clone()
l.Parent = stuff
l.BrickColor = luacyl.BrickColor
l.Size = Vector3.new(.3,.2,.2)
l.Mesh.Scale = Vector3.new(1,.3,.3)
weld(luacyl,l,CFrame.new(Vector3.new(math.sin(r2)*1.7,0,math.cos(r2)*1.7),Vector3.new()))
end
hamp = hamend:Clone()
hamp.BrickColor = color2
hamp.Reflectance = .2
hamp.Size = Vector3.new(.2,.2,3.5)
hamp.Mesh.Scale = Vector3.new(.25,.25,1)
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-1.05,.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.95,1.05,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(1.05,.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.95,1.05,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(1.05,-.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(.95,-1.05,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-1.05,-.95,0))
hamp = hamp:Clone()
hamp.Parent = stuff
weld(hamend,hamp,CFrame.new(-.95,-1.05,0))
for x = -1,1 do
for y = -1,1 do
hamp = hamp:Clone()
hamp.Mesh.Scale = Vector3.new(1,1,1)
hamp.Size = Vector3.new(.5,.5,.2)
hamp.Parent = stuff
weld(hamsd2,hamp,CFrame.new(x*.7,y*.7,-.1))
end
end
rs.C0 = rs0 * CFrame.Angles(math.rad(70),math.rad(50),math.rad(-20))
ls.C0 = ls0 * CFrame.new(.4,.2,-.3) * CFrame.Angles(math.rad(110),math.rad(0),math.rad(00)) * CFrame.Angles(0,math.rad(60),0)
function endScript()
pcall(function() runcon:disconnect() end)
pcall(function() kdcon:disconnect() end)
pcall(function() kucon:disconnect() end)
pcall(game.Destroy,stuff)
pcall(game.Destroy,bg)
pcall(game.Destroy,bv)
end
local spintime = 3
local idling = true
runcon = game:GetService("RunService").Stepped:connect(oc(function()
if not stuff:IsDescendantOf(workspace) then
endScript()
end
local an = (tick()%spintime)*360/spintime
mnw.C0 = CFrame.Angles(0,math.rad(an),0) * CFrame.new(0,.04,1.7)
if idling then
rs.C0 = clerp(rs.C0,rs0 * CFrame.Angles(math.rad(70+tickwave(3,5)),math.rad(50),math.rad(-20)),.4)
ls.C0 = clerp(ls.C0,ls0 * CFrame.new(.4,.2,-.3) * CFrame.Angles(math.rad(115+tickwave(3,5)),math.rad(0),math.rad(-5)) * CFrame.Angles(0,math.rad(60),0),.4)
nk.C0 = clerp(nk.C0,nk0 * CFrame.Angles(tickwave(4,-.1),0,0),.4)
grip.C0 = clerp(grip.C0,grip0,.4)
end
end))
function cfot(tar,cf,t)
coroutine.wrap(function()
for i=1,t do
tar.CFrame = tar.CFrame * cf
wait(1/30)
end
end)()
end
function DoDamage(hum,dmg)
if hum.Health == 0 then return end
local a,b = ypcall(function()
--hum:TakeDamage(dmg)
hum.Health = hum.Health - dmg
if not hum.Parent:FindFirstChild("Torso") then return end
local m = Instance.new("Model",workspace)
m.Name = -dmg
local h = Instance.new("Humanoid",m)
h.MaxHealth = 0
local p = Instance.new("Part",m)
p.Name = "Head"
p.FormFactor = "Custom"
p.Size = Vector3.new(.2,.2,.2)
p.Transparency = 0.97
p.CanCollide = false
p.Anchored = true
p:BreakJoints()
game.Debris:AddItem(m,5)
p.CFrame = CFrame.new(hum.Parent.Torso.Position) * CFrame.new(math.random(-2,2),2.5,math.random(-2,2))
local rAm = math.random(3,6)/100
coroutine.wrap(function()
for i=1,300 do
p.CFrame = p.CFrame * CFrame.new(0,rAm,0)
wait()
end
p:Destroy()
end)()
end)
if not a then print(b) end
end
local atdeb = false
local basiccombo = 0
local basiccombotimer = 0
bg = Instance.new("BodyGyro",char.Torso)
bg.maxTorque = Vector3.new(1,0,1)*9e10
bg.P = 10000
bg.D = 500
bv = Instance.new("BodyVelocity",char.Torso)
bv.maxForce = Vector3.new()
bv.P = 50000
kucon = mouse.KeyUp:connect(oc(function(k)
if k == "0" and sprint then
pcall(function() char.Humanoid.WalkSpeed = char.Humanoid.WalkSpeed / 1.5 end)
sprint = false
end
end))
kdcon = mouse.KeyDown:connect(oc(function(k)
if k == "0" and not sprint then
pcall(function() char.Humanoid.WalkSpeed = char.Humanoid.WalkSpeed * 1.5 end)
sprint = true
end
if k == "f" then
if atdeb then return end
atdeb = true
idling = false
playSound(105374058,hamend,1,1)
--- bg.cframe = char.Torso.CFrame * CFrame.Angles(math.rad(7),0,0)
-- ctween(nk,"C0",nk0 * CFrame.Angles(math.rad(-20),0,0),7,true)
ctween(rs,"C0",rs0*CFrame.new(-.7,0,-.7) * CFrame.Angles(math.rad(150),math.rad(0),math.rad(-90)),7)
ctween(ls,"C0",ls0*CFrame.new(.7,0,-.7) * CFrame.Angles(math.rad(160),math.rad(0),math.rad(30)),13,true)
ctween(nk,"C0",nk0 * CFrame.Angles(math.rad(-35),0,0),13,true)
ctween(rs,"C0",rs0*CFrame.new(-.7,0,-.7) * CFrame.Angles(math.rad(160),math.rad(0),math.rad(60)),13)
playSound(92597296,hamend,1,1.07)
local s = playSound(96626016,hamend)
s.Volume = 0
local hitcon
hitcon = hamend.Touched:connect(function(hit)
s.Volume = 1
if not hit.Anchored then
hit.Velocity = hit.Velocity + hamend.CFrame.lookVector*-20
end
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum and not hum:IsDescendantOf(char) then
DoDamage(hum,30)
hum.PlatformStand = true
wait(.6)
hum.PlatformStand = false
end
end)
bg.maxTorque = Vector3.new(1,1,1)*9e10
ctween(ls,"C0",ls0*CFrame.new(.7,0,-.7) * CFrame.Angles(math.rad(35),math.rad(0),math.rad(30)),4,true)
ctween(nk,"C0",nk0 * CFrame.Angles(math.rad(35),0,0),4,true)
ctween(rs,"C0",rs0*CFrame.new(-.7,0,-.7) * CFrame.Angles(math.rad(35),math.rad(0),math.rad(-30)),4)
if workspace:FindPartOnRay(Ray.new(hamend.Position,hamend.CFrame.lookVector*3),char) then
s.Volume = 1
end
wait(.2)
bg.maxTorque = Vector3.new(1,0,1)*9e10
hitcon:disconnect()
atdeb = false
idling = true
end
if k == "q" then
if atdeb then return end
atdeb = true
idling = false
playSound(105374058,hamend,1,1)
bg.cframe = char.Torso.CFrame * CFrame.Angles(math.rad(7),0,0)
ctween(grip,"C0",grip0*CFrame.Angles(math.rad(-30),math.rad(-25),math.rad(-15)),9,true)
ctween(ls,"C0",ls0*CFrame.new(.7,0,-.7) * CFrame.Angles(math.rad(150),math.rad(0),math.rad(30)),7,true)
ctween(nk,"C0",nk0 * CFrame.Angles(math.rad(-20),0,0),7,true)
ctween(rs,"C0",rs0*CFrame.new(-.7,0,-.7) * CFrame.Angles(math.rad(150),math.rad(0),math.rad(-30)),7)
ctween(ls,"C0",ls0*CFrame.new(.7,0,-.7) * CFrame.Angles(math.rad(160),math.rad(0),math.rad(30)),13,true)
ctween(nk,"C0",nk0 * CFrame.Angles(math.rad(-35),0,0),13,true)
ctween(rs,"C0",rs0*CFrame.new(-.7,0,-.7) * CFrame.Angles(math.rad(160),math.rad(0),math.rad(-30)),13)
playSound(92597296,hamend,1,1.07)
local s = playSound(96626016,hamend)
s.Volume = 0
local hitcon
hitcon = hamend.Touched:connect(function(hit)
s.Volume = 1
if not hit.Anchored then
hit.Velocity = hit.Velocity + hamend.CFrame.lookVector*-20
end
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum and not hum:IsDescendantOf(char) then
DoDamage(hum,30)
hum.PlatformStand = true
wait(.6)
hum.PlatformStand = false
end
end)
bg.cframe = char.Torso.CFrame * CFrame.Angles(math.rad(7),0,0)
wait(.05)
bg.cframe = char.Torso.CFrame * CFrame.Angles(math.rad(-20),0,0)
bg.maxTorque = Vector3.new(1,1,1)*9e10
ctween(ls,"C0",ls0*CFrame.new(.7,0,-.7) * CFrame.Angles(math.rad(55),math.rad(5),math.rad(50)),7,true)
ctween(nk,"C0",nk0 * CFrame.Angles(math.rad(5),0,0),4,true)
ctween(rs,"C0",rs0*CFrame.new(-.9,0,-.9) * CFrame.Angles(math.rad(50),math.rad(5),math.rad(-50)),7)
if workspace:FindPartOnRay(Ray.new(hamend.Position,hamend.CFrame.lookVector*3),char) then
s.Volume = 1
end
wait(.2)
bg.maxTorque = Vector3.new(1,0,1)*9e10
hitcon:disconnect()
atdeb = false
idling = true
end
if k == "r" then
if atdeb then return end
atdeb = true
idling = false
ctween(ls,"C0",ls0*CFrame.new(.7,0,-.7) * CFrame.Angles(math.rad(70),math.rad(0),math.rad(30)),7,true)
ctween(grip,"C0",grip0*CFrame.Angles(math.rad(0),math.rad(90),math.rad(-60))*CFrame.Angles(0,math.rad(180),0),9,true)
bg.maxTorque = Vector3.new(1,1,1)*9e10
bg.cframe = char.Torso.CFrame
ctween(rs,"C0",rs0*CFrame.new(-.7,0,-.7) * CFrame.Angles(math.rad(70),math.rad(0),math.rad(-30)),7,true)
local s = playSound(92597296,hamend,1,1.07)
s.Looped = true
local sndmd = {}
local hitcon
hitcon = hamend.Touched:connect(function(hit)
if not sndmd[hit] then sndmd[hit] = playSound(10730819,hamend) end
if not hit.Anchored then
hit.Velocity = hit.Velocity + hamend.CFrame.lookVector*60
end
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum and not hum:IsDescendantOf(char) then
DoDamage(hum,math.random(4,6))
hum.Sit = true
wait(2)
hum.Sit = false
end
end)
for i=1,20 do
bg.cframe = bg.cframe * CFrame.Angles(0,math.rad(-1440/20),0)
wait(.1)
end
hitcon:disconnect()
bg.maxTorque = Vector3.new(1,0,1)*9e10
s:Stop()
s:Destroy()
atdeb = false
idling = true
end
if k == "e" then
if atdeb then return end
basiccombo = (tick()-basiccombotimer > .5 or basiccombo == 2) and 1 or basiccombo + 1
idling = false
atdeb = true
if basiccombo == 1 then
ctween(ls,"C0",ls0 * CFrame.new(.2,.2,-.1) * CFrame.Angles(math.rad(120),math.rad(0),math.rad(5)) * CFrame.Angles(0,math.rad(60),0),7,true)
ctween(rs,"C0",rs0*CFrame.new(0,0,-.3) * CFrame.Angles(math.rad(120),math.rad(70),math.rad(-30)),7)
bg.maxTorque = Vector3.new(1,1,1)*9e10
bg.cframe = char.Torso.CFrame * CFrame.Angles(0,math.rad(-40),0)
playSound(92597296,hamend,1,1.2)
local ac
local hitcon
hitcon = hamend.Touched:connect(function(hit)
if not ac then ac = playSound(10730819,hamend,1,1) end
if not hit.Anchored then
hit.Velocity = hit.Velocity + hamend.CFrame.lookVector*50
end
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum and not hum:IsDescendantOf(char) then
DoDamage(hum,10)
end
end)
ctween(ls,"C0",ls0 * CFrame.new(1,.2,-1) * CFrame.Angles(math.rad(115),math.rad(0),math.rad(40)) * CFrame.Angles(0,math.rad(60),0),6,true)
ctween(rs,"C0",rs0*CFrame.new(0,0,-.3) * CFrame.Angles(math.rad(120),math.rad(80),math.rad(-30))* CFrame.Angles(math.rad(-50),0,0),6,true)
wait(.1)
bg.cframe = char.Torso.CFrame * CFrame.Angles(0,math.rad(40),0)
hitcon:disconnect()
elseif basiccombo == 2 then
ctween(ls,"C0",ls0*CFrame.new(1,0,-1) * CFrame.Angles(math.rad(5),math.rad(0),math.rad(70)),10,true)
ctween(grip,"C0",grip0*CFrame.Angles(math.rad(10),0,0),12,true)
ctween(rs,"C0",rs0*CFrame.new(0,0,0) * CFrame.Angles(math.rad(-5),math.rad(0),math.rad(0)),10,true)
wait(.2)
playSound(92597296,hamend,1,.7)
wait(.1)
bg.maxTorque = Vector3.new(1,1,1)*9e10
bg.cframe = char.Torso.CFrame
bv.maxForce = Vector3.new(1,0,1)*9e5
bv.velocity = bg.cframe.lookVector * 70
coroutine.wrap(function() for i=1,25 do bv.velocity = bv.velocity*.9 wait(1/30) end bv.maxForce = Vector3.new() end)()
local thrustcon
thrustcon = hamend.Touched:connect(function(hit)
if not hit.Anchored then
hit.Velocity = hit.Velocity + hamend.CFrame.lookVector*-40
end
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum and not hum:IsDescendantOf(char) then
DoDamage(hum,5)
--thrustcon:disconnect()
hum.Sit = true
ctween(grip,"C0",grip0*CFrame.Angles(math.rad(30),0,0),5,true)
if not ac then ac = playSound(92597296,hamend,1,1.15) end
local tor = hum.Parent:FindFirstChild("Torso")
if tor and not tor:FindFirstChild("torv") then
--tor.Velocity = bg.cframe.lookVector*30 + Vector3.new(0,100,0)
local torv = Instance.new("BodyVelocity",tor)
torv.maxForce = Vector3.new(1,1,1)*9e9
torv.P = 2000
torv.velocity = bg.cframe.lookVector*20 + Vector3.new(0,120,0)
torv.Name = "torv"
local torav = Instance.new("BodyAngularVelocity",tor)
torav.maxTorque = Vector3.new(1,1,1)*9e9
torav.P = 5000
torav.angularvelocity = Vector3.new(math.random()-.5,math.random()-.5,math.random()-.5)*2
coroutine.wrap(function()
for i=1,torv.velocity.Y/196.22*30 do
hum.Sit = true
torv.velocity = torv.velocity - Vector3.new(0,196.22/30,0)
wait(1/30)
end
torv:Destroy()
torav:Destroy()
tor.Velocity = Vector3.new()
end)()
end
end
end)
ctween(ls,"C0",ls0*CFrame.new(1,0,-1) * CFrame.Angles(math.rad(80),math.rad(0),math.rad(50)),12,true)
ctween(grip,"C0",grip0*CFrame.Angles(math.rad(-70),0,0),12,true)
ctween(rs,"C0",rs0*CFrame.new(-.6,0,-.7) * CFrame.Angles(math.rad(90),math.rad(0),math.rad(-10)),12,true)
Delay(.3,function() thrustcon:disconnect() end)
end
wait(.1)
bg.maxTorque = Vector3.new(1,0,1)*9e10
basiccombotimer = tick()
atdeb = false
idling = true
end -- 96626016, 92597296
bg.cframe = CFrame.new(char.Torso.Position,char.Torso.Position+char.Torso.CFrame.lookVector*Vector3.new(1,0,1))
end))
char.Humanoid.MaxHealth = 220
char.Humanoid.WalkSpeed = 20
wait(.3)
char.Humanoid.Health = 220
|
dofile(yatm_foundry.modpath .. "/tests/blasting_registry_test.lua")
dofile(yatm_foundry.modpath .. "/tests/kiln_registry_test.lua")
dofile(yatm_foundry.modpath .. "/tests/molding_registry_test.lua")
dofile(yatm_foundry.modpath .. "/tests/smelting_registry_test.lua")
|
--
-- Author: zhong
-- Date: 2016-11-21 18:39:13
--
--设置界面
local ExternalFun = require(appdf.EXTERNAL_SRC .. "ExternalFun")
local SettingLayer = class("SettingLayer", cc.Layer)
SettingLayer.BT_EFFECT = 1
SettingLayer.BT_MUSIC = 2
SettingLayer.BT_CLOSE = 3
--构造
function SettingLayer:ctor( )
--注册触摸事件
ExternalFun.registerTouchEvent(self, true)
--加载csb资源
local csbNode = ExternalFun.loadCSB("setting/SettingLayer.csb", self)
local cbtlistener = function (sender,eventType)
self:onSelectedEvent(sender:getTag(),sender,eventType)
end
local sp_bg = csbNode:getChildByName("setting_bg")
self.m_spBg = sp_bg
--关闭按钮
local btn = sp_bg:getChildByName("close_btn")
btn:setTag(SettingLayer.BT_CLOSE)
btn:addTouchEventListener(function (ref, eventType)
if eventType == ccui.TouchEventType.ended then
ExternalFun.playClickEffect()
self:removeFromParent()
end
end)
--switch
--音效
self.m_btnEffect = sp_bg:getChildByName("check_effect")
self.m_btnEffect:setTag(SettingLayer.BT_EFFECT)
self.m_btnEffect:addEventListener(cbtlistener)
self.m_btnEffect:setSelected(GlobalUserItem.bSoundAble)
--音乐
self.m_btnMusic = sp_bg:getChildByName("check_bg")
self.m_btnMusic:setTag(SettingLayer.BT_MUSIC)
self.m_btnMusic:addEventListener(cbtlistener)
self.m_btnMusic:setSelected(GlobalUserItem.bVoiceAble)
end
--
function SettingLayer:showLayer( var )
self:setVisible(var)
end
function SettingLayer:onSelectedEvent( tag, sender )
if SettingLayer.BT_MUSIC == tag then
local music = not GlobalUserItem.bVoiceAble
GlobalUserItem.setVoiceAble(music)
if GlobalUserItem.bVoiceAble == true then
ExternalFun.playBackgroudAudio("background.mp3")
end
elseif SettingLayer.BT_EFFECT == tag then
local effect = not GlobalUserItem.bSoundAble
GlobalUserItem.setSoundAble(effect)
end
end
function SettingLayer:onTouchBegan(touch, event)
return self:isVisible()
end
function SettingLayer:onTouchEnded(touch, event)
local pos = touch:getLocation()
local m_spBg = self.m_spBg
pos = m_spBg:convertToNodeSpace(pos)
local rec = cc.rect(0, 0, m_spBg:getContentSize().width, m_spBg:getContentSize().height)
if false == cc.rectContainsPoint(rec, pos) then
self:removeFromParent()
end
end
return SettingLayer |
-- local __arg = {...}
local function convert_val(v)
local vtype = type(v)
if vtype == "nil" then
return "nil"
elseif vtype == "string" then
return '"'.. v .. '"'
elseif vtype == "number" or vtype == "boolean" then
return tostring(v)
else
assert(false, "not support value type:"..vtype)
end
end
local function __dump(t, depth)
if type(t) ~= "table" then
return convert_val(t)
end
depth = (depth or 0) + 1
if depth > 10 then
assert(false, "table too depth")
else
local retval = ""
local val
for k, v in pairs(t) do
val = k .. "=" .. __dump(v, depth)
if #retval > 0 then
retval = retval .. "," .. val
else
retval = val
end
end
return "{" .. retval .. "}"
end
end
local function lua_encode(obj)
return __dump(obj, 0)
end
local function lua_decode(str)
local ret = load("return "..str)()
return ret
end
-----------------------------------------------------------
--coders
-----------------------------------------------------------
local coders = {}
function coders.json()
local ok, json = pcall(require, "cjson")
if not ok then
json = require "meiru.3rd.json"
assert(json)
end
local coder = {
encode = json.encode,
decode = json.decode
}
return coder
end
function coders.lua()
local coder = {
encode = lua_encode,
decode = lua_decode
}
return coder
end
function coders.protobuf()
local protobuf = require "protobuf"
return protobuf
end
return function(ctype)
local coder = coders[ctype]()
assert(coder)
return coder
end
|
local libs = (shell.getRunningProgram()):sub(5, -1)
|
if Config.debug then
potentialStops = {}
RegisterCommand('findStops', function(source, args, rawCommand)
for o in ObjectIterator(ObjectFilter.model(BusStop.Models)) do
local hash = sha1.hex(tostring(identifingCoordinate))
local model = GetEntityModel(o)
local coords = GetEntityCoords(o)
local heading = GetEntityHeading(o)
local blip = CreateBlip(513, coords, "Stop Model", 0.5, {r=255,g=0,b=0})
potentialStops[hash] = {
hash = hash,
model = model,
coords = coords,
heading = heading,
blip = blip
}
end
end)
-- Test functionality for the object filter
-- RegisterCommand('objects', function(source, args, rawCommand)
-- for o in ObjectIterator() do print('object', o) end
-- for o in ObjectIterator(ObjectFilter.model(BusStop.Models)) do print('bus stops', o) end
-- for o in ObjectIterator(ObjectFilter.range(GetEntityCoords(PlayerPedId()), 5.0)) do print('within 5m', o) end
--
-- for o in ObjectIterator(
-- ObjectFilter.model(BusStop.Models,
-- ObjectFilter.range(GetEntityCoords(PlayerPedId()), 5.0)
-- )
-- ) do
-- print('within 5m', o)
-- end
-- end)
-- Teleports the user to the next stop
RegisterCommand('nextStop', function(source, args, rawCommand)
if not Job.active then
print('cannot skip, you are not on a route')
TriggerEvent('chat:addMessage', {
template = 'You have to be in an active route',
args = { }
});
return
end
if not Job.Teleport() then
print('cannot skip, failed to teleport')
TriggerEvent('chat:addMessage', {
template = 'You have finished your route, return the bus',
args = { }
});
return
end
print('Teleport success')
TriggerEvent('chat:addMessage', {
template = 'You have been teleported',
args = { }
});
end)
-- Starts a random route
RegisterCommand('busme', function(source, args, rawCommand)
local ped = GetPlayerPed(source)
local entity = ped
local vehicle = GetVehiclePedIsIn(ped, false)
if vehicle then
ESX.Game.DeleteVehicle(vehicle)
end
--Teleport and get your bus
TriggerEvent('chat:addMessage', {
template = 'Fetching a bus...',
args = { }
});
SetPedCoordsKeepVehicle(ped, Config.coordinates.x, Config.coordinates.y, Config.coordinates.z)
Citizen.Wait(1000)
Job.Begin(function(bus)
TriggerEvent('chat:addMessage', {
template = 'Teleporting you to the start...',
args = { }
});
-- Teleport to the stop
if #args >= 1 then
if bus then
Job.Teleport()
end
end
end)
end)
-- Gets the users current coords
RegisterCommand('coords', function(source, args, rawCommand)
local ped = GetPlayerPed(source)
local entity = ped
local vehicle = GetVehiclePedIsIn(ped, false)
local entity = ped
if vehicle ~= 0 then
entity = vehicle
end
local coordinates = GetEntityCoords(entity)
local heading = GetEntityHeading(entity)
print(entity, coordinates, heading)
TriggerEvent('chat:addMessage', {
template = '{0}, {1}, {2} @ {3} deg',
args = { coordinates.x, coordinates.y, coordinates.z, heading }
});
end)
-- Registers a particular bus stop at the players location
RegisterCommand('createStop', function(source, args, rawCommand)
local ped = GetPlayerPed(source)
local vehicle = GetVehiclePedIsIn(ped, false)
local entity = ped
if vehicle ~= 0 then
entity = vehicle
end
-- Prepare the coordinate
local coordinates = GetEntityCoords(entity)
local heading = GetEntityHeading(entity)
-- Prepare the name
local name = ''
if #args == 0 then
local directions = { N = 360, 0, NE = 315, E = 270, SE = 225, S = 180, SW = 135, W = 90, NW = 45 }
local var1, var2 = GetStreetNameAtCoord(coordinates.x, coordinates.y, coordinates.z, Citizen.ResultAsInteger(), Citizen.ResultAsInteger())
local hash1 = GetStreetNameFromHashKey(var1);
local hash2 = GetStreetNameFromHashKey(var2);
local dir = ''
for k, v in pairs(directions) do
if (math.abs(heading - v) < 22.5) then
dir = k;
if (dir == 1) then
dir = 'N';
break;
end
break;
end
end
name = hash1 .. ' ' .. hash2 .. ' ' .. dir
else
name = args[1]
end
-- Prepare the identifying coordinates
local identifyingCoordinates = coordinates
local model = BusStop.FindNearestModel()
if model then
identifyingCoordinates = GetEntityCoords(model)
heading = GetEntityHeading(model) + 90
end
-- Request the stop
BusStop.RequestCreateStop(identifyingCoordinates, coordinates, heading, name, function(hash)
TriggerEvent('chat:addMessage', {
template = 'Bus stop {0} has been created',
args = { hash }
});
end)
end, false)
end |
return require('jwt_ABAC_Authorizer')
|
object_tangible_storyteller_prop_pr_antenna = object_tangible_storyteller_prop_shared_pr_antenna:new {
}
ObjectTemplates:addTemplate(object_tangible_storyteller_prop_pr_antenna, "object/tangible/storyteller/prop/pr_antenna.iff")
|
SkillTree = Object:extend()
function SkillTree:new()
self.timer = Timer()
self.font = fonts.m5x7_16
self.main_canvas = love.graphics.newCanvas(gw, gh)
self.nodes = {}
self.lines = {}
-- Bi-directional links
self.tree = table.copy(tree)
for id, node in ipairs(self.tree) do
for _, linked_node_id in ipairs(node.links or {}) do
table.insert(self.tree[linked_node_id], id)
end
end
for id, node in ipairs(self.tree) do
if node.links then
node.links = fn.unique(node.links)
end
end
-- Create nodes and links
for id, node in ipairs(self.tree) do table.insert(self.nodes, Node(id, node.x, node.y)) end
for id, node in ipairs(self.tree) do
for _, linked_node_id in ipairs(node.links or {}) do
table.insert(self.lines, Line(self.tree, id, linked_node_id))
end
end
bought_node_indexes = {1}
end
function SkillTree:update(dt)
self.timer:update(dt)
camera.smoother = Camera.smooth.damped(5)
if input:down('left_click') then
local mx, my = camera:getMousePosition(sx, sy, 0, 0, sx*gw, sy*gh)
local dx, dy = mx - self.previous_mx, my - self.previous_my
camera:move(-dx, -dy)
end
self.previous_mx, self.previous_my = camera:getMousePosition(sx, sy, 0, 0, sx*gw, sy*gh)
if input:pressed('zoom_in') then self.timer:tween('zoom', 0.2, camera, {scale = camera.scale + 0.4}, 'in-out-cubic') end
if input:pressed('zoom_out') then self.timer:tween('zoom', 0.2, camera, {scale = camera.scale - 0.4}, 'in-out-cubic') end
for _, node in ipairs(self.nodes) do node:update(dt) end
for _, line in ipairs(self.lines) do line:update(dt) end
end
function SkillTree:draw()
love.graphics.setCanvas(self.main_canvas)
love.graphics.clear()
love.graphics.setColor(background_color)
love.graphics.rectangle('fill', 0, 0, gw, gh)
camera:attach(0, 0, gw, gh)
love.graphics.setLineWidth(1/camera.scale)
for _, line in ipairs(self.lines) do line:draw() end
for _, node in ipairs(self.nodes) do node:draw() end
love.graphics.setLineWidth(1)
camera:detach()
-- Stats rectangle
local font = fonts.m5x7_16
love.graphics.setFont(font)
for _, node in ipairs(self.nodes) do
if node.hot then
local stats = self.tree[node.id].stats or {}
-- Figure out max_text_width to be able to set the proper rectangle width
local max_text_width = 0
for i = 1, #stats, 3 do
if font:getWidth(stats[i]) > max_text_width then
max_text_width = font:getWidth(stats[i])
end
end
-- Draw rectangle
local mx, my = love.mouse.getPosition()
mx, my = mx/sx, my/sy
love.graphics.setColor(0, 0, 0, 222)
love.graphics.rectangle('fill', mx, my, 16 + max_text_width, font:getHeight() + (#stats/3)*font:getHeight())
-- Draw text
love.graphics.setColor(default_color)
for i = 1, #stats, 3 do
love.graphics.print(stats[i], math.floor(mx + 8), math.floor(my + font:getHeight()/2 + math.floor(i/3)*font:getHeight()))
end
end
end
love.graphics.setColor(default_color)
love.graphics.setCanvas()
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setBlendMode('alpha', 'premultiplied')
love.graphics.draw(self.main_canvas, 0, 0, 0, sx, sy)
love.graphics.setBlendMode('alpha')
end
function SkillTree:destroy()
end
function SkillTree:canNodeBeBought(id)
for _, linked_node_id in ipairs(self.tree[id]) do
if fn.any(bought_node_indexes, linked_node_id) then return true end
end
end
|
local Draw = require("api.Draw")
local Color = require("mod.extlibs.api.Color")
local UiMouseMenu = require("mod.mouse_ui.api.gui.UiMouseMenu")
local IUiMouseButton = require("mod.mouse_ui.api.gui.IUiMouseButton")
local UiShadowedText = require("api.gui.UiShadowedText")
local UiTheme = require("api.gui.UiTheme")
local UiMouseStyle = require("mod.mouse_ui.api.UiMouseStyle")
local UiMouseMenuButton = class.class("UiMouseMenuButton", IUiMouseButton)
function UiMouseMenuButton:init(opts)
self.text = UiShadowedText:new(opts.text)
self.id = opts.id
self.pressed = false
self.enabled = true
self:set_menu(opts.menu)
self.label_vertices = {}
self.label_vertices_pressed = {}
self.display_direction = opts.display_direction or "horizontal"
end
function UiMouseMenuButton:get_mouse_elements(recursive)
local regions = {}
if self.menu and recursive then
table.append(regions, self.menu:get_mouse_elements(recursive))
end
return regions
end
function UiMouseMenuButton:get_minimum_width()
return self.text:text_width() + 6
end
function UiMouseMenuButton:get_minimum_height()
return self.text:text_height() + 6
end
function UiMouseMenuButton:add_button(button)
if self.menu == nil then
self:set_menu(UiMouseMenu:new {})
end
self.menu:add_button(button)
end
function UiMouseMenuButton:relayout(x, y, width, height)
self.x = x
self.y = y
self.width = math.max(width, self:get_minimum_width())
self.height = math.max(height, self:get_minimum_height())
self.t = UiTheme.load()
self.color = {192, 192, 192}
self.color_dark = {Color:new_rgb(self.color):lighten_by(0.5):to_rgb()}
self.color_light = {Color:new_rgb(self.color):lighten_by(1.5):to_rgb()}
local thickness = 2
self.label_vertices = {
self.x + self.width - 2 - thickness, self.y + self.height - 2 - thickness,
self.x + self.width - 2 - thickness, self.y + self.height - 2 - thickness - 10,
self.x + self.width - 2 - thickness - 10, self.y + self.height - 2 - thickness,
}
self.label_vertices_pressed = fun.iter(self.label_vertices):map(function(i) return i + 2 end):to_list()
if self.menu then
local bx = self.x
local by = self.y
if self.display_direction == "vertical" then
by = self.y + self.height
else
bx = self.x + self.width
end
local button_count = self.menu:iter_mouse_elements():length()
if self.y + self.menu.child_height * button_count > Draw.get_height() then
by = self.y - self.menu.child_height * button_count
end
if self.x + self.menu.child_width > Draw.get_width() then
bx = self.x - self.menu.child_width
end
self.menu:relayout(bx, by, self.width, self.height)
end
end
function UiMouseMenuButton:on_mouse_pressed(x, y, button)
if button == 1 then
self:set_pressed(not self.pressed)
return true
end
return false
end
function UiMouseMenuButton:on_mouse_released(x, y, button)
return true
end
function UiMouseMenuButton:is_mouse_region_enabled()
return self.enabled
end
function UiMouseMenuButton:is_pressed()
return self.pressed
end
function UiMouseMenuButton:is_enabled()
return self.enabled
end
function UiMouseMenuButton:set_pressed(pressed)
self.pressed = pressed
if self.menu then
for _, ui_button in self.menu:iter_mouse_elements() do
ui_button.enabled = self.pressed
end
end
end
function UiMouseMenuButton:set_enabled(enabled)
self.enabled = enabled
end
function UiMouseMenuButton:set_text(text)
self.text:set_data(text)
end
function UiMouseMenuButton:set_menu(menu)
if menu then
assert(class.is_an(UiMouseMenu, menu))
menu._parent = self
for _, ui_button in menu:iter_mouse_elements(false) do
ui_button.enabled = self.pressed
end
end
self.menu = menu
end
function UiMouseMenuButton:draw()
local thickness = 2
UiMouseStyle.draw_panel(self.x, self.y, self.width, self.height, thickness, self.pressed, self.color, self.color_dark, self.color_light)
Draw.set_color(self.color_dark)
if self.pressed then
Draw.filled_polygon(self.label_vertices_pressed)
else
Draw.filled_polygon(self.label_vertices)
end
local w = self.text:text_width()
local h = self.text:text_height()
local x = self.x + (self.width / 2) - (w / 2)
local y = self.y + (self.height / 2) - (h / 2)
if self.pressed then
x = x + 2
y = y + 2
end
self.text:relayout(x, y)
self.text:draw()
if self.menu and self.pressed then
self.menu:draw()
end
end
function UiMouseMenuButton:update(dt)
if self.pressed and self.menu then
self.menu:update(dt)
end
end
return UiMouseMenuButton
|
#! /usr/bin/lua
require( "common" )
require( "lfs" )
require( "imlib2" )
local Dir = "icons"
local OutputDir = "../img/icons"
local IgnoredFiles =
{
"^%.%.$",
"^%.$",
}
local RareDirs =
{
"equipment",
}
local NamedDirs =
{
"items",
}
local NoSuffixDirs =
{
"equipment",
}
-- these are done by eye. I don't really care
-- -- if they're off because they still look ok
local RareColors =
{
"ffffff",
"875fff",
"fafc4f",
"ea8bd5",
"5dd030",
"3581e1",
"e84458",
}
local NamedColors =
{
white = "ffffff",
gray = "aaaaaf",
green = "6bf36e",
lime = "a8d468",
moss = "67a838",
teal = "58e8c0",
yellow = "f7f56b",
orange = "f49e62",
brown = "c09428",
red = "e84458",
pink = "f599f0",
purple = "aa70e0",
blue = "718fff",
cyan = "a6fcfd",
}
function ignored( file )
for _, pattern in ipairs( IgnoredFiles ) do
if file:find( pattern ) then
return true
end
end
return false
end
function recolor( img, htmlColor )
local w, h = img:get_width(), img:get_height()
local redScale = tonumber( htmlColor:sub( 1, 2 ), 16 ) / 255
local greenScale = tonumber( htmlColor:sub( 3, 4 ), 16 ) / 255
local blueScale = tonumber( htmlColor:sub( 5, 6 ), 16 ) / 255
for x = 0, w - 1 do
for y = 0, h - 1 do
local color = img:get_pixel( x, y )
if color.alpha ~= 0 then
img:draw_pixel( x, y,
imlib2.color.new(
color.red * redScale,
color.green * greenScale,
color.blue * blueScale,
color.alpha
)
)
end
end
end
end
local function copy( src, dst )
local contents = readFile( src )
local outFile = io.open( dst, "w" )
outFile:write( contents )
outFile:close()
end
for _, rareDir in ipairs( RareDirs ) do
local dir = ( "%s/%s" ):format( Dir, rareDir )
lfs.mkdir( OutputDir .. "/" .. rareDir )
for file in lfs.dir( dir ) do
if not ignored( file ) then
for rarity, color in ipairs( RareColors ) do
local img = imlib2.image.load( dir .. "/" .. file )
recolor( img, color )
img:save( OutputDir .. "/" .. rareDir .. "/" .. file:gsub( "(%l+)%.png", "%1_rare" .. rarity .. ".png" ) )
img:free()
end
end
end
end
for _, nameDir in ipairs( NamedDirs ) do
local dir = ( "%s/%s" ):format( Dir, nameDir )
lfs.mkdir( OutputDir .. "/" .. nameDir )
for file in lfs.dir( dir ) do
if not ignored( file ) then
for name, color in pairs( NamedColors ) do
local img = imlib2.image.load( dir .. "/" .. file )
recolor( img, color )
img:save( OutputDir .. "/" .. nameDir .. "/" .. file:gsub( "(%l+)%.png", "%1_" .. name .. ".png" ) )
img:free()
end
end
end
end
for _, noSuffixDir in ipairs( NoSuffixDirs ) do
local dir = ( "%s/%s" ):format( Dir, noSuffixDir )
lfs.mkdir( OutputDir .. "/" .. noSuffixDir )
for file in lfs.dir( dir ) do
if not ignored( file ) then
copy( dir .. "/" .. file, OutputDir .. "/" .. noSuffixDir .. "/" .. file )
end
end
end
print( "genIcons: ok!" )
|
if arg[#arg] == "vsc_debug" then
require("lldebugger").start()
end
require 'Engine.Engine'
require 'Love2d.LoveGraphics'
require 'Love2d.LoveAudio'
require 'Love2d.LoveInput'
UpdateFunction = nil
function love.load()
LoveGraphics.SetupWindow()
Engine.Start()
UpdateFunction = Engine.EngineUpdate
end
function love.update(dt)
if UpdateFunction and _G.type(UpdateFunction) == 'function' then
UpdateFunction(dt)
end
end
function love.draw()
Engine.GraphicsUpdate()
end
function love.keypressed(key)
LoveInput.KeyPressed(key)
end
|
local path = "src/weapons/"
local gun = require(path .. "gun")
return {
gun = gun
}
|
function init()
robot.wheels.set_velocity(5,5)
end
function step()
end
function reset()
end
function destroy()
end
|
--[[
TheNexusAvenger
Unit tests for the TextButtonFactory class.
--]]
local NexusUnitTesting = require("NexusUnitTesting")
local NexusButton = game:GetService("ReplicatedStorage"):WaitForChild("NexusButton")
local Factory = NexusButton:WaitForChild("Factory")
local TextButtonFactory = require(Factory:WaitForChild("TextButtonFactory"))
local TextButtonFactoryTest = NexusUnitTesting.UnitTest:Extend()
--[[
Test that the constructor works without failing.
--]]
NexusUnitTesting:RegisterUnitTest(TextButtonFactoryTest.new("Constructor"):SetRun(function(self)
--Create the component under testing.
local CuT = TextButtonFactory.new()
--Run the assertions.
self:AssertEquals(CuT.ClassName,"TextButtonFactory","ClassName is incorrect.")
end))
--[[
Test that the CreateDefault method.
--]]
NexusUnitTesting:RegisterUnitTest(TextButtonFactoryTest.new("CreateDefault"):SetRun(function(self)
--Create the component under testing.
local CuT = TextButtonFactory.CreateDefault(Color3.new(0,170/255,1))
--Create a button and assert the defaults are correct.
local Button,TextLabel = CuT:Create()
self:AssertEquals(Button.BackgroundColor3,Color3.new(0,170/255,1),"Background color is incorrect.")
self:AssertEquals(Button.BorderColor3,Color3.new(0,140/255,225/255),"Border color is incorrect.")
self:AssertEquals(Button.BorderTransparency,0.25,"Border transparency is incorrect.")
self:AssertEquals(TextLabel.Font,Enum.Font.SciFi,"Font is incorrect.")
self:AssertEquals(TextLabel.TextColor3,Color3.new(1,1,1),"TextColor3 is incorrect.")
self:AssertEquals(TextLabel.TextStrokeColor3,Color3.new(0,0,0),"TextStrokeColor3 is incorrect.")
self:AssertEquals(TextLabel.TextStrokeTransparency,0,"TextStrokeTransparency is incorrect.")
self:AssertEquals(TextLabel.TextScaled,true,"TextScaled is incorrect.")
--Destroy the button.
Button:Destroy()
end))
--[[
Test that the SetTextDefault and SetTextDefault methods.
--]]
NexusUnitTesting:RegisterUnitTest(TextButtonFactoryTest.new("SetDefault"):SetRun(function(self)
--Create the component under testing.
local CuT = TextButtonFactory.new()
--Set several defaults.
CuT:SetTextDefault("Text","TestLabel")
CuT:SetTextDefault("Font",Enum.Font.Arcade)
--Create a button and assert the defaults are correct.
local Button1,TextLabel1 = CuT:Create()
self:AssertEquals(TextLabel1.Text,"TestLabel","Text is incorrect.")
self:AssertEquals(TextLabel1.Font,Enum.Font.Arcade,"Font is incorrect.")
--Unset a default.
CuT:UnsetTextDefault("Text")
--Create a button and assert the defaults are correct.
local Button2,TextLabel2 = CuT:Create()
self:AssertNotEquals(TextLabel2.Text,"TestLabel","Text is incorrect.")
self:AssertEquals(TextLabel2.Font,Enum.Font.Arcade,"Font is incorrect.")
--Destroy the buttons.
Button1:Destroy()
Button2:Destroy()
end))
return true |
---------------------------------------------------------------------------------------------------
---menu_manager.lua
---author: Karl
---date: 2021.3.4
---desc: MenuManager manages all menu pages in a menu scene. The class attempts to implement a menu
--- that has the following features:
---
--- 1. Each menu page is an object that can be displayed, interacted, and can send messages to
--- the previous menu pages in the menu array.
--- 2. The menu page array is an array which records all menu pages that lead up to the current
--- menu page, therefore the game knows which one to go back to when the user exits the current
--- menu page.
--- 3. When an array is exited, it continues to exist in the menu page pool but will be removed
--- from the menu page array. Only the most recent one or more menu pages in the menu page
--- array and the exiting menu pages are updated and displayed on the screen.
--- 4. When the user returns to or advances to a new menu page, the old menu page object will
--- be pulled out from menu page pool if possible (that is, if it still exists), otherwise a
--- new menu page object will be created using the same callback function.
--- 5. The menu manager is able to maintain a global menu page transition speed multiplier
--- factor for this menu, so the transition speed can be easily changed here.
---------------------------------------------------------------------------------------------------
---@class MenuManager
local M = LuaClass("menu.MenuManager")
-- require modules
require("BHElib.ui.menu.menu_page")
local MenuPageArray = require("BHElib.ui.menu.menu_page_array")
local MenuPagePool = require("BHElib.ui.menu.menu_page_pool")
local MenuConst = require("BHElib.ui.menu.menu_global")
---------------------------------------------------------------------------------------------------
---virtual functions
---this function needs to initialize menu pages for menu_page_array and menu_page_pool
M.initMenuPages = nil
---this function needs to terminate the menu; call scene transition if needed
M.onMenuExit = nil
---------------------------------------------------------------------------------------------------
---init
---create and return a new Menu instance
---@param transition_speed number a transition speed coefficient
---@return MenuManager
function M.__create(transition_speed)
local self = {}
self.transition_speed = transition_speed or 1 / 15
-- an array to track the sequence of menus leading to the current one
self.menu_page_array = MenuPageArray()
-- a pool to track all existing menus, whether they are entering or exiting (in the latter case they may not be in the array)
self.menu_page_pool = MenuPagePool()
return self
end
function M:ctor()
self:initMenuPages()
end
---------------------------------------------------------------------------------------------------
---add a menu page to the menu page array and menu page pool
function M:registerPage(init_callback, menu_page_id, menu_page, menu_pos)
self.menu_page_array:setMenu(menu_pos, init_callback, menu_page_id)
self.menu_page_pool:setMenuInPool(menu_page_id, menu_page, menu_pos)
end
function M:queryChoice(choice_key)
return self.menu_page_array:queryChoice(choice_key)
end
---@param menu_page_pos number the index from which the cascading starts
function M:cascade(menu_page_pos)
assert(menu_page_pos, "Error: Attempt to cascade menu page at a nil index!")
while menu_page_pos ~= nil do
local menu_page_init_callback, menu_page_id
menu_page_init_callback, menu_page_id, menu_page_pos = self.menu_page_array:findPrevMenuOf(menu_page_pos, "go_to_menus", "num_finished_menus")
if menu_page_pos then
local menu_page = self.menu_page_pool:getMenuFromPool(menu_page_id)
menu_page:onCascade(self.menu_page_array)
end
end
end
---setup a menu page at the given position; can be used to append new menu page to the end of array
---will update the menu page in the page array and page pool;
---it should be guaranteed that the new menu has no choices recorded in the array
---@param menu_page_init_callback function a function that creates a new menu page
---@param menu_id string a unique id that identifies the menu page
---@param menu_pos number position in the array to setup menu page at
---@return MenuPage a menu page that has been setup in the given index of the array
function M:setupMenuPageAtPos(menu_page_init_callback, menu_id, menu_pos)
-- check if menu already exist, if not, create a new one
local menu_page_pool = self.menu_page_pool
local queried_menu_pos = menu_page_pool:getMenuPosFromPool(menu_id)
local menu_page
local create_flag = (queried_menu_pos == nil and not menu_page_pool:isMenuExists(menu_id))
if create_flag then
menu_page = self:createMenuPage(menu_page_init_callback, menu_id)
-- add/set the menu page in the array
self:registerPage(menu_page_init_callback, menu_id, menu_page, menu_pos)
else
menu_page = menu_page_pool:getMenuFromPool(menu_id)
self:registerPage(menu_page_init_callback, menu_id, menu_page, menu_pos)
self.menu_page_array:clearChoices(menu_pos)
end
return menu_page
end
---@param menu_page_init_callback function a function that takes first parameter as menu manager, creates a new menu page
function M:createMenuPage(menu_page_init_callback)
return menu_page_init_callback(self)
end
---set the top menu page to enter, in forward mode
function M:setTopMenuPageToEnter()
local menu_page_array = self.menu_page_array
local menu_id = menu_page_array:getMenuId(menu_page_array:getSize())
local cur_menu_page = self.menu_page_pool:getMenuFromPool(menu_id)
cur_menu_page:setPageEnter(true, self.transition_speed)
end
---setup menu pages
---@param menu_page_info_array ta`ble an array in which each element contains information for initializing each menu page
---@param coordinates_name string name of the render view to render in E.g. "ui" "game" "3d"
---@param init_layer number (if non-nil) set the initial layer of the menu pages to this value
function M:setupMenuPagesFromInfoArray(menu_page_info_array, coordinates_name, init_layer)
for i = 1, #menu_page_info_array do
local class_id, menu_id = unpack(menu_page_info_array[i])
local menu_page = self:setupMenuPageAtPos(class_id, menu_id, i)
if init_layer then
menu_page:setLayer(init_layer)
end
menu_page:setRenderView(coordinates_name)
end
end
---------------------------------------------------------------------------------------------------
---update
---@param dt number elapsed time
function M:update(dt)
-- update all existing menu pages
local menu_page_pool = self.menu_page_pool
local menu_page_array = self.menu_page_array
local to_be_deleted = {}
for menu_page_id, info_array in menu_page_pool:getIter() do
local menu_page_pos = info_array[1]
local menu_page = info_array[2]
if not menu_page:continueMenuPage() then
-- flag for deletion
-- only delete if the menu page is not in the array, in which case it needs to exist to respond to cascade()
if menu_page_array:getSize() < menu_page_pos or menu_page_array:getMenuId(menu_page_pos) ~= menu_page_id then
to_be_deleted[menu_page_id] = menu_page_pos
end
else
if menu_page:isInputEnabled() then
menu_page:processInput()
end
local choices = menu_page:getChoice()
if choices ~= nil then
self:handleChoices(choices, menu_page_pos, menu_page)
end
end
end
-- update after creating new menu pages to ensure update() is called at least once in the first time of render
for menu_page_id, info_array in menu_page_pool:getIter() do
local menu_page = info_array[2]
menu_page:update(1)
end
for menu_page_id, menu_page_pos in pairs(to_be_deleted) do
local menu_page = menu_page_pool:getMenuFromPool(menu_page_id)
menu_page:cleanup()
menu_page_pool:delMenuInPool(menu_page_id)
end
end
---handle choices raised by a menu page in the menu array at the given index
---@param menu_page_pos number the index of the menu page that raised the choices
---@param menu_page MenuPage
function M:handleChoices(choices, menu_page_pos, menu_page)
local menu_page_array = self.menu_page_array
local exit_indicator = 0
local next_pos = -1
local cascade_flag = false
for i = 1, #choices do
local choice = choices[i]
local label = choice[1] -- see menu_global.lua
if label == MenuConst.CHOICE_SPECIFY then
menu_page_array:setChoice(menu_page_pos, choice[2], choice[3])
elseif label == MenuConst.CHOICE_CASCADE then
cascade_flag = true
elseif label == MenuConst.CHOICE_EXECUTE then
local callback = choice[2]
callback(self, menu_page)
else
-- menu page switch
if label == MenuConst.CHOICE_GO_BACK then
exit_indicator = 1
next_pos = menu_page_pos - 1
if next_pos <= 0 then
-- no menu page to go back to, exit the menu
label = MenuConst.CHOICE_EXIT
end
end
if label == MenuConst.CHOICE_EXIT or label == MenuConst.CHOICE_GO_TO_MENUS then
local menus = {} -- for CHOICE_EXIT
if label == MenuConst.CHOICE_GO_TO_MENUS then
menus = choice[2]
end
menu_page_array:setChoice(menu_page_pos, "go_to_menus", menus)
menu_page_array:setChoice(menu_page_pos, "num_finished_menus", 0)
exit_indicator = 2
end
end
end
if cascade_flag then
self:cascade(menu_page_array:getSize()) -- cascade from the current menu page
end
if exit_indicator == 1 then
self:goBackToMenuPage(next_pos)
elseif exit_indicator == 2 then
self:goToNextMenuPage()
else
local top_page = self.menu_page_pool:getMenuFromPool(menu_page_array:getMenuId(menu_page_pos))
top_page:resetSelection(true)
end
end
---exit current menu page and go back to one of the previous menu pages
---@param next_pos number the index of the menu page to go back to in the array
function M:goBackToMenuPage(next_pos)
local menu_page_array = self.menu_page_array
local menu_page_pool = self.menu_page_pool
local cur_pos = menu_page_array:getSize()
local cur_id = menu_page_array:getMenuId(cur_pos)
local cur_page = menu_page_pool:getMenuFromPool(cur_id)
local init_callback, next_id = menu_page_array:getMenuInitCallback(next_pos), menu_page_array:getMenuId(next_pos)
menu_page_array:retrievePrevMenu("go_to_menus", "num_finished_menus") ---TODO: these parameters should be constants
assert(cur_pos == menu_page_array:getSize(), "Error: Size mismatch!")
menu_page_array:popMenu()
cur_page:setPageExit(false, self.transition_speed)
local next_page = self:setupMenuPageAtPos(init_callback, next_id, next_pos)
next_page:setPageEnter(false, self.transition_speed)
end
function M:goToNextMenuPage()
local menu_page_array = self.menu_page_array
local menu_page_pool = self.menu_page_pool
local cur_pos = menu_page_array:getSize()
local cur_id = menu_page_array:getMenuId(cur_pos)
local cur_page = menu_page_pool:getMenuFromPool(cur_id)
cur_page:setPageExit(true, self.transition_speed)
local menu_page_init_callback, next_id, next_pos = menu_page_array:retrieveNextMenu("go_to_menus", "num_finished_menus")
if menu_page_init_callback ~= nil then
local next_page = self:setupMenuPageAtPos(menu_page_init_callback, next_id, next_pos)
next_page:setPageEnter(true, self.transition_speed)
else
-- next menu not found; exit the menu scene
self:onMenuExit()
end
end
---------------------------------------------------------------------------------------------------
---exiting
function M:setAllPageExit()
-- set all menu pages to exit state
local menu_page_pool = self.menu_page_pool
for _, info_array in menu_page_pool:getIter() do
local menu_page = info_array[2]
menu_page:setPageExit(true, self.transition_speed)
end
end
function M:cleanup()
local menu_page_pool = self.menu_page_pool
for _, info_array in menu_page_pool:getIter() do
local menu_page = info_array[2]
menu_page:cleanup()
end
end
return M |
-- Sine wave.
local SoundUnit = require((...):gsub('[^.]*$', '') .. 'soundunit')
local function process (t, v)
return math.sin(v * math.pi)
end
return function (t)
t = SoundUnit(t)
t.process = process
return t
end
|
--- Watch paths recursively for changes
--- @class PathwatcherInstance
local PathwatcherInstance
--- starts a path watcher
---
--- @return PathwatcherInstance
function PathwatcherInstance:start()end
--- stops a path watcher
---
function PathwatcherInstance:stop()end
|
-- Tests for complicated + argument to :edit command
local helpers = require('test.functional.helpers')(after_each)
local clear, insert = helpers.clear, helpers.insert
local command, expect = helpers.command, helpers.expect
local wait = helpers.wait
describe(':edit', function()
setup(clear)
it('is working', function()
insert([[
The result should be in Xfile1: "fooPIPEbar", in Xfile2: "fooSLASHbar"
foo|bar
foo/bar]])
wait()
-- Prepare some test files
command('$-1w! Xfile1')
command('$w! Xfile2')
command('w! Xfile0')
-- Open Xfile using '+' range
command('edit +1 Xfile1')
command('s/|/PIPE/')
command('yank A')
command('w! Xfile1')
-- Open Xfile2 using '|' range
command('edit Xfile2|1')
command("s/\\//SLASH/")
command('yank A')
command('w! Xfile2')
-- Clean first buffer and put @a
command('bf')
command('%d')
command('0put a')
-- Remove empty line
command('$d')
-- The buffer should now contain
expect([[
fooPIPEbar
fooSLASHbar]])
end)
teardown(function()
os.remove('Xfile0')
os.remove('Xfile1')
os.remove('Xfile2')
end)
end)
|
---------------------------------------------------------------------------------------------------
-- func: addallmounts
-- desc: Adds all mount key items to player, granting access to their associated mounts
---------------------------------------------------------------------------------------------------
require("scripts/globals/status")
require("scripts/globals/keyitems")
cmdprops =
{
permission = 1,
parameters = "s"
}
function error(player, msg)
player:PrintToPlayer(msg)
player:PrintToPlayer("!addallmounts {player}")
end
function onTrigger(player, target)
-- validate target
local targ
if (target == nil) then
targ = player
else
targ = GetPlayerByName(target)
if (targ == nil) then
error(player, string.format("Player named '%s' not found!", target))
return
end
end
-- add all mount key items
for i = tpz.ki.CHOCOBO_COMPANION, tpz.ki.CHOCOBO_COMPANION + 26 do
targ:addKeyItem(i)
end
player:PrintToPlayer(string.format("%s now has all mounts.", targ:getName()))
end
|
return {'xie'} |
--- @module navbar.generic
local gen = {}
-------------------------------------------------------------------------------
-- Helper Functions
-------------------------------------------------------------------------------
--- Escape all punctuations contained in string.
-- @treturn string The escaped string
function string:escape_punctuation()
return self:gsub("%p", "%%%1")
end
--- Replace a string by another one (escape the punctuation).
-- @treturn string The escaped string
function string:replace_all(from, into)
return self:gsub(from:escape_punctuation(), into)
end
--- Trim space at the begining and end of the string.
-- @treturn string The new string.
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
--- Return true if string starts with start.
-- @tparam string start The string we are looking for.
-- @treturn bool true if the string starts with start.
function string:starts_with(start)
return self:sub(1, #start) == start
end
--- Return true if string ends with ending.
-- @tparam string ending The string we are looking for.
-- @treturn bool true if the string ends with ending.
function string:ends_with(ending)
return ending == "" or self:sub(-#ending) == ending
end
--- Return true if string contains str.
-- Notes: we will escape all punctuations contained in str first.
-- @tparam string str The string we are looking for.
-- @treturn bool true if the string contains str.
function string:contains(str)
local pat = str:escape_punctuation()
if string.find(self, pat) == nil then
return false
end
return true
end
--- Split function with a python semantic.
-- see http://lua-users.org/wiki/SplitJoin
-- @tparam string sep The character to use for the slit.
-- @tparam int max The maximun number of split.
-- @tparam string regex The regex to use for the split instead of sSeparator.
-- @return A table of string.
function string:split(sep, max, regex)
assert(sep ~= '')
assert(max == nil or max >= 1)
local record = {}
if self:len() > 0 then
local plain = not regex
max = max or -1
local field, start = 1, 1
local first, last = self:find(sep, start, plain)
while first and max ~= 0 do
record[field] = self:sub(start, first-1)
field = field + 1
start = last + 1
first, last = self:find(sep, start, plain)
max = max-1
end
record[field] = self:sub(start)
end
return record
end
--- Return a list with the keys from the table.
-- @tparam table atable The table to use as source.
-- @treturn table A list of the keys from the table.
function gen.keys(atable)
local keys = {}
for key, _ in pairs(atable) do
keys[#keys+1] = key
end
return keys
end
--- Create a set from a list (table)
-- @tparam table list The table to use as source.
-- @treturn table A set (using the elements from list as keys)
function gen.set(list)
local set = {}
for _, l in ipairs(list) do
set[l] = true
end
return set
end
--- Display a set as a string.
-- @tparam table set The set to display.
-- @treturn string A string containing all elements from the set.
function gen.set_tostring(set)
local tab = {}
for k, _ in pairs(set) do
tab[#tab+1] = k
end
return table.concat(tab, ', ')
end
--- Copy (deep copy) a table.
-- Note: works for all lua5 versions.
-- @tparam table list The list to copy.
-- @treturn table A copy of the original table.
function gen.table_deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[gen.table_deepcopy(orig_key)] = gen.table_deepcopy(orig_value)
end
setmetatable(copy, gen.table_deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
--- Clone/Copy a list (table)
-- Note: only works for lua5.2 and above
-- @tparam table list The list to clone.
function gen.table_clone(list)
return { table.unpack(list) }
end
--- Reverse a list (table).
-- Note: modify in place.
-- @tparam table list The list to reverse.
function gen.table_reverse(list)
local i, j = 1, #list
while i < j do
list[i], list[j] = list[j], list[i]
i = i + 1
j = j - 1
end
end
--- Return true if list == {}, false otherwise.
-- @tparam table list A table.
-- @return true if the table is {}, false otherwise.
function gen.is_empty(list)
return next(list) == nil
end
--- Return true if val is present in list, false otherwise
-- @param val A value.
-- @tparam table list A list.
-- @treturn bool true if val is present in list.
function gen.is_in(val, list)
for _, value in ipairs(list) do
if value == val then
return true
end
end
return false
end
--- Lua implementation of PHP scandir for posix systems (we only want the list of file).
function gen.scandir_posix(directory)
directory = directory or '.'
local t, popen = {}, io.popen
local pfile = popen('ls -A "'..directory..'"')
for filename in pfile:lines() do
t[#t+1] = filename
end
pfile:close()
return t
end
--- Lua implementation of PHP scandir for windows systems.
function gen.scandir_windows(directory)
local t, popen = {}, io.popen
local pfile = popen('dir "'..directory..'" /b')
for filename in pfile:lines() do
t[#t+1] = filename
end
pfile:close()
return t
end
--- Return a Class object
--
-- @usage local Rectangle = gen.Class()
-- function Rectangle:__init(l, h) self.l = l or 0; self.h = h or 0 end
-- function Rectangle:surface() return self.l * self.h end
-- local Square = gen.Class(Rectangle)
-- function Square.__init(l) Rectangle.__init(self, l, l)
--
-- @param ... The list of classes this class inherit from (can be empty).
-- @return Class object.
function gen.class(...)
-- "cls" is the new class
local cls, bases = {}, {...}
-- copy base class contents into the new class
for i, base in ipairs(bases) do
-- print(i, base)
for k, v in pairs(base) do
-- print(k, v)
cls[k] = v
end
end
-- set the class's __index, and start filling an "is_a" table that contains this class and all of its bases
-- so you can do an "instance of" check using my_instance.is_a[MyClass]
cls.__index, cls.is_a = cls, {[cls] = true}
for i, base in ipairs(bases) do
for c in pairs(base.is_a) do
cls.is_a[c] = true
end
cls.is_a[base] = true
end
-- the class's __call metamethod
setmetatable(cls, {__call = function (c, ...)
local instance = setmetatable({}, c)
-- run the init method if it's there
local init = instance.__init
if init then init(instance, ...) end
return instance
end})
-- return the new class table, that's ready to fill with methods
return cls
end
-------------------------------------------------------------------------------
-- Module
-------------------------------------------------------------------------------
return gen
|
#!/usr/bin/env lua
---------
-- LuaSrcDiet
--
-- Compresses Lua source code by removing unnecessary characters.
-- For Lua 5.1+ source code.
--
-- **Notes:**
--
-- * Remember to update version and date information below (MSG_TITLE).
-- * TODO: passing data tables around is a horrific mess.
-- * TODO: to implement pcall() to properly handle lexer etc. errors.
-- * TODO: need some automatic testing for a semblance of sanity.
-- * TODO: the plugin module is highly experimental and unstable.
----
package.path = package.path .. ";../Lua/Minifier/?.lua"
local fs = require "fs"
local llex = require "llex"
local lparser = require "lparser"
local luasrcdiet = require "init"
local optlex = require "optlex"
local optparser = require "optparser"
local byte = string.byte
local concat = table.concat
local find = string.find
local fmt = string.format
local gmatch = string.gmatch
local match = string.match
local print = print
local rep = string.rep
local sub = string.sub
local plugin
local LUA_VERSION = match(_VERSION, " (5%.[123])$") or "5.1"
-- Is --opt-binequiv available for this Lua version?
local BIN_EQUIV_AVAIL = LUA_VERSION == "5.1" and not package.loaded.jit
---------------------- Messages and textual data ----------------------
local MSG_TITLE = fmt([[
LuaSrcDiet: Puts your Lua 5.1+ source code on a diet
Version %s <%s>
]], luasrcdiet._VERSION, luasrcdiet._HOMEPAGE)
local MSG_USAGE = [[
usage: luasrcdiet [options] [filenames]
example:
>luasrcdiet myscript.lua -o myscript_.lua
options:
-v, --version prints version information
-h, --help prints usage information
-o <file> specify file name to write output
-s <suffix> suffix for output files (default '_')
--keep <msg> keep block comment with <msg> inside
--plugin <module> run <module> in plugin/ directory
- stop handling arguments
(optimization levels)
--none all optimizations off (normalizes EOLs only)
--basic lexer-based optimizations only
--maximum maximize reduction of source
(informational)
--quiet process files quietly
--read-only read file and print token stats only
--dump-lexer dump raw tokens from lexer to stdout
--dump-parser dump variable tracking tables from parser
--details extra info (strings, numbers, locals)
features (to disable, insert 'no' prefix like --noopt-comments):
%s
default settings:
%s]]
-- Optimization options, for ease of switching on and off.
--
-- * Positive to enable optimization, negative (no) to disable.
-- * These options should follow --opt-* and --noopt-* style for now.
local OPTION = [[
--opt-comments,'remove comments and block comments'
--opt-whitespace,'remove whitespace excluding EOLs'
--opt-emptylines,'remove empty lines'
--opt-eols,'all above, plus remove unnecessary EOLs'
--opt-strings,'optimize strings and long strings'
--opt-numbers,'optimize numbers'
--opt-locals,'optimize local variable names'
--opt-entropy,'tries to reduce symbol entropy of locals'
--opt-srcequiv,'insist on source (lexer stream) equivalence'
--opt-binequiv,'insist on binary chunk equivalence (only for PUC Lua 5.1)'
--opt-experimental,'apply experimental optimizations'
]]
-- Preset configuration.
local DEFAULT_CONFIG = [[
--opt-comments --opt-whitespace --opt-emptylines
--opt-numbers --opt-locals
--opt-srcequiv --noopt-binequiv
]]
-- Override configurations: MUST explicitly enable/disable everything.
local BASIC_CONFIG = [[
--opt-comments --opt-whitespace --opt-emptylines
--noopt-eols --noopt-strings --noopt-numbers
--noopt-locals --noopt-entropy
--opt-srcequiv --noopt-binequiv
]]
local MAXIMUM_CONFIG = [[
--opt-comments --opt-whitespace --opt-emptylines
--opt-eols --opt-strings --opt-numbers
--opt-locals --opt-entropy
--opt-srcequiv
]] .. (BIN_EQUIV_AVAIL and ' --opt-binequiv' or ' --noopt-binequiv')
local NONE_CONFIG = [[
--noopt-comments --noopt-whitespace --noopt-emptylines
--noopt-eols --noopt-strings --noopt-numbers
--noopt-locals --noopt-entropy
--opt-srcequiv --noopt-binequiv
]]
local DEFAULT_SUFFIX = "_" -- default suffix for file renaming
local PLUGIN_SUFFIX = "luasrcdiet.plugin." -- relative location of plugins
------------- Startup and initialize option list handling -------------
--- Simple error message handler; change to error if traceback wanted.
--
-- @tparam string msg The message to print.
local function die(msg)
print("LuaSrcDiet (error): "..msg); os.exit(1)
end
--die = error--DEBUG
-- Prepare text for list of optimizations, prepare lookup table.
local MSG_OPTIONS = ""
do
local WIDTH = 24
local o = {}
for op, desc in gmatch(OPTION, "%s*([^,]+),'([^']+)'") do
local msg = " "..op
msg = msg..rep(" ", WIDTH - #msg)..desc.."\n"
MSG_OPTIONS = MSG_OPTIONS..msg
o[op] = true
o["--no"..sub(op, 3)] = true
end
OPTION = o -- replace OPTION with lookup table
end
MSG_USAGE = fmt(MSG_USAGE, MSG_OPTIONS, DEFAULT_CONFIG)
--------- Global variable initialization, option set handling ---------
local suffix = DEFAULT_SUFFIX -- file suffix
local option = {} -- program options
local stat_c, stat_l -- statistics tables
--- Sets option lookup table based on a text list of options.
--
-- Note: additional forced settings for --opt-eols is done in optlex.lua.
--
-- @tparam string CONFIG
local function set_options(CONFIG)
for op in gmatch(CONFIG, "(%-%-%S+)") do
if sub(op, 3, 4) == "no" and -- handle negative options
OPTION["--"..sub(op, 5)] then
option[sub(op, 5)] = false
else
option[sub(op, 3)] = true
end
end
end
-------------------------- Support functions --------------------------
-- List of token types, parser-significant types are up to TTYPE_GRAMMAR
-- while the rest are not used by parsers; arranged for stats display.
local TTYPES = {
"TK_KEYWORD", "TK_NAME", "TK_NUMBER", -- grammar
"TK_STRING", "TK_LSTRING", "TK_OP",
"TK_EOS",
"TK_COMMENT", "TK_LCOMMENT", -- non-grammar
"TK_EOL", "TK_SPACE",
}
local TTYPE_GRAMMAR = 7
local EOLTYPES = { -- EOL names for token dump
["\n"] = "LF", ["\r"] = "CR",
["\n\r"] = "LFCR", ["\r\n"] = "CRLF",
}
--- Reads source code from the file.
--
-- @tparam string fname Path of the file to read.
-- @treturn string Content of the file.
local function load_file(fname)
local data, err = fs.read_file(fname, "rb")
if not data then die(err) end
return data
end
--- Saves source code to the file.
--
-- @tparam string fname Path of the destination file.
-- @tparam string dat The data to write into the file.
local function save_file(fname, dat)
local ok, err = fs.write_file(fname, dat, "wb")
if not ok then die(err) end
end
------------------ Functions to deal with statistics ------------------
--- Initializes the statistics table.
local function stat_init()
stat_c, stat_l = {}, {}
for i = 1, #TTYPES do
local ttype = TTYPES[i]
stat_c[ttype], stat_l[ttype] = 0, 0
end
end
--- Adds a token to the statistics table.
--
-- @tparam string tok The token.
-- @param seminfo
local function stat_add(tok, seminfo)
stat_c[tok] = stat_c[tok] + 1
stat_l[tok] = stat_l[tok] + #seminfo
end
--- Computes totals for the statistics table, returns average table.
--
-- @treturn table
local function stat_calc()
local function avg(c, l) -- safe average function
if c == 0 then return 0 end
return l / c
end
local stat_a = {}
local c, l = 0, 0
for i = 1, TTYPE_GRAMMAR do -- total grammar tokens
local ttype = TTYPES[i]
c = c + stat_c[ttype]; l = l + stat_l[ttype]
end
stat_c.TOTAL_TOK, stat_l.TOTAL_TOK = c, l
stat_a.TOTAL_TOK = avg(c, l)
c, l = 0, 0
for i = 1, #TTYPES do -- total all tokens
local ttype = TTYPES[i]
c = c + stat_c[ttype]; l = l + stat_l[ttype]
stat_a[ttype] = avg(stat_c[ttype], stat_l[ttype])
end
stat_c.TOTAL_ALL, stat_l.TOTAL_ALL = c, l
stat_a.TOTAL_ALL = avg(c, l)
return stat_a
end
----------------------------- Main tasks -----------------------------
--- A simple token dumper, minimal translation of seminfo data.
--
-- @tparam string srcfl Path of the source file.
local function dump_tokens(srcfl)
-- Load file and process source input into tokens.
local z = load_file(srcfl)
local toklist, seminfolist = llex.lex(z)
-- Display output.
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
if tok == "TK_OP" and byte(seminfo) < 32 then
seminfo = "("..byte(seminfo)..")"
elseif tok == "TK_EOL" then
seminfo = EOLTYPES[seminfo]
else
seminfo = "'"..seminfo.."'"
end
print(tok.." "..seminfo)
end--for
end
--- Dumps globalinfo and localinfo tables.
--
-- @tparam string srcfl Path of the source file.
local function dump_parser(srcfl)
-- Load file and process source input into tokens,
local z = load_file(srcfl)
local toklist, seminfolist, toklnlist = llex.lex(z)
-- Do parser optimization here.
local xinfo = lparser.parse(toklist, seminfolist, toklnlist)
local globalinfo, localinfo = xinfo.globalinfo, xinfo.localinfo
-- Display output.
local hl = rep("-", 72)
print("*** Local/Global Variable Tracker Tables ***")
print(hl.."\n GLOBALS\n"..hl)
-- global tables have a list of xref numbers only
for i = 1, #globalinfo do
local obj = globalinfo[i]
local msg = "("..i..") '"..obj.name.."' -> "
local xref = obj.xref
for j = 1, #xref do msg = msg..xref[j].." " end
print(msg)
end
-- Local tables have xref numbers and a few other special
-- numbers that are specially named: decl (declaration xref),
-- act (activation xref), rem (removal xref).
print(hl.."\n LOCALS (decl=declared act=activated rem=removed)\n"..hl)
for i = 1, #localinfo do
local obj = localinfo[i]
local msg = "("..i..") '"..obj.name.."' decl:"..obj.decl..
" act:"..obj.act.." rem:"..obj.rem
if obj.is_special then
msg = msg.." is_special"
end
msg = msg.." -> "
local xref = obj.xref
for j = 1, #xref do msg = msg..xref[j].." " end
print(msg)
end
print(hl.."\n")
end
--- Reads source file(s) and reports some statistics.
--
-- @tparam string srcfl Path of the source file.
local function read_only(srcfl)
-- Load file and process source input into tokens.
local z = load_file(srcfl)
local toklist, seminfolist = llex.lex(z)
print(MSG_TITLE)
print("Statistics for: "..srcfl.."\n")
-- Collect statistics.
stat_init()
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
stat_add(tok, seminfo)
end--for
local stat_a = stat_calc()
-- Display output.
local function figures(tt)
return stat_c[tt], stat_l[tt], stat_a[tt]
end
local tabf1, tabf2 = "%-16s%8s%8s%10s", "%-16s%8d%8d%10.2f"
local hl = rep("-", 42)
print(fmt(tabf1, "Lexical", "Input", "Input", "Input"))
print(fmt(tabf1, "Elements", "Count", "Bytes", "Average"))
print(hl)
for i = 1, #TTYPES do
local ttype = TTYPES[i]
print(fmt(tabf2, ttype, figures(ttype)))
if ttype == "TK_EOS" then print(hl) end
end
print(hl)
print(fmt(tabf2, "Total Elements", figures("TOTAL_ALL")))
print(hl)
print(fmt(tabf2, "Total Tokens", figures("TOTAL_TOK")))
print(hl.."\n")
end
--- Processes source file(s), writes output and reports some statistics.
--
-- @tparam string srcfl Path of the source file.
-- @tparam string destfl Path of the destination file where to write optimized source.
local function process_file(srcfl, destfl)
-- handle quiet option
local function print(...) --luacheck: ignore 431
if option.QUIET then return end
_G.print(...)
end
if plugin and plugin.init then -- plugin init
option.EXIT = false
plugin.init(option, srcfl, destfl)
if option.EXIT then return end
end
print(MSG_TITLE) -- title message
-- Load file and process source input into tokens.
local z = load_file(srcfl)
if plugin and plugin.post_load then -- plugin post-load
z = plugin.post_load(z) or z
if option.EXIT then return end
end
local toklist, seminfolist, toklnlist = llex.lex(z)
if plugin and plugin.post_lex then -- plugin post-lex
plugin.post_lex(toklist, seminfolist, toklnlist)
if option.EXIT then return end
end
-- Collect 'before' statistics.
stat_init()
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
stat_add(tok, seminfo)
end--for
local stat1_a = stat_calc()
local stat1_c, stat1_l = stat_c, stat_l
-- Do parser optimization here.
optparser.print = print -- hack
local xinfo = lparser.parse(toklist, seminfolist, toklnlist)
if plugin and plugin.post_parse then -- plugin post-parse
plugin.post_parse(xinfo.globalinfo, xinfo.localinfo)
if option.EXIT then return end
end
optparser.optimize(option, toklist, seminfolist, xinfo)
if plugin and plugin.post_optparse then -- plugin post-optparse
plugin.post_optparse()
if option.EXIT then return end
end
-- Do lexer optimization here, save output file.
local warn = optlex.warn -- use this as a general warning lookup
optlex.print = print -- hack
toklist, seminfolist, toklnlist
= optlex.optimize(option, toklist, seminfolist, toklnlist)
if plugin and plugin.post_optlex then -- plugin post-optlex
plugin.post_optlex(toklist, seminfolist, toklnlist)
if option.EXIT then return end
end
local dat = concat(seminfolist)
-- Depending on options selected, embedded EOLs in long strings and
-- long comments may not have been translated to \n, tack a warning.
if find(dat, "\r\n", 1, 1) or
find(dat, "\n\r", 1, 1) then
warn.MIXEDEOL = true
end
-- Save optimized source stream to output file.
save_file(destfl, dat)
-- Collect 'after' statistics.
stat_init()
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
stat_add(tok, seminfo)
end--for
local stat_a = stat_calc()
-- Display output.
print("Statistics for: "..srcfl.." -> "..destfl.."\n")
local function figures(tt)
return stat1_c[tt], stat1_l[tt], stat1_a[tt],
stat_c[tt], stat_l[tt], stat_a[tt]
end
local tabf1, tabf2 = "%-16s%8s%8s%10s%8s%8s%10s",
"%-16s%8d%8d%10.2f%8d%8d%10.2f"
local hl = rep("-", 68)
print("*** lexer-based optimizations summary ***\n"..hl)
print(fmt(tabf1, "Lexical",
"Input", "Input", "Input",
"Output", "Output", "Output"))
print(fmt(tabf1, "Elements",
"Count", "Bytes", "Average",
"Count", "Bytes", "Average"))
print(hl)
for i = 1, #TTYPES do
local ttype = TTYPES[i]
print(fmt(tabf2, ttype, figures(ttype)))
if ttype == "TK_EOS" then print(hl) end
end
print(hl)
print(fmt(tabf2, "Total Elements", figures("TOTAL_ALL")))
print(hl)
print(fmt(tabf2, "Total Tokens", figures("TOTAL_TOK")))
print(hl)
-- Report warning flags from optimizing process.
if warn.LSTRING then
print("* WARNING: "..warn.LSTRING)
elseif warn.MIXEDEOL then
print("* WARNING: ".."output still contains some CRLF or LFCR line endings")
elseif warn.SRC_EQUIV then
print("* WARNING: "..smsg)
elseif warn.BIN_EQUIV then
print("* WARNING: "..bmsg)
end
print()
end
---------------------------- Main functions ---------------------------
local arg = {...} -- program arguments
set_options(DEFAULT_CONFIG) -- set to default options at beginning
--- Does per-file handling, ship off to tasks.
--
-- @tparam {string,...} fspec List of source files.
local function do_files(fspec)
for i = 1, #fspec do
local srcfl = fspec[i]
local destfl
-- Find and replace extension for filenames.
local extb, exte = find(srcfl, "%.[^%.%\\%/]*$")
local basename, extension = srcfl, ""
if extb and extb > 1 then
basename = sub(srcfl, 1, extb - 1)
extension = sub(srcfl, extb, exte)
end
destfl = basename..suffix..extension
if #fspec == 1 and option.OUTPUT_FILE then
destfl = option.OUTPUT_FILE
end
if srcfl == destfl then
die("output filename identical to input filename")
end
-- Perform requested operations.
if option.DUMP_LEXER then
dump_tokens(srcfl)
elseif option.DUMP_PARSER then
dump_parser(srcfl)
elseif option.READ_ONLY then
read_only(srcfl)
else
process_file(srcfl, destfl)
end
end--for
end
--- The main function.
local function main()
local fspec = {}
local argn, i = #arg, 1
if argn == 0 then
option.HELP = true
end
-- Handle arguments.
while i <= argn do
local o, p = arg[i], arg[i + 1]
local dash = match(o, "^%-%-?")
if dash == "-" then -- single-dash options
if o == "-h" then
option.HELP = true; break
elseif o == "-v" then
option.VERSION = true; break
elseif o == "-s" then
if not p then die("-s option needs suffix specification") end
suffix = p
i = i + 1
elseif o == "-o" then
if not p then die("-o option needs a file name") end
option.OUTPUT_FILE = p
i = i + 1
elseif o == "-" then
break -- ignore rest of args
else
die("unrecognized option "..o)
end
elseif dash == "--" then -- double-dash options
if o == "--help" then
option.HELP = true; break
elseif o == "--version" then
option.VERSION = true; break
elseif o == "--keep" then
if not p then die("--keep option needs a string to match for") end
option.KEEP = p
i = i + 1
elseif o == "--plugin" then
if not p then die("--plugin option needs a module name") end
if option.PLUGIN then die("only one plugin can be specified") end
option.PLUGIN = p
plugin = require(PLUGIN_SUFFIX..p)
i = i + 1
elseif o == "--quiet" then
option.QUIET = true
elseif o == "--read-only" then
option.READ_ONLY = true
elseif o == "--basic" then
set_options(BASIC_CONFIG)
elseif o == "--maximum" then
set_options(MAXIMUM_CONFIG)
elseif o == "--none" then
set_options(NONE_CONFIG)
elseif o == "--dump-lexer" then
option.DUMP_LEXER = true
elseif o == "--dump-parser" then
option.DUMP_PARSER = true
elseif o == "--details" then
option.DETAILS = true
elseif OPTION[o] then -- lookup optimization options
set_options(o)
else
die("unrecognized option "..o)
end
else
fspec[#fspec + 1] = o -- potential filename
end
i = i + 1
end--while
if option.HELP then
print(MSG_TITLE..MSG_USAGE); return true
elseif option.VERSION then
print(MSG_TITLE); return true
end
if option["opt-binequiv"] and not BIN_EQUIV_AVAIL then
die("--opt-binequiv is available only for PUC Lua 5.1!")
end
if #fspec > 0 then
if #fspec > 1 and option.OUTPUT_FILE then
die("with -o, only one source file can be specified")
end
do_files(fspec)
return true
else
die("nothing to do!")
end
end
-- entry point -> main() -> do_files()
if not main() then
die("Please run with option -h or --help for usage information")
end
|
function extraNumber(a, b, c)
if a == b then
return c
end
if a == c then
return b
end
return a
end
|
-- ByCat#7797
-- Fixed
local i_primary = ui.add_combo_box("Primary", "i_primary", { "off", "Auto", "Scout", "AWP" }, 0)
local i_secondary = ui.add_combo_box("Secondary", "i_secondary", { "off", "Deagle/R8", "Duals" }, 0)
local buy_Other = ui.add_check_box("Other (Nade, Taser)", "buy_Other", true)
local function buy_bot(event)
if event:get_name() == "round_start" then
if i_primary:get_value() == 1 then
engine.execute_client_cmd("buy scar20")
end
if i_primary:get_value() == 2 then
engine.execute_client_cmd("buy SSG08")
end
if i_primary:get_value() == 3 then
engine.execute_client_cmd("buy awp")
end
-- pistols
if i_secondary:get_value() == 1 then
engine.execute_client_cmd("buy Deagle")
end
if i_secondary:get_value() == 2 then
engine.execute_client_cmd("buy elite")
end
if buy_Other:get_value() then
engine.execute_client_cmd("buy taser;buy vest; buy vesthelm; buy taser; buy defuser; buy hegrenade; buy smokegrenade; buy molotov;")
end
end
end
client.register_callback("fire_game_event", buy_bot)
|
-- Setting player inventory
local function main(e)
local player = game.players[e.player_index]
if not player.get_main_inventory() then return end
-- Main inventory
player.insert{name="construction-robot", count = 50}
player.insert{name = "fusion-reactor-equipment", count = 2}
player.insert{name = "personal-roboport-mk2-equipment", count = 2}
player.insert{name = "exoskeleton-equipment", count = 5}
player.insert{name = "battery-mk2-equipment", count = 4}
player.insert{name = "solar-panel-equipment", count = 7}
player.insert{name = "belt-immunity-equipment", count = 1}
player.insert{name = "perfect-night-glasses", count = 1}
-- Guns
player.get_inventory(defines.inventory.character_guns).clear()
player.get_inventory(defines.inventory.character_ammo).clear()
-- Worker robot cargo size research (5 tiers in Vanilla)
player.force.technologies['worker-robots-speed-1'].researched = true
player.force.technologies['worker-robots-speed-2'].researched = true
player.force.technologies['worker-robots-speed-3'].researched = true
player.force.technologies['worker-robots-speed-4'].researched = true
player.force.technologies['worker-robots-speed-5'].researched = true
-- Worker robot cargo size research (3 tiers in Vanilla)
player.force.technologies['worker-robots-storage-1'].researched = true
player.force.technologies['worker-robots-storage-2'].researched = true
player.force.technologies['worker-robots-storage-3'].researched = true
end
local function player_created(e)
main(e)
end
local function cutscene_cancelled(e)
if remote.interfaces["freeplay"] then
main(e)
end
end
script.on_event(defines.events.on_player_created,player_created)
script.on_event(defines.events.on_cutscene_cancelled,cutscene_cancelled) |
-- There should be only one instance of this code
-- running for a given lua state
--[[
Queue
--]]
local Queue = {}
setmetatable(Queue, {
__call = function(self, ...)
return self:create(...);
end,
});
local Queue_mt = {
__index = Queue;
}
function Queue.init(self, first, last, name)
first = first or 1;
last = last or 0;
local obj = {
first=first,
last=last,
name=name};
setmetatable(obj, Queue_mt);
return obj
end
function Queue.create(self, first, last, name)
first = first or 1
last = last or 0
return self:init(first, last, name);
end
--[[
function Queue.new(name)
return Queue:init(1, 0, name);
end
--]]
function Queue:enqueue(value)
--self.MyList:PushRight(value)
local last = self.last + 1
self.last = last
self[last] = value
return value
end
function Queue:pushFront(value)
-- PushLeft
local first = self.first - 1;
self.first = first;
self[first] = value;
end
function Queue:dequeue(value)
-- return self.MyList:PopLeft()
local first = self.first
if first > self.last then
return nil, "list is empty"
end
local value = self[first]
self[first] = nil -- to allow garbage collection
self.first = first + 1
return value
end
function Queue:length()
return self.last - self.first+1
end
-- Returns an iterator over all the current
-- values in the queue
function Queue:entries(func, param)
local starting = self.first-1;
local len = self:length();
local closure = function()
starting = starting + 1;
return self[starting];
end
return closure;
end
-- Task specifics
local Task = {}
setmetatable(Task, {
__call = function(self, ...)
return self:create(...);
end,
});
local Task_mt = {
__index = Task,
}
function Task.init(self, aroutine, ...)
local obj = {
routine = coroutine.create(aroutine),
}
setmetatable(obj, Task_mt);
obj:setParams({...});
return obj
end
function Task.create(self, aroutine, ...)
-- The 'aroutine' should be something that is callable
-- either a function, or a table with a meta '__call'
-- implementation. Checking with type == 'function'
-- is not good enough as it will miss the meta __call cases
return self:init(aroutine, ...)
end
function Task.getStatus(self)
return coroutine.status(self.routine);
end
-- A function that can be used as a predicate
function Task.isFinished(self)
return task:getStatus() == "dead"
end
function Task.setParams(self, params)
self.params = params
return self;
end
function Task.resume(self)
--print("Task, RESUMING: ", unpack(self.params));
return coroutine.resume(self.routine, unpack(self.params));
end
function Task.yield(self, ...)
return coroutine.yield(...)
end
-- kernel state
local ContinueRunning = true;
local TaskID = 0;
local TasksSuspendedForSignal = {};
local TasksReadyToRun = Queue();
local CurrentTask = nil;
-- Scheduler Related
local function tasksPending()
return TasksReadyToRun:length();
end
-- put a task on the ready list
-- the 'task' should be something that can be executed,
-- whether it's a function, functor, or something that has a '__call'
-- metamethod implemented.
-- The 'params' is a table of parameters which will be passed to the function
-- when it's ready to run.
local function scheduleTask(task, params)
--print("Scheduler.scheduleTask: ", task, params)
params = params or {}
if not task then
return false, "no task specified"
end
task:setParams(params);
TasksReadyToRun:enqueue(task);
task.state = "readytorun"
return task;
end
local function removeTask(tsk)
--print("REMOVING DEAD FIBER: ", fiber);
return true;
end
local function inMainFiber()
return coroutine.running() == nil;
end
local function getCurrentTask()
return CurrentTask;
end
local function suspendCurrentTask(...)
CurrentTask.state = "suspended"
end
local function SchedulerStep()
-- Now check the regular fibers
local task = TasksReadyToRun:dequeue()
-- If no fiber in ready queue, then just return
if task == nil then
--print("Scheduler.step: NO TASK")
return true
end
if task:getStatus() == "dead" then
removeFiber(task)
return true;
end
-- If the task we pulled off the active list is
-- not dead, then perhaps it is suspended. If that's true
-- then it needs to drop out of the active list.
-- We assume that some other part of the system is responsible for
-- keeping track of the task, and rescheduling it when appropriate.
if task.state == "suspended" then
--print("suspended task wants to run")
return true;
end
-- If we have gotten this far, then the task truly is ready to
-- run, and it should be set as the currentFiber, and its coroutine
-- is resumed.
CurrentTask = task;
local results = {task:resume()};
-- once we get results back from the resume, one
-- of two things could have happened.
-- 1) The routine exited normally
-- 2) The routine yielded
--
-- In both cases, we parse out the results of the resume
-- into a success indicator and the rest of the values returned
-- from the routine
--local pcallsuccess = results[1];
--table.remove(results,1);
local success = results[1];
table.remove(results,1);
--print("PCALL, RESUME: ", pcallsuccess, success)
-- no task is currently executing
CurrentTask = nil;
if not success then
print("RESUME ERROR")
print(unpack(results));
end
-- Again, check to see if the task is dead after
-- the most recent resume. If it's dead, then don't
-- bother putting it back into the readytorun queue
-- just remove the task from the list of tasks
if task:getStatus() == "dead" then
removeTask(task)
return true;
end
-- The only way the task will get back onto the readylist
-- is if it's state is 'readytorun', otherwise, it will
-- stay out of the readytorun list.
if task.state == "readytorun" then
scheduleTask(task, results);
end
end
-- Kernel specific routines
local function getNewTaskID()
TaskID = TaskID + 1;
return TaskID;
end
local function getCurrentTaskID()
return getCurrentTask().TaskID;
end
local function spawn(func, ...)
local task = Task(func, ...)
task.TaskID = getNewTaskID();
scheduleTask(task, {...});
return task;
end
local function suspend(...)
suspendCurrentTask();
return yield(...)
end
local function yield(...)
return coroutine.yield(...);
end
local function signalOne(eventName, ...)
if not TasksSuspendedForSignal[eventName] then
return false, "event not registered", eventName
end
local nTasks = #TasksSuspendedForSignal[eventName]
if nTasks < 1 then
return false, "no tasks waiting for event"
end
local suspended = TasksSuspendedForSignal[eventName][1];
scheduleTask(suspended,{...});
table.remove(TasksSuspendedForSignal[eventName], 1);
return true;
end
local function signalAll(eventName, ...)
if not TasksSuspendedForSignal[eventName] then
return false, "event not registered"
end
local nTasks = #TasksSuspendedForSignal[eventName]
if nTasks < 1 then
return false, "no tasks waiting for event"
end
for i=1,nTasks do
scheduleTask(TasksSuspendedForSignal[eventName][1],{...});
table.remove(TasksSuspendedForSignal[eventName], 1);
end
return true;
end
local function waitForSignal(eventName)
local cTask = getCurrentTask();
if cTask == nil then
return false, "not currently in a running task"
end
if not TasksSuspendedForSignal[eventName] then
TasksSuspendedForSignal[eventName] = {}
end
table.insert(TasksSuspendedForSignal[eventName], cTask);
return suspend()
end
local function onSignal(self, func, eventName)
local function closure()
waitForSignal(eventName)
func();
end
return spawn(closure)
end
local function run(func, ...)
if func ~= nil then
spawn(func, ...)
end
while (ContinueRunning) do
SchedulerStep();
end
end
local function halt(self)
ContinueRunning = false;
end
local exports = {
halt = halt;
run = run;
spawn = spawn;
suspend = suspend;
yield = yield;
onSignal = onSignal;
signalAll = signalAll;
signalOne = signalOne;
waitForSignal = waitForSignal;
}
-- put everything into the global namespace by default
for k,v in pairs(exports) do
_G[k] = v;
end
return exports;
|
// This is mainly for the benefit of Lua programmers, developers, and beta testers.
SWEP_BASES = true
SWEP_BASES_VERSION = 323
SWEP_BASES_AUTHOR = "Andrew McWatters"
include( "sb_lua_functions.lua" )
for k, v in pairs( file.Find( "autorun/sb_*.lua", "LUA" ) ) do AddCSLuaFile( v ) end |
--[[
Guide to LoveUI.Textfield.
Properties:
--Property
--[Example Values] description
tabAccessible
[true/false] whether can select textfield with tab. default true.
hidden
[true/false] set false to hide and disable textfield. default false.
enabled
[true/false] set false to disable editting. default true.
textColor
[love.graphics.newColor(0,0,0)] set to change text color
opaque
[true/false] whether to draw blackground default true.
image
[nil] set to nil to disable gloss
value
["aString"] set this to set string contents
backgroundColor
[aColor] set background color
font
[aFont] set text font.
setFrame(aFrame)
to change origin, size of Textfield
selectAll()
select all.
setAction(anAction, EventType, aTarget)
Refer to LoveUI.lua, search for 'Control Events', possible Event Types are listed there. Not all are responded to. set eventType nil to use default.
]]--
LoveUI.require("LoveUIControl.lua")
LoveUI.require("LoveUITextfieldCell.lua")
LoveUI.Textfield=LoveUI.Control:new();
function LoveUI.Textfield:init(frame)
-- e.g local o=LoveUI.Object:alloc():init();
LoveUI.Control.init(self, frame, LoveUI.TextfieldCell:new(self, LoveUI:getImage("light-gloss-bottom-top.png")));
self.editable=true;
self.enabled=true;
self.cellClass=LoveUI.TextfieldCell;
self.cell.value=""
self.shouldResignFirstResponder=false
self.opaque=true;
self.isFirstResponder=false;
self.justBecameFirstResponder=false
self.tabAccessible=true;
return self;
end
function LoveUI.Textfield:display()
self.cell:display(self.frame, self)
end
function LoveUI.Textfield:update(dt)
self.cell:update(dt);
end
function LoveUI.Textfield:selectAll()
self.cell.selectStart=0
self.cell.selectLength=#tostring(self.cell.value)
end
function LoveUI.Textfield:mouseDown(theEvent)
--self.color=LoveUI.graphics.newColor(0, 0, 255);
self.cell:mouseDown(theEvent);
end
function LoveUI.Textfield:acceptsFirstResponder()
return self.enabled;
end
function LoveUI.Textfield:becomeFirstResponder()
self.isFirstResponder=true;
if self.enabled then
self.cell.state=LoveUI.OnState;
self:selectAll();
self.justBecameFirstResponder = true;
end
return self.enabled;
end
function LoveUI.Textfield:resignFirstResponder()
return self.cell:resignFirstResponder();
end
function LoveUI.Textfield:setAction(anAction, forControlEvent)
self.cell:setActionForEvent(anAction, forControlEvent);
end
function LoveUI.Textfield:getAction()
return self.cell.action;
end
function LoveUI.Textfield:mouseUp(theEvent)
self.cell:mouseUp(theEvent);
end
function LoveUI.Textfield:keyDown(theEvent)
if theEvent.keyCode==love.key_tab then
LoveUI.Control.keyDown(self, theEvent);
return
end
self.cell:keyDown(theEvent);
end |
require 'cutorch'
require 'libcuorn'
require 'cunn'
require 'orn' |
local gems = require "columns.gems"
local boards = require "columns.boards"
context("Gem", function()
context("combinations", function()
before(function()
board = boards({ w = 2, h = 1 })
hole = gems.hole()
wild = gems.wild()
fixed = gems.fixed()
obstacle = gems.obstacle()
gem_a = gems.normal{ color = 1 }
gem_b = gems.normal{ color = 1 }
gem_c = gems.normal{ color = 2 }
end)
CHOICES = {
{ 'hole' , 'hole' , false },
{ 'wild' , 'wild' , true },
{ 'fixed' , 'fixed' , false },
{ 'obstacle' , 'obstacle' , false },
{ 'gem_a' , 'gem_a' , true },
{ 'gem_b' , 'gem_b' , true },
{ 'gem_c' , 'gem_c' , true },
{ 'hole' , 'wild' , false },
{ 'hole' , 'fixed' , false },
{ 'hole' , 'obstacle' , false },
{ 'hole' , 'gem_a' , false },
{ 'hole' , 'gem_b' , false },
{ 'hole' , 'gem_c' , false },
-- Wildcards get their own tests.
--{ 'wild' , 'fixed' , false },
--{ 'wild' , 'obstacle' , false },
--{ 'wild' , 'gem_a' , true },
--{ 'wild' , 'gem_b' , true },
--{ 'wild' , 'gem_c' , true },
{ 'fixed' , 'obstacle' , false },
{ 'fixed' , 'gem_a' , false },
{ 'fixed' , 'gem_b' , false },
{ 'fixed' , 'gem_c' , false },
{ 'obstacle' , 'gem_a' , false },
{ 'obstacle' , 'gem_b' , false },
{ 'obstacle' , 'gem_c' , false },
{ 'gem_a' , 'gem_b' , true },
{ 'gem_a' , 'gem_c' , false },
{ 'gem_b' , 'gem_c' , false },
}
for _, combination in ipairs(CHOICES) do
test("compares " .. combination[1] .. " with " .. combination[2], function()
local env = getfenv()
local a = env[combination[1]]
local b = env[combination[2]]
if combination[3] then
board.set(1, 1, a); board.set(2, 1, b)
assert_true(gems.isMatch(board, {{x=1, y=1}, {x=2, y=1}}, 1))
board.set(1, 1, b); board.set(2, 1, a)
assert_true(gems.isMatch(board, {{x=1, y=1}, {x=2, y=1}}, 1))
else
board.set(1, 1, a); board.set(2, 1, b)
assert_false(not not gems.isMatch(board, {{x=1, y=1}, {x=2, y=1}}, 1))
board.set(1, 1, b); board.set(2, 1, a)
assert_false(not not gems.isMatch(board, {{x=1, y=1}, {x=2, y=1}}, 1))
end
end)
end
end)
context("wildcards", function()
before(function()
coords = {{x=1, y=1}, {x=2, y=1}, {x=3, y=1}}
board = boards({ w = 4, h = 1 })
hole = gems.hole()
wild = gems.wild()
fixed = gems.fixed()
obstacle = gems.obstacle()
gem_a = gems.normal{ color = 1 }
gem_b = gems.normal{ color = 2 }
end)
test("WAA wildcards matches", function()
board.set(1, 1, wild); board.set(2, 1, gem_a); board.set(3, 1, gem_a)
assert_true(not not gems.isMatch(board, coords, 1))
assert_true(not not gems.isMatch(board, coords, 2))
end)
test("AWA wildcards matches", function()
board.set(1, 1, gem_a); board.set(2, 1, wild); board.set(3, 1, gem_a)
assert_true(not not gems.isMatch(board, coords, 1))
assert_true(not not gems.isMatch(board, coords, 2))
end)
test("AAW wildcards matches", function()
board.set(1, 1, gem_a); board.set(2, 1, gem_a); board.set(3, 1, wild)
assert_true(not not gems.isMatch(board, coords, 1))
assert_true(not not gems.isMatch(board, coords, 2))
end)
test("WAB wildcards does not match", function()
board.set(1, 1, wild); board.set(2, 1, gem_a); board.set(3, 1, gem_b)
assert_false(not not gems.isMatch(board, coords, 1))
assert_false(not not gems.isMatch(board, coords, 2))
end)
test("AWB wildcards does not match", function()
board.set(1, 1, gem_a); board.set(2, 1, wild); board.set(3, 1, gem_b)
assert_false(not not gems.isMatch(board, coords, 1))
assert_false(not not gems.isMatch(board, coords, 2))
end)
test("BAW wildcards does not match", function()
board.set(1, 1, gem_b); board.set(2, 1, gem_a); board.set(3, 1, wild)
assert_false(not not gems.isMatch(board, coords, 1))
assert_false(not not gems.isMatch(board, coords, 2))
end)
test("ABW wildcards does not match", function()
board.set(1, 1, gem_a); board.set(2, 1, gem_b); board.set(3, 1, wild)
assert_false(not not gems.isMatch(board, coords, 1))
assert_false(not not gems.isMatch(board, coords, 2))
end)
test("WAW wildcards matches", function()
board.set(1, 1, wild); board.set(2, 1, gem_a); board.set(3, 1, wild)
assert_true(gems.isMatch(board, coords, 1))
assert_true(gems.isMatch(board, coords, 2))
end)
test("AAWB wildcards matches only first 3", function()
board.set(1, 1, gem_a); board.set(2, 1, gem_a); board.set(3, 1, wild); board.set(4, 1, gem_a)
assert_true(gems.isMatch(board, coords, 1))
assert_true(gems.isMatch(board, coords, 2))
assert_false(not not gems.isMatch(board, coords, 3))
end)
end)
end)
|
local function CreditsText( pn )
function update(self)
local str = ScreenSystemLayerHelpers.GetCreditsMessage(pn);
self:settext(str);
end
function UpdateVisible(self)
local screen = SCREENMAN:GetTopScreen();
local bShow = true;
if screen then
local sClass = screen:GetName();
bShow = THEME:GetMetric( sClass, "ShowCreditDisplay" );
end
self:visible( bShow );
end
local text = Font("mentone","24px") .. {
InitCommand=function(self)
self:name("Credits" .. PlayerNumberToString(pn))
ActorUtil.LoadAllCommandsAndSetXY(self,Var "LoadingScreen");
end;
UpdateTextCommand=function(self)
local str = ScreenSystemLayerHelpers.GetCreditsMessage(pn);
self:settext(str);
end;
UpdateVisibleCommand=function(self)
local screen = SCREENMAN:GetTopScreen();
local bShow = true;
if screen then
local sClass = screen:GetName();
bShow = THEME:GetMetric( sClass, "ShowCreditDisplay" );
end
self:visible( bShow );
end;
--[[ RefreshCreditTextMessageCommand=update;
CoinInsertedMessageCommand=update;
PlayerJoinedMessageCommand=update;
ScreenChangedMessageCommand=UpdateVisible; --]]
};
return text;
end
local t = Def.ActorFrame {
CreditsText( PLAYER_1 );
CreditsText( PLAYER_2 );
};
return t; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.