content stringlengths 5 1.05M |
|---|
-- Action
local setmetatable = setmetatable
local _M = { _VERSION = '0.0.1' }
local mt = { __index = _M }
function _M.new(name, action)
return setmetatable({
name = name,
action = action
}, mt)
end
function _M.execute(self, rule_name, decision)
local name = self.name
local action = self.action
decision:match(rule_name)
local fn = decision[name]
if fn then
fn(decision, action)
return
end
end
return _M |
module("moonscript.data", package.seeall)
local stack_t = {}
local _stack_mt = { __index = stack_t, __tostring = function(self)
return "<Stack {"..table.concat(self, ", ").."}>"
end}
function stack_t:pop()
return table.remove(self)
end
function stack_t:push(value)
table.insert(self, value)
return value
end
function stack_t:top()
return self[#self]
end
function Stack(...)
local self = setmetatable({}, _stack_mt)
for _, v in ipairs{...} do
self:push(v)
end
return self
end
function Set(items)
local self = {}
for _,item in ipairs(items) do
self[item] = true
end
return self
end
-- find out the type of a node
function ntype(node)
if type(node) ~= "table" then return "value" end
return node[1]
end
lua_keywords = Set{
'and', 'break', 'do', 'else', 'elseif',
'end', 'false', 'for', 'function', 'if',
'in', 'local', 'nil', 'not', 'or',
'repeat', 'return', 'then', 'true',
'until', 'while'
}
|
--------------------------------------------------------------------------------
-- Kui Nameplates
-- By Kesava at curse.com
-- All rights reserved
--------------------------------------------------------------------------------
-- Base element script handler & base frame element registrar
-- Update registered elements and dispatch messages
--------------------------------------------------------------------------------
local addon = KuiNameplates
local wipe = wipe
addon.Nameplate = {}
addon.Nameplate.__index = addon.Nameplate
-- Element registrar
function addon.Nameplate.RegisterElement(frame, element_name, element_frame)
frame = frame.parent
if frame[element_name] then return end
frame.elements[element_name] = true
frame[element_name] = element_frame
-- approximate provider;
-- can't find elements with different names to their parent plugin
local provider = addon:GetPlugin(element_name)
if provider and type(provider.PostRegister) == 'function' then
provider:PostRegister(frame,element_name)
end
end
-- Disable/enable an element on a per-frame basis:
-- XXX important to note that once an element is disabled, it must be manually
-- re-enabled for that frame; it does not re-enable when a frame is re-used.
function addon.Nameplate.DisableElement(frame, element_name)
if not element_name then return end
frame = frame.parent
if frame and frame.elements[element_name] then
frame.elements[element_name] = false
local provider = addon:GetPlugin(element_name)
if provider and type(provider.DisableOnFrame) == 'function' then
provider:DisableOnFrame(frame,element_name)
end
end
end
function addon.Nameplate.EnableElement(frame, element_name)
if not element_name then return end
frame = frame.parent
if frame and frame.elements[element_name] == false then
frame.elements[element_name] = true
local provider = addon:GetPlugin(element_name)
if provider and type(provider.EnableOnFrame) == 'function' then
provider:EnableOnFrame(frame,element_name)
end
end
end
-------------------------------------------------------- Frame event handlers --
function addon.Nameplate.OnUnitAdded(f,unit)
f = f.parent
if not unit then
addon:print('NO UNIT: '..f:GetName())
return
else
f.state.personal = UnitIsUnit(unit,'player')
f.unit = unit
f.handler:OnShow()
end
end
------------------------------------------------------- Frame script handlers --
function addon.Nameplate.OnShow(f)
f = f.parent
f:Show()
addon:DispatchMessage('Show', f)
end
function addon.Nameplate.OnHide(f)
f = f.parent
if not f:IsShown() then return end
f:Hide()
addon:DispatchMessage('Hide', f)
f.unit = nil
wipe(f.state)
end
function addon.Nameplate.Create(f)
f = f.parent
addon:DispatchMessage('Create', f)
end
|
local hotkey = require "hs.hotkey"
local grid = require "hs.grid"
local window = require "hs.window"
local application = require "hs.application"
local appfinder = require "hs.appfinder"
local fnutils = require "hs.fnutils"
hs.application.enableSpotlightForNameSearches(true)
local logger = hs.logger.new('Launcher', 'debug')
grid.setMargins({0, 0})
applist = {
{shortcut = '1', appname = 'OmniFocus'},
{shortcut = '2', appname = 'flomo'},
{shortcut = 'A', appname = 'Sequel Ace'},
{shortcut = 'C', appname = 'Visual Studio Code'},
{shortcut = 'D', appname = 'Dash'},
{shortcut = 'E', appname = 'EuDic'},
{shortcut = 'F', appname = 'Firefox'},
{shortcut = 'J', appname = 'Safari'},
{shortcut = 'K', appname = 'kitty'},
{shortcut = 'L', appname = 'Telegram'},
{shortcut = 'M', appname = 'Mail'},
{shortcut = 'N', appname = 'Notion'},
{shortcut = 'O', appname = 'Microsoft Outlook'},
{shortcut = 'P', appname = 'PhpStorm'},
{shortcut = 'Q', appname = 'Activity Monitor'},
{shortcut = 'S', appname = 'Slack'},
{shortcut = 'V', appname = 'MacVim'},
{shortcut = 'W', appname = 'Workflowy'}
}
local hostnames = hs.host.names()
--[[
[ Map key B to the default browser.
]]
local defaultBrowser = nil
for i = 1, #hostnames do
if string.find(string.lower(hostnames[i]), 'imac') ~= nil then
defaultBrowser = 'Google Chrome'
break
elseif string.find(string.lower(hostnames[i]), 'mbp') ~= nil then
defaultBrowser = 'Brave Browser'
break
end
end
if defaultBrowser ~= nil then
table.insert(applist, {shortcut = 'B', appname = defaultBrowser})
end
--[[
[ Map key T to the default twitter client.
]]
local defaultTwitterClient = nil
for i = 1, #hostnames do
if string.find(string.lower(hostnames[i]), 'imac') ~= nil then
defaultTwitterClient = 'Twitter'
break
elseif string.find(string.lower(hostnames[i]), 'mbp') ~= nil then
defaultTwitterClient = 'Tweetbot'
break
end
end
if defaultTwitterClient ~= nil then
table.insert(applist, {shortcut = 'T', appname = defaultTwitterClient})
end
-- Do mappings.
fnutils.each(applist, function(entry)
hotkey.bind({'alt'}, entry.shortcut, entry.appname, function()
-- application.launchOrFocus(entry.appname)
toggle_application(entry.appname)
end)
end)
-- Toggle an application between being the frontmost app, and being hidden
function toggle_application(app_name)
local app = appfinder.appFromName(app_name)
if not app or not app:mainWindow() then
application.launchOrFocus(app_name)
return
else
local mainwin = app:mainWindow()
if mainwin == window.focusedWindow() then
mainwin:application():hide()
else
mainwin:application():activate(true)
mainwin:application():unhide()
mainwin:focus()
end
end
end
|
--------------------------------
-- @module ContourData
-- @extend Ref
-- @parent_module ccs
---@class ccs.ContourData:ccs.Ref
local ContourData = {}
ccs.ContourData = ContourData
--------------------------------
---
---@return boolean
function ContourData:init()
end
--------------------------------
---
---@param vertex vec2_table
---@return ccs.ContourData
function ContourData:addVertex(vertex)
end
--------------------------------
---
---@return ccs.ContourData
function ContourData:create()
end
--------------------------------
--- js ctor
---@return ccs.ContourData
function ContourData:ContourData()
end
return nil
|
--- SETUP
local tool = script.Parent;
local server = require(game:GetService("ServerStorage"):WaitForChild("nofairTCM_Server"):WaitForChild("GunKit"));
local this = server:setup():setGun {
tool = tool;
settings = require(tool.settings);
};
--- BIND EVENT
-- setupClient 에 설명을 확인해주세요 (이건 이제 서버에서 작동하는 부분)
-- 웹훅 사용시 주의사항
-- 웹훅이 필요하시면 ServerStorage 에 모듈을 만들고 requrie 해와서 쓰는 방식을 쓰세요
-- 그렇게 하지 않고 여기에 바로 웹훅을 집어넣으면 웹훅 아이디가 노출될 수 있으며
-- 다른이가 사용할 수 있게 됩니다
this:bind("kill",function(thisPlayer,killedHumanoidObj,killedPlayer)
end);
this:bind("fire",function(thisPlayer,firePos,hitPos,hitObj,hitHumanoid,hitPlayer)
end);
|
-- Biological cell simulation
-- Disclaimer: I am not a molecular biologist! (Nor am I a computer scientist.)
foobar: Cell {
cell: self
dna: [
foo: 40
]
rna: Queue new
ribosomes: Set new
transcribe: '(value)' => {
instructions: {
-- ...
}
dna foo | ≥ 42 | if true -> rna put (instructions)
}
ribosome: {
process: '(instructions)' => {
protein: Protein from (instructions)
cell << events emit "protein" (protein)
}
loop -> {
instructions: await (rna take promise)
process (instructions)
}
}
ribosomes add (ribosome)
dna on change (transcribe)
'increase foo' => {
dna foo | increment
}
}
foobar increase foo
foobar increase foo -- A new protein is emitted!
|
-- Common Localizations - Finnish
-- Localizations are licensed under the MIT License, from http://goo.gl/fhnw1t
lang_dict = {}
lang_dict["app"] = {}
lang_dict["app"]["button"] = ""
lang_dict["app"]["button.abort"] = ""
lang_dict["app"]["button.accept"] = "Hyväksy"
lang_dict["app"]["button.back"] = "Takaisin"
lang_dict["app"]["button.cancel"] = "Peruuta"
lang_dict["app"]["button.close"] = "Sulje"
lang_dict["app"]["button.confirm"] = "Varmista"
lang_dict["app"]["button.continue"] = "Jatka"
lang_dict["app"]["button.forward"] = "Eteenpäin"
lang_dict["app"]["button.ignore"] = "Ohita"
lang_dict["app"]["button.no"] = "Ei"
lang_dict["app"]["button.ok"] = "Ok"
lang_dict["app"]["button.quit"] = "Lopeta"
lang_dict["app"]["button.resume"] = "Jatka"
lang_dict["app"]["button.retry"] = "Yritä uudelleen"
lang_dict["app"]["button.yes"] = "Kyllä"
lang_dict["app"]["dir.error"] = ""
lang_dict["app"]["dir.error.access"] = ""
lang_dict["app"]["dir.error.change"] = ""
lang_dict["app"]["dir.error.copy"] = ""
lang_dict["app"]["dir.error.create"] = ""
lang_dict["app"]["dir.error.delete"] = ""
lang_dict["app"]["dir.error.modify"] = ""
lang_dict["app"]["dir.error.move"] = ""
lang_dict["app"]["dir.error.open"] = ""
lang_dict["app"]["dir.error.read"] = ""
lang_dict["app"]["dir.error.rename"] = ""
lang_dict["app"]["dir.few"] = ""
lang_dict["app"]["dir.many"] = ""
lang_dict["app"]["dir.one"] = ""
lang_dict["app"]["dir.other"] = ""
lang_dict["app"]["dir.two"] = ""
lang_dict["app"]["dir.zero"] = ""
lang_dict["app"]["drive.access"] = ""
lang_dict["app"]["drive.change"] = ""
lang_dict["app"]["drive.error"] = ""
lang_dict["app"]["drive.few"] = ""
lang_dict["app"]["drive.many"] = ""
lang_dict["app"]["drive.one"] = ""
lang_dict["app"]["drive.other"] = ""
lang_dict["app"]["drive.two"] = ""
lang_dict["app"]["drive.zero"] = ""
lang_dict["app"]["edit"] = ""
lang_dict["app"]["edit.clear"] = ""
lang_dict["app"]["edit.copy"] = ""
lang_dict["app"]["edit.cut"] = ""
lang_dict["app"]["edit.delete"] = ""
lang_dict["app"]["edit.duplicate"] = ""
lang_dict["app"]["edit.group"] = ""
lang_dict["app"]["edit.insert"] = ""
lang_dict["app"]["edit.merge"] = ""
lang_dict["app"]["edit.modify"] = ""
lang_dict["app"]["edit.move"] = ""
lang_dict["app"]["edit.paste"] = ""
lang_dict["app"]["edit.paste.special"] = ""
lang_dict["app"]["edit.redo"] = ""
lang_dict["app"]["edit.remove"] = ""
lang_dict["app"]["edit.split"] = ""
lang_dict["app"]["edit.undo"] = ""
lang_dict["app"]["edit.ungroup"] = ""
lang_dict["app"]["error"] = ""
lang_dict["app"]["error.audio"] = ""
lang_dict["app"]["error.connection"] = ""
lang_dict["app"]["error.critical"] = "Kriittinen virhe"
lang_dict["app"]["error.device"] = ""
lang_dict["app"]["error.fonts"] = ""
lang_dict["app"]["error.input"] = ""
lang_dict["app"]["error.runtime"] = "Ajoaikainen virhe"
lang_dict["app"]["error.shutdown"] = "Suljettu väärin"
lang_dict["app"]["error.system"] = "Järjestelmävirhe"
lang_dict["app"]["error.video"] = ""
lang_dict["app"]["file.error"] = ""
lang_dict["app"]["file.error.access"] = ""
lang_dict["app"]["file.error.copy"] = ""
lang_dict["app"]["file.error.create"] = ""
lang_dict["app"]["file.error.delete"] = ""
lang_dict["app"]["file.error.lock"] = ""
lang_dict["app"]["file.error.modify"] = ""
lang_dict["app"]["file.error.move"] = ""
lang_dict["app"]["file.error.open"] = ""
lang_dict["app"]["file.error.overwrite"] = ""
lang_dict["app"]["file.error.read"] = ""
lang_dict["app"]["file.error.rename"] = ""
lang_dict["app"]["file.error.save"] = ""
lang_dict["app"]["file.error.write"] = ""
lang_dict["app"]["file.few"] = ""
lang_dict["app"]["file.many"] = ""
lang_dict["app"]["file.one"] = ""
lang_dict["app"]["file.other"] = ""
lang_dict["app"]["file.two"] = ""
lang_dict["app"]["file.zero"] = ""
lang_dict["app"]["help"] = ""
lang_dict["app"]["help.about"] = ""
lang_dict["app"]["help.content"] = ""
lang_dict["app"]["help.copyright"] = ""
lang_dict["app"]["help.guide"] = ""
lang_dict["app"]["help.license"] = ""
lang_dict["app"]["help.manual"] = ""
lang_dict["app"]["help.privacy"] = ""
lang_dict["app"]["help.support"] = ""
lang_dict["app"]["io.close"] = ""
lang_dict["app"]["io.close.all"] = ""
lang_dict["app"]["io.compress"] = ""
lang_dict["app"]["io.export"] = ""
lang_dict["app"]["io.extract"] = ""
lang_dict["app"]["io.import"] = ""
lang_dict["app"]["io.new"] = ""
lang_dict["app"]["io.open"] = ""
lang_dict["app"]["io.open.recent"] = ""
lang_dict["app"]["io.overwrite"] = ""
lang_dict["app"]["io.preview"] = ""
lang_dict["app"]["io.rename"] = ""
lang_dict["app"]["io.revert"] = ""
lang_dict["app"]["io.save"] = ""
lang_dict["app"]["io.save.all"] = ""
lang_dict["app"]["io.save.as"] = ""
lang_dict["app"]["net"] = ""
lang_dict["app"]["net.attach"] = ""
lang_dict["app"]["net.connect"] = ""
lang_dict["app"]["net.disconnect"] = ""
lang_dict["app"]["net.download"] = ""
lang_dict["app"]["net.join"] = ""
lang_dict["app"]["net.leave"] = ""
lang_dict["app"]["net.offline"] = ""
lang_dict["app"]["net.online"] = ""
lang_dict["app"]["net.receive"] = ""
lang_dict["app"]["net.send"] = ""
lang_dict["app"]["net.share"] = ""
lang_dict["app"]["net.sync"] = ""
lang_dict["app"]["net.upload"] = ""
lang_dict["app"]["page.all"] = ""
lang_dict["app"]["page.all\\long"] = "Kaikki sivut"
lang_dict["app"]["page.choose"] = ""
lang_dict["app"]["page.choose\\long"] = "Valitse sivu"
lang_dict["app"]["page.count.few"] = ""
lang_dict["app"]["page.count.many"] = ""
lang_dict["app"]["page.count.one"] = "$1. sivu"
lang_dict["app"]["page.count.other"] = "$1 sivua"
lang_dict["app"]["page.count.two"] = ""
lang_dict["app"]["page.count.zero"] = ""
lang_dict["app"]["page.first"] = "Ensimmäinen sivu"
lang_dict["app"]["page.last"] = ""
lang_dict["app"]["page.last\\long"] = "Viimeinen sivu"
lang_dict["app"]["page.next"] = ""
lang_dict["app"]["page.next\\long"] = "Seuraava sivu"
lang_dict["app"]["page.number.few"] = ""
lang_dict["app"]["page.number.many"] = ""
lang_dict["app"]["page.number.one"] = "Sivu $1"
lang_dict["app"]["page.number.other"] = "Sivu $1"
lang_dict["app"]["page.number.two"] = ""
lang_dict["app"]["page.number.zero"] = ""
lang_dict["app"]["page.outof.few"] = ""
lang_dict["app"]["page.outof.many"] = ""
lang_dict["app"]["page.outof.one"] = "$1. sivu $2 sivusta"
lang_dict["app"]["page.outof.other"] = ""
lang_dict["app"]["page.outof.two"] = ""
lang_dict["app"]["page.outof.zero"] = ""
lang_dict["app"]["page.page.few"] = ""
lang_dict["app"]["page.page.many"] = ""
lang_dict["app"]["page.page.one"] = "Sivu"
lang_dict["app"]["page.page.other"] = "Sivut"
lang_dict["app"]["page.page.two"] = ""
lang_dict["app"]["page.page.zero"] = ""
lang_dict["app"]["page.previous"] = ""
lang_dict["app"]["page.previous\\long"] = "Edellinen sivu"
lang_dict["app"]["search"] = ""
lang_dict["app"]["search.find"] = ""
lang_dict["app"]["search.find.infiles"] = ""
lang_dict["app"]["search.find.next"] = ""
lang_dict["app"]["search.find.previous"] = ""
lang_dict["app"]["search.find.replace"] = ""
lang_dict["app"]["search.goto"] = ""
lang_dict["app"]["search.replace"] = ""
lang_dict["app"]["search.replace.files"] = ""
lang_dict["app"]["select"] = ""
lang_dict["app"]["select.add"] = ""
lang_dict["app"]["select.add.to"] = ""
lang_dict["app"]["select.deselect"] = ""
lang_dict["app"]["select.deselect.all"] = ""
lang_dict["app"]["select.invert"] = ""
lang_dict["app"]["select.invert\\long"] = ""
lang_dict["app"]["select.remove"] = ""
lang_dict["app"]["select.remove.from"] = ""
lang_dict["app"]["select.select"] = ""
lang_dict["app"]["select.select.all"] = ""
lang_dict["app"]["sort"] = ""
lang_dict["app"]["sort.asc"] = ""
lang_dict["app"]["sort.desc"] = ""
lang_dict["app"]["sort.mark"] = ""
lang_dict["app"]["sort.order"] = ""
lang_dict["app"]["sort.reverse"] = ""
lang_dict["app"]["sort.unmark"] = ""
lang_dict["app"]["title"] = ""
lang_dict["app"]["title.error"] = "Virhe"
lang_dict["app"]["title.message"] = "Viesti"
lang_dict["app"]["title.notify"] = "Huomio"
lang_dict["app"]["title.warning"] = "Varoitus"
lang_dict["app"]["total"] = ""
lang_dict["app"]["trans"] = ""
lang_dict["app"]["trans.flip"] = ""
lang_dict["app"]["trans.free"] = ""
lang_dict["app"]["trans.lower"] = ""
lang_dict["app"]["trans.mirror"] = ""
lang_dict["app"]["trans.raise"] = ""
lang_dict["app"]["trans.rotate"] = ""
lang_dict["app"]["trans.scale"] = ""
lang_dict["app"]["trans.skew"] = ""
lang_dict["app"]["trans.stretch"] = ""
lang_dict["app"]["trans.translate"] = ""
lang_dict["app"]["type.demo"] = "Demo"
lang_dict["app"]["type.demo.na"] = "Tämä ominaisuus ei ole saatavilla demoversiossa"
lang_dict["app"]["type.demo.over"] = "Pelin demoversio on päättynyt"
lang_dict["app"]["type.demo\\long"] = "Demoversio"
lang_dict["app"]["type.free"] = "Ilmainen pelata"
lang_dict["app"]["type.free\\long"] = "Ilmaispeluuversio"
lang_dict["app"]["type.freeware"] = "Ilmaistuote"
lang_dict["app"]["type.freeware\\long"] = "Ilmaisversio"
lang_dict["app"]["type.full"] = "Täysi"
lang_dict["app"]["type.full.buy"] = ""
lang_dict["app"]["type.full.buy\\long"] = "Haluaisitko hankkia täysversion?"
lang_dict["app"]["type.full.website"] = ""
lang_dict["app"]["type.full.website\\long"] = "Haluaisitko avata verkkosivun \\"$1\\"?"
lang_dict["app"]["type.full\\long"] = "Täysversio"
lang_dict["app"]["type.lite"] = "Kevyt"
lang_dict["app"]["type.lite.na"] = "Tämä ominaisuus ei ole saatavilla kevytversiossa"
lang_dict["app"]["type.lite.over"] = "Pelin kevytversio on päättynyt"
lang_dict["app"]["type.lite\\long"] = "Kevytversio"
lang_dict["app"]["type.shareware"] = "Shareware"
lang_dict["app"]["type.shareware\\long"] = "Shareware-versio"
lang_dict["app"]["type.vote"] = "Äänestä tätä peliä Steam Greenlight:ssa"
lang_dict["app"]["version"] = "Versio: $1"
lang_dict["app"]["version.alpha"] = "Alpha-versio"
lang_dict["app"]["version.beta"] = "Beta-versio"
lang_dict["app"]["version.build"] = "Version tyyppi"
lang_dict["app"]["version.proto"] = "Prototyyppi"
lang_dict["app"]["version.release"] = "Julkaisuversio"
lang_dict["app"]["view"] = ""
lang_dict["app"]["view.camera"] = ""
lang_dict["app"]["view.grid"] = ""
lang_dict["app"]["view.guides"] = ""
lang_dict["app"]["view.refresh"] = ""
lang_dict["app"]["view.snap"] = ""
lang_dict["app"]["view.zoom"] = ""
lang_dict["app"]["view.zoom.in"] = ""
lang_dict["app"]["view.zoom.out"] = ""
lang_dict["app"]["view.zoom.reset"] = ""
lang_dict["astro"] = {}
lang_dict["astro"]["And"] = "Andromeda"
lang_dict["astro"]["Ant"] = "Ilmapumppu"
lang_dict["astro"]["Aps"] = "Paratiisilintu"
lang_dict["astro"]["Aql"] = "Kotka"
lang_dict["astro"]["Aqr"] = "Vesimies"
lang_dict["astro"]["Ara"] = "Alttari"
lang_dict["astro"]["Ari"] = "Oinas"
lang_dict["astro"]["Aur"] = "Ajomies"
lang_dict["astro"]["Boo"] = "Karhunvartija"
lang_dict["astro"]["CMa"] = "Iso koira"
lang_dict["astro"]["CMi"] = "Pieni koira"
lang_dict["astro"]["CVn"] = "Ajokoirat"
lang_dict["astro"]["Cae"] = "Veistotaltta"
lang_dict["astro"]["Cam"] = "Kirahvi"
lang_dict["astro"]["Cap"] = "Kauris"
lang_dict["astro"]["Car"] = "Köli"
lang_dict["astro"]["Cas"] = "Kassiopeia"
lang_dict["astro"]["Cen"] = "Kentauri"
lang_dict["astro"]["Cep"] = "Kefeus"
lang_dict["astro"]["Cet"] = "Valaskala"
lang_dict["astro"]["Cha"] = "Kameleontti"
lang_dict["astro"]["Cir"] = "Harppi"
lang_dict["astro"]["Cnc"] = "Krapu"
lang_dict["astro"]["Col"] = "Kyyhkynen"
lang_dict["astro"]["Com"] = "Bereniken hiukset"
lang_dict["astro"]["CrA"] = "Etelän kruunu"
lang_dict["astro"]["CrB"] = "Pohjan kruunu"
lang_dict["astro"]["Crt"] = "Malja"
lang_dict["astro"]["Cru"] = "Etelän risti"
lang_dict["astro"]["Crv"] = "Korppi"
lang_dict["astro"]["Cyg"] = "Joutsen"
lang_dict["astro"]["Del"] = "Delfiini"
lang_dict["astro"]["Dor"] = "Kultakala"
lang_dict["astro"]["Dra"] = "Lohikäärme"
lang_dict["astro"]["Equ"] = "Pieni hevonen"
lang_dict["astro"]["Eri"] = "Eridanus"
lang_dict["astro"]["For"] = "Sulatusuuni"
lang_dict["astro"]["Gem"] = "Kaksoset"
lang_dict["astro"]["Gru"] = "Kurki"
lang_dict["astro"]["Her"] = "Herkules"
lang_dict["astro"]["Hor"] = "Heilurikello"
lang_dict["astro"]["Hya"] = "Vesikäärme"
lang_dict["astro"]["Hyi"] = "Etelän vesikäärme"
lang_dict["astro"]["Ind"] = "Intiaani"
lang_dict["astro"]["LMi"] = "Pieni leijona"
lang_dict["astro"]["Lac"] = "Sisilisko"
lang_dict["astro"]["Leo"] = "Leijona"
lang_dict["astro"]["Lep"] = "Jänis"
lang_dict["astro"]["Lib"] = "Vaaka"
lang_dict["astro"]["Lup"] = "Susi"
lang_dict["astro"]["Lyn"] = "Ilves"
lang_dict["astro"]["Lyr"] = "Lyyra"
lang_dict["astro"]["Men"] = "Pöytävuori"
lang_dict["astro"]["Mic"] = "Mikroskooppi"
lang_dict["astro"]["Mon"] = "Yksisarvinen"
lang_dict["astro"]["Mus"] = "Kärpänen"
lang_dict["astro"]["Nor"] = "Kulmaviivoitin"
lang_dict["astro"]["Oct"] = "Oktantti"
lang_dict["astro"]["Oph"] = "Käärmeen-kantaja"
lang_dict["astro"]["Ori"] = "Orion"
lang_dict["astro"]["Pav"] = "Riikinkukko"
lang_dict["astro"]["Peg"] = "Pegasus"
lang_dict["astro"]["Per"] = "Perseus"
lang_dict["astro"]["Phe"] = "Feeniks"
lang_dict["astro"]["Pic"] = "Maalari"
lang_dict["astro"]["PsA"] = "Etelän kala"
lang_dict["astro"]["Psc"] = "Kalat"
lang_dict["astro"]["Pup"] = "Peräkeula"
lang_dict["astro"]["Pyx"] = "Kompassi"
lang_dict["astro"]["Ret"] = "Verkko"
lang_dict["astro"]["Scl"] = "Kuvan-veistäjä"
lang_dict["astro"]["Sco"] = "Skorpioni"
lang_dict["astro"]["Sct"] = "Kilpi"
lang_dict["astro"]["Ser"] = "Käärme"
lang_dict["astro"]["Sex"] = "Sekstantti"
lang_dict["astro"]["Sge"] = "Nuoli"
lang_dict["astro"]["Sgr"] = "Jousimies"
lang_dict["astro"]["Tau"] = "Härkä"
lang_dict["astro"]["Tel"] = "Kaukoputki"
lang_dict["astro"]["TrA"] = "Etelän kolmio"
lang_dict["astro"]["Tri"] = "Kolmio"
lang_dict["astro"]["Tuc"] = "Tukaani"
lang_dict["astro"]["UMa"] = "Iso karhu"
lang_dict["astro"]["UMi"] = "Pieni karhu"
lang_dict["astro"]["Vel"] = "Purje"
lang_dict["astro"]["Vir"] = "Neitsyt"
lang_dict["astro"]["Vol"] = "Lentokala"
lang_dict["astro"]["Vul"] = "Kettu"
lang_dict["astro"]["ceres"] = "Ceres"
lang_dict["astro"]["chiron"] = "Chiron"
lang_dict["astro"]["constellation"] = "Tähdistö"
lang_dict["astro"]["deimos"] = "Deimos"
lang_dict["astro"]["eris"] = "Eris"
lang_dict["astro"]["haumea"] = ""
lang_dict["astro"]["juno"] = "Juno"
lang_dict["astro"]["makemake"] = ""
lang_dict["astro"]["pallas"] = "Pallas"
lang_dict["astro"]["phobos"] = "Phobos"
lang_dict["astro"]["total"] = ""
lang_dict["astro"]["vesta"] = "Vesta"
lang_dict["audio"] = {}
lang_dict["audio"]["audio"] = "Ääni"
lang_dict["audio"]["audio.advanced"] = ""
lang_dict["audio"]["audio.advanced.change"] = ""
lang_dict["audio"]["audio.advanced\\long"] = ""
lang_dict["audio"]["audio.card"] = "Äänikortti"
lang_dict["audio"]["audio.change"] = "Vaihda ääniasetuksia"
lang_dict["audio"]["audio.error"] = ""
lang_dict["audio"]["audio.error.init"] = ""
lang_dict["audio"]["audio.error.mode"] = ""
lang_dict["audio"]["audio.error.mode\\long"] = ""
lang_dict["audio"]["audio.off"] = ""
lang_dict["audio"]["audio.on"] = ""
lang_dict["audio"]["audio.settings"] = "Ääniasetukset"
lang_dict["audio"]["audio.turn.off"] = ""
lang_dict["audio"]["audio.turn.on"] = ""
lang_dict["audio"]["audio.warn.fatal"] = ""
lang_dict["audio"]["audio.warn.nonfatal"] = ""
lang_dict["audio"]["bitdepth"] = "Bittisyvyys"
lang_dict["audio"]["bitdepth.audio"] = "Äänen bittisyvyys"
lang_dict["audio"]["bitdepth.bits.few"] = ""
lang_dict["audio"]["bitdepth.bits.many"] = ""
lang_dict["audio"]["bitdepth.bits.one"] = ""
lang_dict["audio"]["bitdepth.bits.other"] = "$1 bittiä"
lang_dict["audio"]["bitdepth.bits.two"] = ""
lang_dict["audio"]["bitdepth.bits.zero"] = ""
lang_dict["audio"]["bitdepth.change"] = "Vaihda bittisyvyyttä"
lang_dict["audio"]["bitdepth.choose"] = "Valitse bittisyvyys"
lang_dict["audio"]["bitdepth.desc"] = ""
lang_dict["audio"]["bitdepth.func"] = ""
lang_dict["audio"]["channels"] = "Kanavat"
lang_dict["audio"]["channels.audio"] = "Äänikanavat"
lang_dict["audio"]["channels.change"] = "Vaihda äänikanavien määrää"
lang_dict["audio"]["channels.choose"] = "Valitse äänikanavien määrä"
lang_dict["audio"]["channels.mono"] = "Mono"
lang_dict["audio"]["channels.stereo"] = "Stereo"
lang_dict["audio"]["channels.surround"] = "Surround"
lang_dict["audio"]["channels.surround.51"] = "5.1 surround"
lang_dict["audio"]["channels.surround.71"] = "7.1 surround"
lang_dict["audio"]["controls.backward"] = ""
lang_dict["audio"]["controls.ctrack"] = ""
lang_dict["audio"]["controls.eject"] = ""
lang_dict["audio"]["controls.fforward"] = ""
lang_dict["audio"]["controls.forward"] = ""
lang_dict["audio"]["controls.loop"] = ""
lang_dict["audio"]["controls.pause"] = ""
lang_dict["audio"]["controls.play"] = ""
lang_dict["audio"]["controls.playlist"] = ""
lang_dict["audio"]["controls.random"] = ""
lang_dict["audio"]["controls.rec"] = ""
lang_dict["audio"]["controls.repeat"] = ""
lang_dict["audio"]["controls.rewind"] = "Taaksepäin"
lang_dict["audio"]["controls.stop"] = ""
lang_dict["audio"]["controls.track"] = ""
lang_dict["audio"]["music"] = "Musiikki"
lang_dict["audio"]["music.ambience"] = "Musiikki ja taustaäänet"
lang_dict["audio"]["music.change"] = "Säädä musiikin voimakkuutta"
lang_dict["audio"]["music.off"] = ""
lang_dict["audio"]["music.on"] = ""
lang_dict["audio"]["music.turn.off"] = "Ota musiikki pois päältä"
lang_dict["audio"]["music.turn.on"] = "Laita musiikki päälle"
lang_dict["audio"]["music.volume"] = "Musiikin voimakkuus"
lang_dict["audio"]["sampling"] = "Näytteenottotaajuus"
lang_dict["audio"]["sampling.change"] = "Vaihda näytteenottotaajuutta"
lang_dict["audio"]["sampling.choose"] = "Valitse näytteenottotaajuus"
lang_dict["audio"]["sampling.desc"] = ""
lang_dict["audio"]["sampling.freq"] = "Näytteenottotaajuus"
lang_dict["audio"]["sampling.func"] = ""
lang_dict["audio"]["sampling.hertz.few"] = ""
lang_dict["audio"]["sampling.hertz.one"] = ""
lang_dict["audio"]["sampling.hertz.other"] = ""
lang_dict["audio"]["sampling.hertz.two"] = ""
lang_dict["audio"]["sampling.hertz.zero"] = ""
lang_dict["audio"]["sampling.hz"] = "$1 Hz"
lang_dict["audio"]["sampling.khertz.few"] = ""
lang_dict["audio"]["sampling.khertz.many"] = ""
lang_dict["audio"]["sampling.khertz.one"] = ""
lang_dict["audio"]["sampling.khertz.other"] = ""
lang_dict["audio"]["sampling.khertz.two"] = ""
lang_dict["audio"]["sampling.khertz.zero"] = ""
lang_dict["audio"]["sampling.khz"] = ""
lang_dict["audio"]["sampling.ratex"] = "Taajuus: $1"
lang_dict["audio"]["sapmling.hertz.many"] = ""
lang_dict["audio"]["sounds"] = "Äänet"
lang_dict["audio"]["sounds.change"] = "Säädä ääniefektien voimakkuutta"
lang_dict["audio"]["sounds.effects"] = "Ääniefektit"
lang_dict["audio"]["sounds.off"] = ""
lang_dict["audio"]["sounds.on"] = ""
lang_dict["audio"]["sounds.turn.off"] = "Ota ääniefektit pois päältä"
lang_dict["audio"]["sounds.turn.on"] = "Laita ääniefektit päälle"
lang_dict["audio"]["sounds.volume"] = "Ääniefektien voimakkuus"
lang_dict["audio"]["total"] = ""
lang_dict["audio"]["volume"] = "Äänenvoimakkuus"
lang_dict["audio"]["volume.change"] = "Säädä äänenvoimakkuutta"
lang_dict["audio"]["volume.decrease"] = "Vähennä äänenvoimakkuutta"
lang_dict["audio"]["volume.increase"] = "Lisää äänenvoimakkuutta"
lang_dict["audio"]["volume.levels"] = "Äänenvoimakkuustasot"
lang_dict["audio"]["volume.mute"] = "Päällä"
lang_dict["audio"]["volume.muted"] = "Pois"
lang_dict["audio"]["volume.off"] = "Ota ääni käyttöön"
lang_dict["audio"]["volume.on"] = "Poista ääni käytöstä"
lang_dict["audio"]["volume.unmute"] = ""
lang_dict["audio"]["volume.unmuted"] = ""
lang_dict["chess"] = {}
lang_dict["chess"]["board"] = "Lauta"
lang_dict["chess"]["board.style"] = "Tyyli"
lang_dict["chess"]["board.style.choose"] = "Valitse laudan tyyli"
lang_dict["chess"]["board.style\\long"] = "Laudan tyyli"
lang_dict["chess"]["captured"] = "Vangittu"
lang_dict["chess"]["captured\\full"] = "Vangittuja nappuloita"
lang_dict["chess"]["castle"] = "Tornitus"
lang_dict["chess"]["check"] = ""
lang_dict["chess"]["checkmate"] = "Shakkimatti"
lang_dict["chess"]["color"] = "Väri"
lang_dict["chess"]["color\\full"] = "nappulan väri"
lang_dict["chess"]["delete"] = "Poista"
lang_dict["chess"]["delete\\full"] = "poista nappula"
lang_dict["chess"]["enpassant"] = ""
lang_dict["chess"]["error.check"] = "Sijainti alkaa shakkitilanteesta"
lang_dict["chess"]["error.position"] = "laiton sijoitus"
lang_dict["chess"]["error.toomany"] = "liikaa nappuloita"
lang_dict["chess"]["fiftymoves"] = "Viidenkymmenen siirron sääntö"
lang_dict["chess"]["flip"] = "Käännä lauta"
lang_dict["chess"]["goto"] = "Siirry vuoroon"
lang_dict["chess"]["high1"] = "edellinen"
lang_dict["chess"]["high1\\long"] = "edellinen siirto"
lang_dict["chess"]["high2"] = "saatavilla"
lang_dict["chess"]["high2\\long"] = "saatavilla olevat siirrot"
lang_dict["chess"]["high3"] = "edellinen ja saatavilla"
lang_dict["chess"]["high3\\long"] = "edellinen ja saatavilla olevat siirrot"
lang_dict["chess"]["high4"] = "pois päältä"
lang_dict["chess"]["highlight"] = "Korosta"
lang_dict["chess"]["highlightd"] = "Korosta siirtoja"
lang_dict["chess"]["impossible"] = "Shakkimatti on mahdoton"
lang_dict["chess"]["invalid"] = "Laiton siirto"
lang_dict["chess"]["load"] = "Lataa tietokanta"
lang_dict["chess"]["loadd"] = "Katso klassisia otteluita"
lang_dict["chess"]["move"] = "Siirrä"
lang_dict["chess"]["move\\full"] = "liikuta nappulaa"
lang_dict["chess"]["moves"] = "Vuorot"
lang_dict["chess"]["moves1"] = "Takaisinpäin"
lang_dict["chess"]["moves2"] = "Edellinen"
lang_dict["chess"]["moves3"] = "Seuraava"
lang_dict["chess"]["moves4"] = "Eteenpäin"
lang_dict["chess"]["movesd"] = "Vuoronavigaatio"
lang_dict["chess"]["movesl"] = "Vuorolista"
lang_dict["chess"]["nomoves"] = "Ei laillisia siirtoja"
lang_dict["chess"]["opening"] = "Avaus"
lang_dict["chess"]["opponent"] = "Vastustaja"
lang_dict["chess"]["pgn.black"] = "Musta"
lang_dict["chess"]["pgn.date"] = "Aika"
lang_dict["chess"]["pgn.event"] = "Tapahtuma"
lang_dict["chess"]["pgn.match"] = "Ottelu"
lang_dict["chess"]["pgn.result"] = "Tulos"
lang_dict["chess"]["pgn.round"] = "Siirto"
lang_dict["chess"]["pgn.site"] = "Paikka"
lang_dict["chess"]["pgn.white"] = "Valkoinen"
lang_dict["chess"]["player1"] = "Ihminen"
lang_dict["chess"]["player2"] = "Tietokone"
lang_dict["chess"]["repetition"] = "Kolmas toisto"
lang_dict["chess"]["result.black"] = "Musta voitti"
lang_dict["chess"]["result.draw"] = "Tasapeli"
lang_dict["chess"]["result.none"] = "Ei tulosta"
lang_dict["chess"]["result.white"] = "Valkoinen voitti"
lang_dict["chess"]["setup"] = "Asetus"
lang_dict["chess"]["setup\\full"] = "Asettele pelilauta"
lang_dict["chess"]["setup\\short"] = "Asettele pelilauta"
lang_dict["chess"]["side"] = "Valitse puoli"
lang_dict["chess"]["side1"] = "valkoinen"
lang_dict["chess"]["side2"] = "musta"
lang_dict["chess"]["side3"] = "ei kumpikaan"
lang_dict["chess"]["siden"] = "Puoli"
lang_dict["chess"]["spawn"] = "Lisää"
lang_dict["chess"]["spawn\\full"] = "lisää nappula"
lang_dict["chess"]["stalemate"] = "Kyllästyminen"
lang_dict["chess"]["switch"] = "Vaihda puolta"
lang_dict["chess"]["total"] = ""
lang_dict["gameplay"] = {}
lang_dict["gameplay"]["action.few"] = ""
lang_dict["gameplay"]["action.many"] = ""
lang_dict["gameplay"]["action.one"] = "Toiminto"
lang_dict["gameplay"]["action.other"] = ""
lang_dict["gameplay"]["action.two"] = ""
lang_dict["gameplay"]["action.zero"] = ""
lang_dict["gameplay"]["attack"] = "Hyökkää"
lang_dict["gameplay"]["bomb"] = "Pommi"
lang_dict["gameplay"]["cancel"] = "Peru"
lang_dict["gameplay"]["command"] = "Komento"
lang_dict["gameplay"]["command.other"] = ""
lang_dict["gameplay"]["difficulty"] = "Haastavuus"
lang_dict["gameplay"]["difficulty.change"] = "Vaihda haastavuustaso"
lang_dict["gameplay"]["difficulty.easy"] = "Helppo"
lang_dict["gameplay"]["difficulty.hard"] = "Vaikea"
lang_dict["gameplay"]["difficulty.lunatic"] = "Sekopäinen"
lang_dict["gameplay"]["difficulty.maniac"] = "Uhkarohkea"
lang_dict["gameplay"]["difficulty.veryeasy"] = "Tosi helppo"
lang_dict["gameplay"]["difficulty.veryhard"] = "Tosi vaikea"
lang_dict["gameplay"]["difficulty\\long"] = "Haastavuustaso"
lang_dict["gameplay"]["difficutly.choose"] = "Valitse haastavuus"
lang_dict["gameplay"]["difficutly.normal"] = "Normaali"
lang_dict["gameplay"]["down"] = "Alas"
lang_dict["gameplay"]["focus"] = "Keskity"
lang_dict["gameplay"]["help"] = "Apua"
lang_dict["gameplay"]["hint"] = "Vinkki"
lang_dict["gameplay"]["hints.disable"] = ""
lang_dict["gameplay"]["hints.disabled"] = ""
lang_dict["gameplay"]["hints.enable"] = ""
lang_dict["gameplay"]["hints.enabled"] = ""
lang_dict["gameplay"]["hints.hide.one"] = ""
lang_dict["gameplay"]["hints.hide.other"] = ""
lang_dict["gameplay"]["hints.one"] = ""
lang_dict["gameplay"]["hints.other"] = ""
lang_dict["gameplay"]["hints.show.one"] = ""
lang_dict["gameplay"]["hints.show.other"] = ""
lang_dict["gameplay"]["hit"] = "Lyö"
lang_dict["gameplay"]["jump"] = "Hyppää"
lang_dict["gameplay"]["left"] = "Vasemmalle"
lang_dict["gameplay"]["mdown"] = "Liiku alas"
lang_dict["gameplay"]["mleft"] = "Liiku vasemmalle"
lang_dict["gameplay"]["mode.choose"] = "Valitse pelityyli"
lang_dict["gameplay"]["mode.few"] = ""
lang_dict["gameplay"]["mode.many"] = ""
lang_dict["gameplay"]["mode.one"] = "Pelityyli"
lang_dict["gameplay"]["mode.other"] = ""
lang_dict["gameplay"]["mode.sandbox"] = "Hiekkalaatikko"
lang_dict["gameplay"]["mode.sandbox.desc"] = "Pelaa ilman erityistä päämäärää"
lang_dict["gameplay"]["mode.score"] = "Pistehaaste"
lang_dict["gameplay"]["mode.score.desc"] = "Kerää mahdollisimman monta pistettä"
lang_dict["gameplay"]["mode.survive"] = "Selvityminen"
lang_dict["gameplay"]["mode.survive.desc"] = "Koeta selvitä mahdollisimman pitkään"
lang_dict["gameplay"]["mode.time"] = "Aikahaaste"
lang_dict["gameplay"]["mode.time.desc"] = "Suorita mahdollisimman nopeasti"
lang_dict["gameplay"]["mode.two"] = ""
lang_dict["gameplay"]["mode.zero"] = ""
lang_dict["gameplay"]["mright"] = "Liiku oikealle"
lang_dict["gameplay"]["mup"] = "Liiku ylös"
lang_dict["gameplay"]["pause"] = "Pysäytä"
lang_dict["gameplay"]["reset"] = "Palauta"
lang_dict["gameplay"]["right"] = "Oikealle"
lang_dict["gameplay"]["selsect"] = "Valitse"
lang_dict["gameplay"]["shoot"] = "Ammu"
lang_dict["gameplay"]["skill"] = "Osaaminen"
lang_dict["gameplay"]["skill.advanced"] = "Edistynyt"
lang_dict["gameplay"]["skill.average"] = "Keskiverto"
lang_dict["gameplay"]["skill.beginner"] = "Aloittelija"
lang_dict["gameplay"]["skill.change"] = "Muuta osaamistasoa"
lang_dict["gameplay"]["skill.choose"] = "Valitse osaamistaso"
lang_dict["gameplay"]["skill.expert"] = "Taitava"
lang_dict["gameplay"]["skill.novice"] = "Noviisi"
lang_dict["gameplay"]["skill\\long"] = "Osaamistaso"
lang_dict["gameplay"]["start"] = "Aloita"
lang_dict["gameplay"]["total"] = ""
lang_dict["gameplay"]["up"] = "Ylös"
lang_dict["input"] = {}
lang_dict["input"]["axis.dpad"] = ""
lang_dict["input"]["axis.fifth"] = ""
lang_dict["input"]["axis.fourth"] = ""
lang_dict["input"]["axis.fourth\\long"] = ""
lang_dict["input"]["axis.horizontal"] = ""
lang_dict["input"]["axis.horizontal\\long"] = ""
lang_dict["input"]["axis.pov"] = ""
lang_dict["input"]["axis.sixth"] = ""
lang_dict["input"]["axis.third"] = ""
lang_dict["input"]["axis.third\\long"] = ""
lang_dict["input"]["axis.vertical"] = ""
lang_dict["input"]["axis.vertical\\long"] = ""
lang_dict["input"]["button"] = "Nappula"
lang_dict["input"]["button.analog"] = ""
lang_dict["input"]["button.back"] = ""
lang_dict["input"]["button.buttonx"] = "Nappula $1"
lang_dict["input"]["button.home"] = ""
lang_dict["input"]["button.lanalog"] = ""
lang_dict["input"]["button.lbumper"] = ""
lang_dict["input"]["button.lshoulder"] = ""
lang_dict["input"]["button.lstick"] = ""
lang_dict["input"]["button.ltrigger"] = ""
lang_dict["input"]["button.ouya1"] = "O"
lang_dict["input"]["button.ouya2"] = "A"
lang_dict["input"]["button.ouya3"] = "U"
lang_dict["input"]["button.ouya4"] = "Y"
lang_dict["input"]["button.press"] = "Paina nappulaa"
lang_dict["input"]["button.press.any"] = "Paina mitä vain nappulaa"
lang_dict["input"]["button.press.buttonx"] = "Paina nappulaa $1"
lang_dict["input"]["button.press.on"] = "Paina nappulaa $1:ssä"
lang_dict["input"]["button.press.xbutton"] = ""
lang_dict["input"]["button.ps1"] = "Neliö"
lang_dict["input"]["button.ps2"] = "Cross"
lang_dict["input"]["button.ps3"] = "Ympyrä"
lang_dict["input"]["button.ps4"] = "Kolmio"
lang_dict["input"]["button.ranalog"] = ""
lang_dict["input"]["button.rbumper"] = ""
lang_dict["input"]["button.release"] = "Päästä nappula $1"
lang_dict["input"]["button.release.all"] = "Päästä kaikki nappulat"
lang_dict["input"]["button.release.all\\long"] = "Älä paina mitään nappulaa $1:ssä"
lang_dict["input"]["button.rshoulder"] = ""
lang_dict["input"]["button.rstick"] = ""
lang_dict["input"]["button.rtrigger"] = ""
lang_dict["input"]["button.select"] = ""
lang_dict["input"]["button.start"] = ""
lang_dict["input"]["button.trigger"] = ""
lang_dict["input"]["button.xbox1"] = "A"
lang_dict["input"]["button.xbox2"] = "B"
lang_dict["input"]["button.xbox3"] = "X"
lang_dict["input"]["button.xbox4"] = "Y"
lang_dict["input"]["buttons"] = ""
lang_dict["input"]["controls"] = "Ohjaus"
lang_dict["input"]["controls.change"] = "Muuta pelin ohjausta"
lang_dict["input"]["controls.devicex"] = "$1:n ohjaus"
lang_dict["input"]["controls.game"] = "Pelin ohjaus"
lang_dict["input"]["controls.reset"] = "Resetoi ohjausasetukset"
lang_dict["input"]["controls.reset.confirm"] = "Haluaisitko resetoida kaikki pelin ohjausasetukset?"
lang_dict["input"]["controls.reset.confirm\\long"] = ""
lang_dict["input"]["input"] = "Ohjaus"
lang_dict["input"]["input.change"] = "Muuta ohjausasetuksia"
lang_dict["input"]["input.choose"] = "Valitse ohjauslaita"
lang_dict["input"]["input.devicex"] = "Laite: $1"
lang_dict["input"]["input.settings"] = "Ohjausasetukset"
lang_dict["input"]["joystick"] = "Ilotikku"
lang_dict["input"]["joystick.assign"] = "Aseta nappula \\"$1\\":lle"
lang_dict["input"]["joystick.assign.none"] = "Nappuloita ei asetettu"
lang_dict["input"]["joystick.assign.taken"] = "Nappula on jo asetettu"
lang_dict["input"]["joystick.calibration"] = "Kalibrointi"
lang_dict["input"]["joystick.calibration\\long"] = "Ilotikun kalibrointi"
lang_dict["input"]["joystick.change"] = "Vaihda ilotikun asetuksia"
lang_dict["input"]["joystick.changem"] = "Vaihda nappula-asetuksia"
lang_dict["input"]["joystick.changen"] = "Säädä ilotikun nolla-aluetta"
lang_dict["input"]["joystick.changes"] = "Säädä ilotikun herkkyyttä"
lang_dict["input"]["joystick.controls"] = "Ilotikun asetukset"
lang_dict["input"]["joystick.error"] = ""
lang_dict["input"]["joystick.error.none"] = "Ilotikkuja ei löydy"
lang_dict["input"]["joystick.error.none\\long"] = ""
lang_dict["input"]["joystick.joystickx"] = "Ilotikku $1"
lang_dict["input"]["joystick.map"] = "Nappula-asetukset"
lang_dict["input"]["joystick.mapx"] = "$1:n nappula-asetukset"
lang_dict["input"]["joystick.null"] = "Nolla-alue"
lang_dict["input"]["joystick.null\\long"] = "Ilotikun nolla-alue"
lang_dict["input"]["joystick.sensitivity"] = "Ilotikun herkkyys"
lang_dict["input"]["key"] = "Näppäinkontrollit"
lang_dict["input"]["key.alt"] = ""
lang_dict["input"]["key.arrows"] = ""
lang_dict["input"]["key.back"] = ""
lang_dict["input"]["key.ctrl"] = ""
lang_dict["input"]["key.down"] = "Alanuoli"
lang_dict["input"]["key.enter"] = ""
lang_dict["input"]["key.escape"] = ""
lang_dict["input"]["key.keys"] = ""
lang_dict["input"]["key.keyx"] = "$1 näppäin"
lang_dict["input"]["key.lalt"] = ""
lang_dict["input"]["key.lctrl"] = ""
lang_dict["input"]["key.left"] = "Vasen nuoli"
lang_dict["input"]["key.lshift"] = ""
lang_dict["input"]["key.ralt"] = ""
lang_dict["input"]["key.rctrl"] = ""
lang_dict["input"]["key.right"] = "Oikea nuoli"
lang_dict["input"]["key.rshift"] = ""
lang_dict["input"]["key.shift"] = ""
lang_dict["input"]["key.space"] = "Välilyönti"
lang_dict["input"]["key.tab"] = ""
lang_dict["input"]["key.up"] = "Ylänuoli"
lang_dict["input"]["keyboard"] = "Näppäimistö"
lang_dict["input"]["keyboard.assign"] = "Aseta näppäin \\"$1\\":lle"
lang_dict["input"]["keyboard.assign.none"] = "Näppäimiä ei asetettu"
lang_dict["input"]["keyboard.assign.taken"] = "Näppäin on jo asetettu"
lang_dict["input"]["keyboard.change"] = "Muuta näppäinkontrolleja"
lang_dict["input"]["keyboard.changem"] = "Vaihda näppäinasetuksia"
lang_dict["input"]["keyboard.controls"] = "Näppäinkontrollit"
lang_dict["input"]["keyboard.error"] = ""
lang_dict["input"]["keyboard.error.none"] = "Näppäimistöä ei löydy"
lang_dict["input"]["keyboard.error.none\\long"] = ""
lang_dict["input"]["keyboard.map"] = "Näppäinasetukset"
lang_dict["input"]["keyboard.mapx"] = "$1:n näppäinasetukset"
lang_dict["input"]["keyboard.press.akey"] = "Paina näppäintä"
lang_dict["input"]["keyboard.press.any"] = "Paina mitä vain näppäintä"
lang_dict["input"]["keyboard.press.key"] = "Paina $1-näppäintä"
lang_dict["input"]["keyboard.release.all"] = "Älä paina mitään näppäintä"
lang_dict["input"]["keyboard.release.key"] = "Vapauta $1-näppäin"
lang_dict["input"]["mouse"] = "Hiiri"
lang_dict["input"]["mouse.buttons"] = "Hiiren nappulat"
lang_dict["input"]["mouse.error"] = ""
lang_dict["input"]["mouse.error.none"] = "Hiirtä ei löydy"
lang_dict["input"]["mouse.error.none\\long"] = ""
lang_dict["input"]["mouse.lmb"] = "Vasen hiiren nappi"
lang_dict["input"]["mouse.mmb"] = "Hiiren keskinappi"
lang_dict["input"]["mouse.press.abutton"] = "Paina hiiren nappia"
lang_dict["input"]["mouse.press.any"] = "Paina mitä vain hiiren nappua"
lang_dict["input"]["mouse.press.buttonx"] = "Paina $1:ä"
lang_dict["input"]["mouse.rmb"] = "Oikea hiiren nappi"
lang_dict["input"]["mouse.wheel"] = "Hiiren rulla"
lang_dict["input"]["total"] = ""
lang_dict["input"]["touch"] = "Kosketusnäyttö"
lang_dict["lang"] = {}
lang_dict["lang"]["error"] = "Kielivirhe"
lang_dict["lang"]["error.missing"] = ""
lang_dict["lang"]["error.na"] = "Kieli ei ole saatavilla"
lang_dict["lang"]["error.na.in"] = "Ei ole saatavilla $1"
lang_dict["lang"]["error.na.in\\long"] = "Tätä peliä ei ole saatavilla $1"
lang_dict["lang"]["error.na\\long"] = "Valittu kieli ei ole saatavilla"
lang_dict["lang"]["lang"] = "Kieli"
lang_dict["lang"]["lang.change"] = "Vaihda kieli"
lang_dict["lang"]["lang.choose"] = "Valitse kieli"
lang_dict["lang"]["lang.current"] = "Valittu kieli"
lang_dict["lang"]["name"] = "Suomi"
lang_dict["lang"]["name.english"] = "Finnish"
lang_dict["math"] = {}
lang_dict["math"]["add"] = "Yhteenlasku"
lang_dict["math"]["add0"] = ""
lang_dict["math"]["add1"] = ""
lang_dict["math"]["add2"] = ""
lang_dict["math"]["add3"] = ""
lang_dict["math"]["addv"] = ""
lang_dict["math"]["algebra"] = "Algebra"
lang_dict["math"]["angle"] = ""
lang_dict["math"]["angle.acute"] = ""
lang_dict["math"]["angle.obtuse"] = ""
lang_dict["math"]["angle.right"] = ""
lang_dict["math"]["arithmetic"] = "Aritmetiikka"
lang_dict["math"]["circ"] = ""
lang_dict["math"]["circle"] = "Ympyrä"
lang_dict["math"]["circle1"] = ""
lang_dict["math"]["circle2"] = ""
lang_dict["math"]["cos"] = "Kosini"
lang_dict["math"]["cot"] = ""
lang_dict["math"]["csc"] = ""
lang_dict["math"]["dart"] = ""
lang_dict["math"]["degree.few"] = ""
lang_dict["math"]["degree.many"] = ""
lang_dict["math"]["degree.one"] = ""
lang_dict["math"]["degree.other"] = ""
lang_dict["math"]["degree.two"] = ""
lang_dict["math"]["degree.zero"] = ""
lang_dict["math"]["div"] = "Jakolasku"
lang_dict["math"]["div0"] = ""
lang_dict["math"]["div1"] = ""
lang_dict["math"]["div2"] = ""
lang_dict["math"]["div3"] = ""
lang_dict["math"]["divv"] = ""
lang_dict["math"]["ellipse"] = ""
lang_dict["math"]["expo"] = ""
lang_dict["math"]["expo0"] = ""
lang_dict["math"]["expo1"] = ""
lang_dict["math"]["expo2"] = ""
lang_dict["math"]["expo3"] = ""
lang_dict["math"]["expov"] = ""
lang_dict["math"]["geometry"] = "Geometria"
lang_dict["math"]["heptagon"] = ""
lang_dict["math"]["hexagon"] = ""
lang_dict["math"]["kite"] = ""
lang_dict["math"]["log"] = ""
lang_dict["math"]["log0"] = ""
lang_dict["math"]["log1"] = ""
lang_dict["math"]["log2"] = ""
lang_dict["math"]["log3"] = ""
lang_dict["math"]["logb"] = ""
lang_dict["math"]["logv"] = ""
lang_dict["math"]["math"] = "Matematiikka"
lang_dict["math"]["mod"] = ""
lang_dict["math"]["mod0"] = ""
lang_dict["math"]["mod1"] = ""
lang_dict["math"]["mod2"] = ""
lang_dict["math"]["mod3"] = ""
lang_dict["math"]["modv"] = ""
lang_dict["math"]["mul"] = "Kertolasku"
lang_dict["math"]["mul0"] = ""
lang_dict["math"]["mul1"] = ""
lang_dict["math"]["mul2"] = ""
lang_dict["math"]["mul3"] = ""
lang_dict["math"]["mulv"] = ""
lang_dict["math"]["num"] = "Luku"
lang_dict["math"]["num.complex"] = "Kompleksiluku"
lang_dict["math"]["num.integer"] = "Kokonaisluku"
lang_dict["math"]["num.rational"] = "Rationaaliluku"
lang_dict["math"]["num.real"] = "Reaaliluku"
lang_dict["math"]["oblong"] = ""
lang_dict["math"]["octagon"] = ""
lang_dict["math"]["parallelogram"] = ""
lang_dict["math"]["pentagon"] = ""
lang_dict["math"]["quadrilateral"] = ""
lang_dict["math"]["radian.few"] = ""
lang_dict["math"]["radian.many"] = ""
lang_dict["math"]["radian.one"] = ""
lang_dict["math"]["radian.other"] = ""
lang_dict["math"]["radian.two"] = ""
lang_dict["math"]["radian.zero"] = ""
lang_dict["math"]["rect"] = ""
lang_dict["math"]["rhomboid"] = ""
lang_dict["math"]["rhombus"] = ""
lang_dict["math"]["root"] = ""
lang_dict["math"]["root0"] = ""
lang_dict["math"]["root1"] = ""
lang_dict["math"]["root2"] = ""
lang_dict["math"]["root3"] = ""
lang_dict["math"]["rootb"] = ""
lang_dict["math"]["rootv"] = ""
lang_dict["math"]["sec"] = ""
lang_dict["math"]["sin"] = "Sini"
lang_dict["math"]["square"] = "Neliö"
lang_dict["math"]["square1"] = ""
lang_dict["math"]["sub"] = "Vähennyslasku"
lang_dict["math"]["sub0"] = ""
lang_dict["math"]["sub1"] = ""
lang_dict["math"]["sub2"] = ""
lang_dict["math"]["sub3"] = ""
lang_dict["math"]["subv"] = ""
lang_dict["math"]["tan"] = "Tangentti"
lang_dict["math"]["total"] = ""
lang_dict["math"]["trapezoid"] = ""
lang_dict["math"]["triangle"] = "Kolmio"
lang_dict["math"]["triangle1"] = ""
lang_dict["math"]["triangle2"] = ""
lang_dict["math"]["trianglea"] = ""
lang_dict["math"]["triangleb"] = ""
lang_dict["math"]["trianglec"] = ""
lang_dict["math"]["trig"] = "Trigonometria"
lang_dict["menu"] = {}
lang_dict["menu"]["close"] = ""
lang_dict["menu"]["close.confirm\\long"] = "Haluatko sulkea pelin?"
lang_dict["menu"]["close.confrim"] = ""
lang_dict["menu"]["content.locked"] = ""
lang_dict["menu"]["content.locked\\long"] = ""
lang_dict["menu"]["content.na"] = ""
lang_dict["menu"]["content.na\\long"] = ""
lang_dict["menu"]["continue"] = ""
lang_dict["menu"]["continue.confirm"] = ""
lang_dict["menu"]["continue.confirm\\long"] = ""
lang_dict["menu"]["continue.error"] = "Peli ei voi jatkaa"
lang_dict["menu"]["credits"] = "Lopputekstit"
lang_dict["menu"]["credits.art"] = "Taide"
lang_dict["menu"]["credits.citations"] = ""
lang_dict["menu"]["credits.code"] = "Ohjelmointi"
lang_dict["menu"]["credits.design"] = "Suunnitelu"
lang_dict["menu"]["credits.end"] = "Loppu"
lang_dict["menu"]["credits.fonts"] = ""
lang_dict["menu"]["credits.localization"] = ""
lang_dict["menu"]["credits.marketing"] = "Markkinointi"
lang_dict["menu"]["credits.music"] = "Musiikki"
lang_dict["menu"]["credits.playtesting"] = ""
lang_dict["menu"]["credits.production"] = "Tuotanto"
lang_dict["menu"]["credits.qa"] = "Laadun varmistus"
lang_dict["menu"]["credits.sfx"] = ""
lang_dict["menu"]["credits.sound"] = "Äänet"
lang_dict["menu"]["credits.soundtrack"] = ""
lang_dict["menu"]["credits.story"] = "Kirjoitus"
lang_dict["menu"]["credits.thanks"] = ""
lang_dict["menu"]["credits.thanks.special"] = "Erityiskiitokset"
lang_dict["menu"]["credits.thanks.to"] = "Kiitos"
lang_dict["menu"]["credits.thanks.you"] = "Kiitos sinulle pelaamisesta"
lang_dict["menu"]["credits.theme"] = ""
lang_dict["menu"]["credits.typo"] = ""
lang_dict["menu"]["credits.voiceacting"] = "Ääninäyttely"
lang_dict["menu"]["credits\\long"] = "Pelin lopputekstit"
lang_dict["menu"]["date"] = "Päiväys ja aika"
lang_dict["menu"]["date.change"] = "Vaihda tämänhetkinen päiväys tai aika"
lang_dict["menu"]["date.change.confirm"] = ""
lang_dict["menu"]["date.change.confirm\\long"] = "Haluatko vaihtaa päiväyksen ja ajan?"
lang_dict["menu"]["date.choose"] = "Valitse päiväys ja aika"
lang_dict["menu"]["date.error"] = "Virhe päiväyksessä tai ajassa"
lang_dict["menu"]["date.error\\long"] = "Päiväys tai aika on virheellinen"
lang_dict["menu"]["date\\long"] = "Päiväyksen ja ajan asetukset"
lang_dict["menu"]["episode.choose"] = ""
lang_dict["menu"]["episode.error"] = ""
lang_dict["menu"]["episode.error.na"] = ""
lang_dict["menu"]["episode.error.na\\long"] = ""
lang_dict["menu"]["episode.error.none"] = ""
lang_dict["menu"]["episode.error.none\\long"] = ""
lang_dict["menu"]["episode.few"] = ""
lang_dict["menu"]["episode.many"] = ""
lang_dict["menu"]["episode.one"] = ""
lang_dict["menu"]["episode.other"] = ""
lang_dict["menu"]["episode.two"] = ""
lang_dict["menu"]["f"] = ""
lang_dict["menu"]["level.choose"] = "Valitse taso"
lang_dict["menu"]["level.completed"] = "Suoritettu"
lang_dict["menu"]["level.completed\\long"] = "Taso suoritettu"
lang_dict["menu"]["level.failed"] = ""
lang_dict["menu"]["level.failed\\long"] = ""
lang_dict["menu"]["level.few"] = ""
lang_dict["menu"]["level.keep"] = "Jatka pelaamista"
lang_dict["menu"]["level.keep.confirm"] = ""
lang_dict["menu"]["level.keep.confirm\\long"] = "Haluatko jatkaa pelaamista?"
lang_dict["menu"]["level.many"] = ""
lang_dict["menu"]["level.one"] = ""
lang_dict["menu"]["level.other"] = "Tasot"
lang_dict["menu"]["level.retry"] = ""
lang_dict["menu"]["level.retry.confirm"] = ""
lang_dict["menu"]["level.retry.confirm\\long"] = ""
lang_dict["menu"]["level.retry\\medium"] = ""
lang_dict["menu"]["level.select"] = "Tason valinta"
lang_dict["menu"]["level.two"] = ""
lang_dict["menu"]["level.zero"] = ""
lang_dict["menu"]["loading"] = "Ladataan"
lang_dict["menu"]["loading.error"] = "Latausvirhe"
lang_dict["menu"]["loading.file.few"] = ""
lang_dict["menu"]["loading.file.many"] = ""
lang_dict["menu"]["loading.file.one"] = "1$. tiedosto $2 tiedostosta"
lang_dict["menu"]["loading.file.other"] = ""
lang_dict["menu"]["loading.file.two"] = ""
lang_dict["menu"]["loading.file.zero"] = ""
lang_dict["menu"]["loading.missing"] = "Tiedosto puuttuu tai on rikki"
lang_dict["menu"]["loading.notfound"] = ""
lang_dict["menu"]["loading.percent"] = "Ladataan: $1%"
lang_dict["menu"]["loading.wait"] = "Odota"
lang_dict["menu"]["menu"] = "Päävalikko"
lang_dict["menu"]["mode.choose"] = "Valitse pelityyli"
lang_dict["menu"]["mode.coop"] = "Yhteistyö"
lang_dict["menu"]["mode.coop.local"] = "Yhteistyö (paikallinen)"
lang_dict["menu"]["mode.coop.online"] = "Yhteistyö (internet)"
lang_dict["menu"]["mode.few"] = ""
lang_dict["menu"]["mode.hotseat"] = "Vuorotellen"
lang_dict["menu"]["mode.local"] = "Moninpeli (paikallinen)"
lang_dict["menu"]["mode.many"] = ""
lang_dict["menu"]["mode.multi"] = "Moninpeli"
lang_dict["menu"]["mode.one"] = "Pelityyli"
lang_dict["menu"]["mode.online"] = "Moninpeli (internet)"
lang_dict["menu"]["mode.other"] = ""
lang_dict["menu"]["mode.single"] = "Yksinpeli"
lang_dict["menu"]["mode.two"] = ""
lang_dict["menu"]["mode.versus"] = "Vastakkain"
lang_dict["menu"]["mode.versus.local"] = "Vastakkain (paikallinen)"
lang_dict["menu"]["mode.versus.online"] = "Vastakkain (internet)"
lang_dict["menu"]["new"] = "Uusi peli"
lang_dict["menu"]["new.confirm"] = ""
lang_dict["menu"]["new.confirm\\long"] = "Haluatko aloittaa uuden pelin?"
lang_dict["menu"]["new\\long"] = "Aloita uusi peli"
lang_dict["menu"]["over"] = "Peli ohi"
lang_dict["menu"]["over.try"] = "Yritä uudelleen"
lang_dict["menu"]["over.try.confirm"] = ""
lang_dict["menu"]["over.try.confirm\\long"] = "Haluatko yrittää uudelleen?"
lang_dict["menu"]["pause"] = "Pysäytetty"
lang_dict["menu"]["pause.confirm"] = ""
lang_dict["menu"]["pause.confirm\\long"] = "Haluatko jatkaa pelaamista?"
lang_dict["menu"]["pause\\long"] = "Peli on pysäytetty"
lang_dict["menu"]["quit"] = "Lopeta"
lang_dict["menu"]["quit.confirm"] = ""
lang_dict["menu"]["quit.confirm\\long"] = "Haluatko sulkea pelin?"
lang_dict["menu"]["quit\\long"] = "Lopeta peli"
lang_dict["menu"]["restart"] = ""
lang_dict["menu"]["restart.changes"] = ""
lang_dict["menu"]["restart.changes\\long"] = "Muutosten käyttöönotto vaatii uudelleenkäynnistyksen"
lang_dict["menu"]["restart.confirm"] = ""
lang_dict["menu"]["restart.confirm\\long"] = "Haluatko käynnistää pelin uudelleen?"
lang_dict["menu"]["restart.required"] = "Tarvitsee uudelleenkäynnistyksen"
lang_dict["menu"]["resume"] = "Jatka"
lang_dict["menu"]["resume.confirm"] = ""
lang_dict["menu"]["resume.confirm\\long"] = "Haluatko jatkaa edellistä peliä?"
lang_dict["menu"]["resume\\long"] = "Jatka edellistä peliä"
lang_dict["menu"]["settings"] = "Asetukset"
lang_dict["menu"]["settings.change"] = "Vaihda pelin asetuksia"
lang_dict["menu"]["settings.choose"] = "Valitse pelin asetus"
lang_dict["menu"]["settings.eror"] = ""
lang_dict["menu"]["settings.error.load"] = ""
lang_dict["menu"]["settings.error.load\\long"] = ""
lang_dict["menu"]["settings.error.save"] = ""
lang_dict["menu"]["settings.error.save\\long"] = ""
lang_dict["menu"]["settings.reset"] = "Palauta"
lang_dict["menu"]["settings.reset.confirm"] = ""
lang_dict["menu"]["settings.reset.confirm\\long"] = "Haluatko palauttaa pelin asetukset?"
lang_dict["menu"]["settings.reset\\long"] = "Palauta asetukset"
lang_dict["menu"]["settings\\long"] = "Pelin asetukset"
lang_dict["menu"]["total"] = ""
lang_dict["menu"]["update"] = ""
lang_dict["menu"]["update.check"] = ""
lang_dict["menu"]["update.check.confirm"] = ""
lang_dict["menu"]["update.check.confirm\\long"] = ""
lang_dict["menu"]["update.check.wait"] = ""
lang_dict["menu"]["update.choose"] = ""
lang_dict["menu"]["update.completed"] = ""
lang_dict["menu"]["update.download.few"] = ""
lang_dict["menu"]["update.download.many"] = ""
lang_dict["menu"]["update.download.one"] = ""
lang_dict["menu"]["update.download.other"] = ""
lang_dict["menu"]["update.download.two"] = ""
lang_dict["menu"]["update.download.wait"] = ""
lang_dict["menu"]["update.error.check"] = ""
lang_dict["menu"]["update.error.check\\long"] = ""
lang_dict["menu"]["update.error.download"] = ""
lang_dict["menu"]["update.error.download\\long"] = ""
lang_dict["menu"]["update.error.install"] = ""
lang_dict["menu"]["update.error.install\\long"] = ""
lang_dict["menu"]["update.error.na"] = ""
lang_dict["menu"]["update.error.uptodate"] = ""
lang_dict["menu"]["update.failed"] = ""
lang_dict["menu"]["update.install.confirm"] = ""
lang_dict["menu"]["update.install.confirm\\long"] = ""
lang_dict["menu"]["update.install.few"] = ""
lang_dict["menu"]["update.install.many"] = ""
lang_dict["menu"]["update.install.one"] = ""
lang_dict["menu"]["update.install.other"] = ""
lang_dict["menu"]["update.install.two"] = ""
lang_dict["menu"]["update.install.wait"] = ""
lang_dict["menu"]["update.progress"] = ""
lang_dict["menu"]["update.restart.cofirm"] = ""
lang_dict["menu"]["update.restart.confirm\\long"] = ""
lang_dict["menu"]["update\\long"] = ""
lang_dict["meta"] = {}
lang_dict["meta"]["license"] = ""
lang_dict["meta"]["notes"] = ""
lang_dict["meta"]["repos"] = ""
lang_dict["meta"]["script.break"] = "False"
lang_dict["meta"]["script.cased"] = "True"
lang_dict["meta"]["script.name"] = "Latn"
lang_dict["meta"]["script.rtl"] = "False"
lang_dict["meta"]["stats"] = ""
lang_dict["meta"]["stats.pinternet"] = ""
lang_dict["meta"]["stats.pspeakers"] = "0.1"
lang_dict["meta"]["stats.psteam"] = "0.34"
lang_dict["meta"]["support"] = ""
lang_dict["meta"]["trans"] = ""
lang_dict["meta"]["trans.contributors"] = "sol, waterlimon"
lang_dict["meta"]["trans.pwords"] = ""
lang_dict["meta"]["trans.updated"] = ""
lang_dict["meta"]["trans.words"] = ""
lang_dict["meta"]["updates"] = ""
lang_dict["meta"]["url"] = ""
lang_dict["progress"] = {}
lang_dict["progress"]["gander.female"] = "Nainen"
lang_dict["progress"]["gender"] = "Sukupuoli"
lang_dict["progress"]["gender.choose"] = "Valitse sukupuoli"
lang_dict["progress"]["gender.male"] = "Mies"
lang_dict["progress"]["gender.other"] = "Muu"
lang_dict["progress"]["gender.undefined"] = "Määrittelemätön"
lang_dict["progress"]["name"] = ""
lang_dict["progress"]["name.anon"] = "Nimetön"
lang_dict["progress"]["name.enter"] = ""
lang_dict["progress"]["name.enter\\long"] = "Anna profiilin nimi"
lang_dict["progress"]["name.none"] = "Tuntematon"
lang_dict["progress"]["name.player"] = "Pelaaja"
lang_dict["progress"]["name.player.id"] = "Pelaaja $1"
lang_dict["progress"]["name.warn"] = ""
lang_dict["progress"]["name.warn\\long"] = "Profiilin nimi ei kelpaa"
lang_dict["progress"]["name\\long"] = ""
lang_dict["progress"]["pregress.error"] = "Tilannevirhe"
lang_dict["progress"]["pregress.save.fail"] = "Tilannetta ei voitu tallentaa"
lang_dict["progress"]["profile.change"] = "Vaihda profiiliasetuksia"
lang_dict["progress"]["profile.choose"] = "Valitse profiili"
lang_dict["progress"]["profile.delete"] = "Poista profiili"
lang_dict["progress"]["profile.delete.confirm"] = ""
lang_dict["progress"]["profile.delete.confirm\\long"] = "Haluaisitko poistaa tämän profiilin?"
lang_dict["progress"]["profile.edit"] = ""
lang_dict["progress"]["profile.error"] = ""
lang_dict["progress"]["profile.error.delete"] = "Virhe profiilia poistaessa"
lang_dict["progress"]["profile.error.load"] = "Virhe profiilia ladatessa"
lang_dict["progress"]["profile.error.load\\long"] = "Profiilia ei voitu ladata"
lang_dict["progress"]["profile.error.new"] = "Virhe profiilia luodessa"
lang_dict["progress"]["profile.error.rename"] = "Virhe profiilin nimen vaihdossa"
lang_dict["progress"]["profile.error.save"] = "Virhe profiilia tallennettaessa"
lang_dict["progress"]["profile.error.save\\long"] = "Profiilia ei voitu tallentaa"
lang_dict["progress"]["profile.few"] = ""
lang_dict["progress"]["profile.many"] = ""
lang_dict["progress"]["profile.new"] = "Luo uusi profiili"
lang_dict["progress"]["profile.new.confirm"] = ""
lang_dict["progress"]["profile.new.confirm\\long"] = ""
lang_dict["progress"]["profile.one"] = "Profiili"
lang_dict["progress"]["profile.other"] = ""
lang_dict["progress"]["profile.password"] = ""
lang_dict["progress"]["profile.password.enter"] = ""
lang_dict["progress"]["profile.rename"] = "Vaihda profiilin nimeä"
lang_dict["progress"]["profile.signin"] = ""
lang_dict["progress"]["profile.singout"] = ""
lang_dict["progress"]["profile.two"] = ""
lang_dict["progress"]["profile.username"] = ""
lang_dict["progress"]["profile.zero"] = ""
lang_dict["progress"]["progress.last"] = "Edellistä peliä ei tallennettu oikein"
lang_dict["progress"]["progress.load.fail"] = "Tilannetta ei voitu ladata"
lang_dict["progress"]["progress.loading"] = "Tilannetta ladataan"
lang_dict["progress"]["progress.saving"] = "Tilannetta tallennetaan"
lang_dict["progress"]["progress.warning"] = "Koko tilannetta ei voitu tallentaa"
lang_dict["progress"]["sg.choose"] = "Valitse pelitallenne"
lang_dict["progress"]["sg.copy"] = "Kopioi"
lang_dict["progress"]["sg.copy.confirm"] = ""
lang_dict["progress"]["sg.copy.confirm\\long"] = "Haluaisitko kopioida pelitallenteen?"
lang_dict["progress"]["sg.copy\\long"] = "Kopioi pelitallenne"
lang_dict["progress"]["sg.delete"] = "Poista"
lang_dict["progress"]["sg.delete.confirm"] = ""
lang_dict["progress"]["sg.delete.confirm\\long"] = "Haluaisitko poistaa pelitallenteen?"
lang_dict["progress"]["sg.delete.fail"] = ""
lang_dict["progress"]["sg.delete.fail\\long"] = "Pelitallennetta ei voitu poistaa"
lang_dict["progress"]["sg.delete\\long"] = "Poista pelitallenne"
lang_dict["progress"]["sg.load"] = "Lataa"
lang_dict["progress"]["sg.load.fail"] = "Tallennettua pelitilaa ei voitu ladata"
lang_dict["progress"]["sg.load\\long"] = "Lataa pelitallenne"
lang_dict["progress"]["sg.loading"] = "Lataan tallennettua peliä"
lang_dict["progress"]["sg.loading.fail"] = "Pelitilan latausvirhe"
lang_dict["progress"]["sg.loading.fail\\long"] = "Tallennettua pelitilaa ei voitu ladata"
lang_dict["progress"]["sg.name"] = "Kirjoita nimi pelitallenteelle"
lang_dict["progress"]["sg.overwrite"] = ""
lang_dict["progress"]["sg.overwrite.confirm"] = ""
lang_dict["progress"]["sg.overwrite.confirm\\long"] = "Haluaisitko ylikirjoittaa tallennetun pelin?"
lang_dict["progress"]["sg.overwrite.fail"] = "Tallenteen yli ei voitu kirjoittaa"
lang_dict["progress"]["sg.overwrite\\long"] = "Ylikirjoita peli"
lang_dict["progress"]["sg.save"] = "Tallenna"
lang_dict["progress"]["sg.save.confirm"] = ""
lang_dict["progress"]["sg.save.confirm\\long"] = "Haluaisitko tallentaa pelin?"
lang_dict["progress"]["sg.save\\long"] = "Tallenna peli"
lang_dict["progress"]["sg.saved"] = ""
lang_dict["progress"]["sg.saving"] = "Peliä tallennetaan"
lang_dict["progress"]["sg.saving.fail"] = "Pelin tallennusvirhe"
lang_dict["progress"]["sg.saving.fail\\long"] = "Peliä ei voitu tallentaa"
lang_dict["progress"]["sg.scan"] = "Etsin pelitallenteita"
lang_dict["progress"]["sg.scan.fail"] = "En löytänyt pelitallenteita"
lang_dict["progress"]["slot"] = "Lokero"
lang_dict["progress"]["slot.choose"] = "Valitse lokero"
lang_dict["progress"]["slot.choose.empty"] = "Valitse tyhjä lokero"
lang_dict["progress"]["slot.choose\\long"] = "Valitse tallennuslokero"
lang_dict["progress"]["slot.copy"] = "Kopioi tallennuslokero"
lang_dict["progress"]["slot.copy.confirm"] = ""
lang_dict["progress"]["slot.copy.confirm\\long"] = "Haluaisitko kopioida lokeron $1?"
lang_dict["progress"]["slot.delete"] = "Poista tallennuslokero"
lang_dict["progress"]["slot.delete.confirm"] = ""
lang_dict["progress"]["slot.delete.confirm\\long"] = "Haluaisitko poistaa lokeron $1?"
lang_dict["progress"]["slot.delete.error"] = "Tallennuslokeroa ei voitu poistaa"
lang_dict["progress"]["slot.empty"] = "Tyhjä"
lang_dict["progress"]["slot.empty\\long"] = "Tyhjä lokero"
lang_dict["progress"]["slot.id"] = "Lokero $1"
lang_dict["progress"]["slot.load"] = "Lataa tallennuslokerosta"
lang_dict["progress"]["slot.load.error"] = "Tallennuslokeroa ei voitu ladata"
lang_dict["progress"]["slot.notempty"] = "Lokero $1 ei ole tyhjä"
lang_dict["progress"]["slot.overwrite"] = "Ylikirjoita tallennuslokero"
lang_dict["progress"]["slot.overwrite.confirm"] = ""
lang_dict["progress"]["slot.overwrite.confirm\\long"] = "Haluaisitko ylikirjoittaa lokeron $1?"
lang_dict["progress"]["slot.overwrite.error"] = "Tallennuslokeron yli ei voitu tallentaa"
lang_dict["progress"]["slot.save"] = "Tallennuslokero"
lang_dict["progress"]["total"] = ""
lang_dict["sayings"] = {}
lang_dict["sayings"]["beginning"] = ""
lang_dict["sayings"]["beginning.similar"] = ""
lang_dict["sayings"]["bird"] = ""
lang_dict["sayings"]["bird.similar"] = ""
lang_dict["sayings"]["birds"] = ""
lang_dict["sayings"]["birds.similar"] = ""
lang_dict["sayings"]["blink"] = ""
lang_dict["sayings"]["blink.similar"] = ""
lang_dict["sayings"]["cat"] = ""
lang_dict["sayings"]["cat.similar"] = ""
lang_dict["sayings"]["chickens"] = ""
lang_dict["sayings"]["chickens.similar"] = ""
lang_dict["sayings"]["clock"] = ""
lang_dict["sayings"]["clock.similar"] = ""
lang_dict["sayings"]["cut"] = ""
lang_dict["sayings"]["cut.similar"] = ""
lang_dict["sayings"]["end"] = ""
lang_dict["sayings"]["end.similar"] = ""
lang_dict["sayings"]["flow"] = ""
lang_dict["sayings"]["flow.similar"] = ""
lang_dict["sayings"]["fool"] = ""
lang_dict["sayings"]["fortune"] = ""
lang_dict["sayings"]["fortune.similar"] = ""
lang_dict["sayings"]["forward"] = ""
lang_dict["sayings"]["forward.similar"] = ""
lang_dict["sayings"]["gain"] = ""
lang_dict["sayings"]["gain.similar"] = ""
lang_dict["sayings"]["gate"] = ""
lang_dict["sayings"]["gate.similar"] = ""
lang_dict["sayings"]["goal"] = ""
lang_dict["sayings"]["leap"] = ""
lang_dict["sayings"]["leap.similar"] = ""
lang_dict["sayings"]["luck"] = ""
lang_dict["sayings"]["luck.similar"] = ""
lang_dict["sayings"]["moment"] = ""
lang_dict["sayings"]["moment.similar"] = ""
lang_dict["sayings"]["mouth"] = ""
lang_dict["sayings"]["mouth.similar"] = ""
lang_dict["sayings"]["opportunity"] = ""
lang_dict["sayings"]["opportunity.similar"] = ""
lang_dict["sayings"]["ox"] = ""
lang_dict["sayings"]["ox.similar"] = ""
lang_dict["sayings"]["path"] = ""
lang_dict["sayings"]["patience"] = ""
lang_dict["sayings"]["plan"] = ""
lang_dict["sayings"]["practice"] = ""
lang_dict["sayings"]["praticle.similar"] = ""
lang_dict["sayings"]["reap"] = ""
lang_dict["sayings"]["reap.similar"] = ""
lang_dict["sayings"]["run"] = ""
lang_dict["sayings"]["run.similar"] = ""
lang_dict["sayings"]["slow"] = ""
lang_dict["sayings"]["slow.similar"] = ""
lang_dict["sayings"]["stitch"] = ""
lang_dict["sayings"]["stitch.similar"] = ""
lang_dict["sayings"]["stoke.similar"] = ""
lang_dict["sayings"]["stroke"] = ""
lang_dict["sayings"]["total"] = ""
lang_dict["sayings"]["turn"] = ""
lang_dict["sayings"]["turn.similar"] = ""
lang_dict["sayings"]["two"] = ""
lang_dict["sayings"]["two.similar"] = ""
lang_dict["sayings"]["wait"] = ""
lang_dict["sayings"]["wait.similar"] = ""
lang_dict["sayings"]["water"] = ""
lang_dict["sayings"]["water.similar"] = ""
lang_dict["sayings"]["wheat"] = ""
lang_dict["sayings"]["wind"] = ""
lang_dict["sayings"]["wind.similar"] = ""
lang_dict["sayings"]["wise"] = ""
lang_dict["score"] = {}
lang_dict["score"]["achieve.few"] = ""
lang_dict["score"]["achieve.many"] = ""
lang_dict["score"]["achieve.one"] = ""
lang_dict["score"]["achieve.other"] = ""
lang_dict["score"]["achieve.two"] = ""
lang_dict["score"]["achieve.unlock"] = ""
lang_dict["score"]["achieve.unlock.plural"] = ""
lang_dict["score"]["achieve.unlock\\long"] = ""
lang_dict["score"]["achieve.zero"] = ""
lang_dict["score"]["attempt.failed"] = ""
lang_dict["score"]["attempt.failed\\long"] = ""
lang_dict["score"]["attempt.few"] = ""
lang_dict["score"]["attempt.made"] = ""
lang_dict["score"]["attempt.many"] = ""
lang_dict["score"]["attempt.one"] = ""
lang_dict["score"]["attempt.other"] = ""
lang_dict["score"]["attempt.successful"] = ""
lang_dict["score"]["attempt.successful\\long"] = ""
lang_dict["score"]["attempt.two"] = ""
lang_dict["score"]["attempt.zero"] = ""
lang_dict["score"]["bones.earned.plural"] = ""
lang_dict["score"]["bonus.earned"] = ""
lang_dict["score"]["bonus.earned\\long"] = ""
lang_dict["score"]["bonus.few"] = ""
lang_dict["score"]["bonus.many"] = ""
lang_dict["score"]["bonus.one"] = ""
lang_dict["score"]["bonus.other"] = ""
lang_dict["score"]["bonus.two"] = ""
lang_dict["score"]["bonus.zero"] = ""
lang_dict["score"]["completed"] = "Suoritettu"
lang_dict["score"]["completed\\long"] = "Suoritetut tasot"
lang_dict["score"]["hiscore"] = "Ennätykset"
lang_dict["score"]["hiscore.downloading"] = ""
lang_dict["score"]["hiscore.downloading\\long"] = "Haetaan ennätyksiä"
lang_dict["score"]["hiscore.error"] = "Virhe ennätyksissä"
lang_dict["score"]["hiscore.error.connect"] = ""
lang_dict["score"]["hiscore.error.connect\\long"] = "Yhdistäminen ennätyspalvelimeen epäonnistui"
lang_dict["score"]["hiscore.error.connect\\medium"] = ""
lang_dict["score"]["hiscore.error.download"] = ""
lang_dict["score"]["hiscore.error.download\\long"] = ""
lang_dict["score"]["hiscore.error.download\\medium"] = "Virhe ennätysten lataamisessa"
lang_dict["score"]["hiscore.error.load"] = ""
lang_dict["score"]["hiscore.error.load\\long"] = "Ennätyksiä ei voitu ladata"
lang_dict["score"]["hiscore.error.load\\medium"] = ""
lang_dict["score"]["hiscore.error.save"] = ""
lang_dict["score"]["hiscore.error.save\\long"] = "Ennätystä ei voitu tallentaa"
lang_dict["score"]["hiscore.error.save\\medium"] = ""
lang_dict["score"]["hiscore.error.upload"] = ""
lang_dict["score"]["hiscore.error.upload\\long"] = ""
lang_dict["score"]["hiscore.error.upload\\medium"] = "Virhe ennätyksen lähetyksessä"
lang_dict["score"]["hiscore.loading"] = ""
lang_dict["score"]["hiscore.loading\\long"] = "Ladataan ennätyksiä"
lang_dict["score"]["hiscore.offline"] = "Paikalliset ennätykset"
lang_dict["score"]["hiscore.online"] = "Maailmanlaajuiset ennätykset"
lang_dict["score"]["hiscore.reset"] = "Nollaa ennätykset"
lang_dict["score"]["hiscore.reset.confirm"] = ""
lang_dict["score"]["hiscore.reset.confirm\\long"] = "Haluatko nollata ennätykset?"
lang_dict["score"]["hiscore.saving"] = ""
lang_dict["score"]["hiscore.saving\\long"] = "Tallennetaan ennätystä"
lang_dict["score"]["hiscore.submit"] = "Tallenna tulos"
lang_dict["score"]["hiscore.submit.confirm"] = ""
lang_dict["score"]["hiscore.submit.confirm\\long"] = "Haluatko tallentaa tuloksesi?"
lang_dict["score"]["hiscore.upload"] = "Lähetä tulos"
lang_dict["score"]["hiscore.upload.confirm"] = ""
lang_dict["score"]["hiscore.upload.confirm\\long"] = "Haluatko lähettää tuloksesi?"
lang_dict["score"]["hiscore.uploading"] = ""
lang_dict["score"]["hiscore.uploading\\long"] = "Lähetetään ennätystä"
lang_dict["score"]["played"] = ""
lang_dict["score"]["played\\long"] = ""
lang_dict["score"]["points.count.few"] = ""
lang_dict["score"]["points.count.many"] = ""
lang_dict["score"]["points.count.one"] = "$1 piste"
lang_dict["score"]["points.count.other"] = "$1 pistettä"
lang_dict["score"]["points.count.two"] = ""
lang_dict["score"]["points.count.zero"] = ""
lang_dict["score"]["points.few"] = ""
lang_dict["score"]["points.many"] = ""
lang_dict["score"]["points.one"] = ""
lang_dict["score"]["points.other"] = "Pisteet"
lang_dict["score"]["points.two"] = ""
lang_dict["score"]["points.your"] = ""
lang_dict["score"]["points.zero"] = ""
lang_dict["score"]["score"] = "Tulos"
lang_dict["score"]["score.your"] = "Tuloksesi"
lang_dict["score"]["stats"] = ""
lang_dict["score"]["stats.your"] = ""
lang_dict["score"]["stats.your\\long"] = ""
lang_dict["score"]["stats\\long"] = ""
lang_dict["score"]["time"] = ""
lang_dict["score"]["time\\long"] = ""
lang_dict["score"]["total"] = ""
lang_dict["translit"] = {}
lang_dict["translit"]["A"] = ""
lang_dict["translit"]["Ae"] = ""
lang_dict["translit"]["B"] = ""
lang_dict["translit"]["C"] = ""
lang_dict["translit"]["D"] = ""
lang_dict["translit"]["E"] = ""
lang_dict["translit"]["F"] = ""
lang_dict["translit"]["G"] = ""
lang_dict["translit"]["H"] = ""
lang_dict["translit"]["I"] = ""
lang_dict["translit"]["J"] = ""
lang_dict["translit"]["K"] = ""
lang_dict["translit"]["L"] = ""
lang_dict["translit"]["M"] = ""
lang_dict["translit"]["N"] = ""
lang_dict["translit"]["O"] = ""
lang_dict["translit"]["Oe"] = ""
lang_dict["translit"]["P"] = ""
lang_dict["translit"]["Q"] = ""
lang_dict["translit"]["R"] = ""
lang_dict["translit"]["S"] = ""
lang_dict["translit"]["T"] = ""
lang_dict["translit"]["U"] = ""
lang_dict["translit"]["V"] = ""
lang_dict["translit"]["W"] = ""
lang_dict["translit"]["X"] = ""
lang_dict["translit"]["Y"] = ""
lang_dict["translit"]["Z"] = ""
lang_dict["translit"]["a"] = "ä, å"
lang_dict["translit"]["ae"] = ""
lang_dict["translit"]["af"] = ""
lang_dict["translit"]["ai"] = ""
lang_dict["translit"]["av"] = ""
lang_dict["translit"]["ay"] = ""
lang_dict["translit"]["b"] = ""
lang_dict["translit"]["c"] = ""
lang_dict["translit"]["ch"] = ""
lang_dict["translit"]["d"] = ""
lang_dict["translit"]["dy"] = ""
lang_dict["translit"]["dz"] = ""
lang_dict["translit"]["dzh"] = ""
lang_dict["translit"]["e"] = ""
lang_dict["translit"]["ef"] = ""
lang_dict["translit"]["ei"] = ""
lang_dict["translit"]["ev"] = ""
lang_dict["translit"]["ey"] = ""
lang_dict["translit"]["f"] = ""
lang_dict["translit"]["g"] = ""
lang_dict["translit"]["gk"] = ""
lang_dict["translit"]["h"] = ""
lang_dict["translit"]["i"] = ""
lang_dict["translit"]["ia"] = ""
lang_dict["translit"]["iu"] = ""
lang_dict["translit"]["j"] = ""
lang_dict["translit"]["k"] = ""
lang_dict["translit"]["kh"] = ""
lang_dict["translit"]["l"] = ""
lang_dict["translit"]["lf"] = ""
lang_dict["translit"]["lv"] = ""
lang_dict["translit"]["ly"] = ""
lang_dict["translit"]["m"] = ""
lang_dict["translit"]["n"] = ""
lang_dict["translit"]["nch"] = ""
lang_dict["translit"]["nt"] = ""
lang_dict["translit"]["nx"] = ""
lang_dict["translit"]["ny"] = ""
lang_dict["translit"]["o"] = "ö"
lang_dict["translit"]["oe"] = ""
lang_dict["translit"]["oi"] = ""
lang_dict["translit"]["ou"] = ""
lang_dict["translit"]["oy"] = ""
lang_dict["translit"]["p"] = ""
lang_dict["translit"]["ps"] = ""
lang_dict["translit"]["q"] = ""
lang_dict["translit"]["r"] = ""
lang_dict["translit"]["s"] = ""
lang_dict["translit"]["sh"] = ""
lang_dict["translit"]["shch"] = ""
lang_dict["translit"]["sht"] = ""
lang_dict["translit"]["t"] = ""
lang_dict["translit"]["th"] = ""
lang_dict["translit"]["total"] = ""
lang_dict["translit"]["ts"] = ""
lang_dict["translit"]["ty"] = ""
lang_dict["translit"]["u"] = ""
lang_dict["translit"]["ue"] = ""
lang_dict["translit"]["v"] = ""
lang_dict["translit"]["w"] = ""
lang_dict["translit"]["x"] = ""
lang_dict["translit"]["y"] = ""
lang_dict["translit"]["ya"] = ""
lang_dict["translit"]["yi"] = ""
lang_dict["translit"]["yo"] = ""
lang_dict["translit"]["yu"] = ""
lang_dict["translit"]["z"] = ""
lang_dict["translit"]["zh"] = ""
lang_dict["video"] = {}
lang_dict["video"]["aa"] = "Reunojenpehmennys"
lang_dict["video"]["aa.change"] = "Vaihda reunojenpehmennyksen tasoa"
lang_dict["video"]["aa.choose"] = "Valitse reunojenpehmennyksen taso"
lang_dict["video"]["aa.desc"] = ""
lang_dict["video"]["aa.desc\\long"] = ""
lang_dict["video"]["aa.desc\\short"] = "Pehmentää reunojen piirtoa, parantaen kuvanlaatua"
lang_dict["video"]["aa.func"] = ""
lang_dict["video"]["aa.func\\long"] = ""
lang_dict["video"]["aa.func\\short"] = "Pehmentää tai sumentaa rosoisia reunoja näytöllä"
lang_dict["video"]["aa.level"] = "$1x"
lang_dict["video"]["aa.modex"] = "Reunojenpehmennystaso: $1"
lang_dict["video"]["aa.off"] = "Ota reunojenpehmennys pois käytöstä"
lang_dict["video"]["aa.on"] = "Ota reunojenpehmennys käyttöön"
lang_dict["video"]["aa\\long"] = "Reunojenpehmennyksen tasot"
lang_dict["video"]["aspect"] = "Kuvasuhde"
lang_dict["video"]["aspect.change"] = "Muuta näytön kuvasuhdetta"
lang_dict["video"]["aspect.choose"] = "Valitse kuvasuhde"
lang_dict["video"]["aspect.desc"] = "Näytön korkeuden ja leveyden suhde"
lang_dict["video"]["aspect.func"] = "Määrittää näytön mittasuhteet"
lang_dict["video"]["aspect.ratio"] = "$1:$2"
lang_dict["video"]["aspect\\long"] = "Näytön kuvasuhde"
lang_dict["video"]["color"] = "Väri"
lang_dict["video"]["color.change"] = "Muuta värin laatua"
lang_dict["video"]["color.choose"] = "Valitse värin laatu"
lang_dict["video"]["color.count.few"] = ""
lang_dict["video"]["color.count.many"] = ""
lang_dict["video"]["color.count.one"] = ""
lang_dict["video"]["color.count.other"] = "$1 väriä"
lang_dict["video"]["color.count.two"] = ""
lang_dict["video"]["color.count.zero"] = ""
lang_dict["video"]["color.mode1"] = ""
lang_dict["video"]["color.mode2"] = "Tuhansia värejä"
lang_dict["video"]["color.mode3"] = "Miljoonia värejä"
lang_dict["video"]["color\\long"] = "Värin laatu"
lang_dict["video"]["depth"] = "Värisyvyys"
lang_dict["video"]["depth.bit.few"] = ""
lang_dict["video"]["depth.bit.many"] = ""
lang_dict["video"]["depth.bit.one"] = "$1 bitti"
lang_dict["video"]["depth.bit.other"] = "$1 bittiä"
lang_dict["video"]["depth.bit.two"] = ""
lang_dict["video"]["depth.bit.zero"] = ""
lang_dict["video"]["depth.change"] = "Muuta värisyvyyden formaattia"
lang_dict["video"]["depth.choose"] = "Valitse värisyvyys"
lang_dict["video"]["depth.current"] = ""
lang_dict["video"]["depth.currentx"] = ""
lang_dict["video"]["depth.desc"] = "Yhden pikselin värin esittämiseen käytettyjen bittien määrä"
lang_dict["video"]["depth.desc\\long"] = ""
lang_dict["video"]["depth.error"] = ""
lang_dict["video"]["depth.error.change"] = ""
lang_dict["video"]["depth.error.unsupported"] = ""
lang_dict["video"]["depth.error.unsupported2"] = ""
lang_dict["video"]["depth.func"] = "Määrittää esitettävien värien määrän"
lang_dict["video"]["depth.func\\long"] = ""
lang_dict["video"]["depth\\long"] = "Värisyvyyden formaatti"
lang_dict["video"]["fps"] = "Kuvataajuus"
lang_dict["video"]["fps.change"] = "Vaihda tavoitekuvataajuutta"
lang_dict["video"]["fps.choose"] = "Valitse tavoitekuvataajuus"
lang_dict["video"]["fps.count.few"] = ""
lang_dict["video"]["fps.count.few\\long"] = ""
lang_dict["video"]["fps.count.many"] = ""
lang_dict["video"]["fps.count.many\\long"] = ""
lang_dict["video"]["fps.count.one"] = ""
lang_dict["video"]["fps.count.one\\long"] = "$1 päivitys sekunnissa"
lang_dict["video"]["fps.count.other"] = "$1 FPS"
lang_dict["video"]["fps.count.other\\long"] = "$1 päivitystä sekunnissa"
lang_dict["video"]["fps.count.two"] = ""
lang_dict["video"]["fps.count.two\\long"] = ""
lang_dict["video"]["fps.count.zero"] = ""
lang_dict["video"]["fps.count.zero\\long"] = ""
lang_dict["video"]["fps.current"] = "Kuvataajuus nyt"
lang_dict["video"]["fps.target"] = "Tavoitekuvataajuus"
lang_dict["video"]["gamma"] = "Gamma-korjaus"
lang_dict["video"]["gamma.change"] = "Säädä gamma-korjauksen tasoja"
lang_dict["video"]["gamma.choose"] = "Valitse gamma-korjauksen taso"
lang_dict["video"]["gamma\\long"] = "Gamma-korjauksen tasot"
lang_dict["video"]["graphics"] = "Grafiikka"
lang_dict["video"]["graphics.advanced"] = ""
lang_dict["video"]["graphics.advanced.change"] = ""
lang_dict["video"]["graphics.advanced\\long"] = ""
lang_dict["video"]["graphics.card"] = "Näytönohjain"
lang_dict["video"]["graphics.change"] = "Vaihda grafiikka-asetuksia"
lang_dict["video"]["graphics.error"] = ""
lang_dict["video"]["graphics.error.init"] = ""
lang_dict["video"]["graphics.settings"] = "Grafiikka-asetukset"
lang_dict["video"]["mode"] = "Näyttötila"
lang_dict["video"]["mode.application"] = "Sovelluksen näyttötila"
lang_dict["video"]["mode.change"] = "Vaihda näyttötilaa"
lang_dict["video"]["mode.choose"] = "Valitse näyttötila"
lang_dict["video"]["mode.confirm"] = ""
lang_dict["video"]["mode.confrim\\long"] = "Vahvista valittu näyttötila"
lang_dict["video"]["mode.efullscreen"] = "Vaihda koko ruudun tilaan"
lang_dict["video"]["mode.error"] = "Näyttötilavirhe"
lang_dict["video"]["mode.error.change"] = ""
lang_dict["video"]["mode.error.unsupported"] = ""
lang_dict["video"]["mode.error.unsupported2"] = "Valittua näyttötilaa ei tueta"
lang_dict["video"]["mode.ewindowed"] = "Vaihda ikkunatilaan"
lang_dict["video"]["mode.fullscreen"] = "Koko ruutu"
lang_dict["video"]["mode.keep"] = ""
lang_dict["video"]["mode.keep\\long"] = "Haluatko pitää valitun näyttötilan?"
lang_dict["video"]["mode.windowed"] = "Ikkuna"
lang_dict["video"]["quality"] = "Laatu"
lang_dict["video"]["quality.average"] = "Keskiverto"
lang_dict["video"]["quality.change"] = "Vaihda grafiikan laatu"
lang_dict["video"]["quality.choose"] = "Valitse grafiikan laatu"
lang_dict["video"]["quality.graphics"] = "Grafiikan laatu"
lang_dict["video"]["quality.high"] = "Korkea"
lang_dict["video"]["quality.low"] = "Matala"
lang_dict["video"]["quality.maximum"] = "Paras"
lang_dict["video"]["quality.minimum"] = "Nopein"
lang_dict["video"]["resolution"] = "Tarkkuus"
lang_dict["video"]["resolution.area"] = "$1x$2"
lang_dict["video"]["resolution.area\\long"] = "$1 kertaa $2 pikseliä"
lang_dict["video"]["resolution.change"] = "Vaihda näytön tarkkuutta"
lang_dict["video"]["resolution.choose"] = "Valitse tarkkuus"
lang_dict["video"]["resolution.confirm"] = ""
lang_dict["video"]["resolution.confirm\\long"] = "Vahvista valittu tarkkuus"
lang_dict["video"]["resolution.current"] = ""
lang_dict["video"]["resolution.error"] = "Tarkkuusvirhe"
lang_dict["video"]["resolution.error.change"] = ""
lang_dict["video"]["resolution.error.unsupported"] = ""
lang_dict["video"]["resolution.error.unsupported\\long"] = "Valittua tarkkuutta ei tueta"
lang_dict["video"]["resolution.keep"] = ""
lang_dict["video"]["resolution.keep\\long"] = "Haluatko pitää valitun tarkkuuden?"
lang_dict["video"]["resolution\\long"] = "Näytön tarkkuus"
lang_dict["video"]["rrate"] = "Virkistystaajuus"
lang_dict["video"]["rrate.change"] = "Vaihda näytön virkistystaajuutta"
lang_dict["video"]["rrate.choose"] = "Valitse virkistystaajuus"
lang_dict["video"]["rrate.hz.few"] = ""
lang_dict["video"]["rrate.hz.few\\long"] = ""
lang_dict["video"]["rrate.hz.many"] = ""
lang_dict["video"]["rrate.hz.many\\long"] = ""
lang_dict["video"]["rrate.hz.one"] = ""
lang_dict["video"]["rrate.hz.one\\long"] = "$1 Hertz"
lang_dict["video"]["rrate.hz.other"] = "$1 Hz"
lang_dict["video"]["rrate.hz.other\\long"] = "$1 Hertz"
lang_dict["video"]["rrate.hz.two"] = ""
lang_dict["video"]["rrate.hz.two\\long"] = ""
lang_dict["video"]["rrate.hz.zero"] = ""
lang_dict["video"]["rrate.hz.zero\\long"] = ""
lang_dict["video"]["rratefull"] = "Näytön virkistystaajuus"
lang_dict["video"]["total"] = ""
lang_dict["video"]["vsync"] = "Vsync"
lang_dict["video"]["vsync.change"] = "Ota tai poista vsync käytöstä"
lang_dict["video"]["vsync.desc"] = "Synkronoi näytönohjaimen ja näytön virkistystaajuuden"
lang_dict["video"]["vsync.desc\\long"] = ""
lang_dict["video"]["vsync.func"] = ""
lang_dict["video"]["vsync.func\\long"] = "Vähentää kuvan repeytymistä"
lang_dict["video"]["vsync.off"] = "Pois"
lang_dict["video"]["vsync.on"] = "Päällä"
lang_dict["video"]["vsync.turnoff"] = "Poista vsync käytöstä"
lang_dict["video"]["vsync.turnon"] = "Ota vsync käyttöön"
lang_dict["video"]["vsync\\long"] = "Pystysuuntainen synkronisaatio"
return lang_dict
|
dofile'../../include.lua'
os.execute('clear')
--try_torch = true
if try_torch then
T = require'libTransform'
else
T = require'Transform'
end
q = require'quaternion'
v = require'vector'
util = require'util'
angle0 = 45*DEG_TO_RAD
axis0 = {0,1,0}
angle1 = 45*DEG_TO_RAD
axis1 = {1,0,0}
t = 0
print(angle0*RAD_TO_DEG, unpack(axis0))
print(angle1*RAD_TO_DEG, unpack(axis1))
--
q0 = q.from_angle_axis(angle0,axis0)
q1 = q.from_angle_axis(angle1,axis1)
print(q0,q1)
qSlerp = q.slerp(q0,q1,t)
angle, axis = q.angle_axis( qSlerp )
print(angle*RAD_TO_DEG, unpack(axis))
print('=======')
function randAA()
local ang = math.random()*360*DEG_TO_RAD-180*DEG_TO_RAD
local axis = v.new{
math.random(),
math.random(),
math.random()
}
return ang, axis / v.norm(axis)
end
local quats = {}
for i=1,100 do
local ang, axis = randAA()
print(ang, axis)
quats[i] = q.from_angle_axis(ang, axis)
end
local fromQ = require'Transform'.from_quatp
local toQ = require'Transform'.to_quatp
local quatps = {}
for i,quat in ipairs(quats) do
local quatp = {unpack(quat)}
quatp[5] = math.random() * 10
quatp[6] = math.random() * 10
quatp[7] = math.random() * 10
quatps[i] = v.new(quatp)
end
for i,quatp in ipairs(quatps) do
print('*')
print(quatp)
local tr = fromQ(quatp)
print(tr)
local quatp1 = toQ(tr)
v.new(quatp1)
--local tr1 = fromQ(quatp1)
print(quatp, quatp1)
--print(quatp1-quatp)
end
|
-- NOTE: CLove has 'different' API than Love. Be careful!
box = {}
box.x = 100
box.y = 100
box.s = 32
function love.load()
end
function love.update(dt)
if love.joystick.isDown(0, "b", "dpright") then
box.x = box.x + 100 * dt
end
if love.joystick.isDown(0, "x", "dpleft") then
box.x = box.x - 100 * dt
end
if love.joystick.isDown(0, "y", "dpup") then
box.y = box.y + 100 * dt
end
if love.joystick.isDown(0, "a", "dpdown") then
box.y = box.y - 100 * dt
end
-- NOTE!
-- RT & LT are being shown in this piece of code and can not be accesed
-- differently at least using an XBox One controller.
for i=1, love.joystick.getAxisCount(0) do
local value = love.joystick.getAxis(0, i)
if value ~= 0 then
print("detected movement: " .. value .. " on axis: " .. i)
end
end
end
function love.joystickpressed(id, button)
if id == 0 then
-- add your logic
print(button .. " has been just pressed!")
end
end
function love.joystickreleased(id, button)
if id == 0 then
-- add your logic here
end
end
function love.draw()
love.graphics.rectangle("fill", box.x, box.y, box.s, box.s)
local count = love.joystick.getCount(0)
local name = love.joystick.getName(0)
local isGamepad = tostring(love.joystick.isGamepad(0))
local isConnected = tostring(love.joystick.isConnected(0))
-- local getHatCount = love.joystick.getHatCount(0)
-- local getHat = tostring(love.joystick.getHat(0, "d")) -- TYPE can be: u, d, l , r, ld (left down), lu, rd, du
-- local getGamepadAxis = tostring(love.joystick.getGamepadAxis(0, "rightx"))
love.graphics.print("You got: " .. count .. " connected device with status of connected: " .. isConnected .. " joystick/gamepad connected which \n are/are not gamepads: " .. isGamepad .. " by the name of: " .. name, 10, 300);
end
|
return {
Inventory = {
-- MILITECH "FALCON" SANDEVISTAN MK.5 / Cyberware / Operating System / Legendary
-- Manufactured by Militech, the "Falcon" is hands down the best and most advanced Sandevistan model out there. Previously used only by elite Militech soldiers, its now available to the average consumer. The nickname is no accident - the peregrine falcon was once one of the fastest animals in the world, as this implant is among cyberware.
-- Slows time by 30% for 18 sec.
-- Increase any damage dealt by 15% when Sandevistan is active.
-- Increase Crit Chance by 20% and Crit Damage by 35% when Sandevistan is active.
-- Cooldown 60 sec.
{
id = "Items.SandevistanC4MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- MILITECH BERSERK MK.5 / Cyberware / Operating System / Legendary
-- The only official Berserk implant from Militech available on the market, but an exceptionally fine one at that. Its genius lies in being nanopowered, making it highly suited for regenerative purposes.
-- When activated, ranged weapon recoil and sway -15%, melee damage +15% and Armor +10% for 10 seconds.
-- Max health and stamina +40%, defeating enemies restores 5% health.
-- Cooldown 60 seconds.
{
id = "Items.BerserkC4MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- NETWATCH NETDRIVER MK.5 / Cyberware / Operating System / Legendary
-- A cyberdeck series used by the best NetWatch agents and a frightening beast in terms of its offensive capabilities. It's best if NetWatch didn't catch you using this.
-- Allows yout to preform quickhacks on targets and devices while scanning.
-- Offensive quickhacks can be uploaded to 3 targets within a 6-meter radius.
-- Increases damage dealt by quickhacks by 30%.
-- Increases cyberdeck RAM recovery rare by 9 unit(s) per 60 sec.
-- Increases quickhack spread distance by 60%.
{
id = "Items.NetwatchNetdriverLegendaryMKV",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
{ slot = "Program6" },
},
},
-- QIANT "WARP DANCER" SANDEVISTAN MK.5 / Cyberware / Operating System / Legendary
-- QianT's pride and joy - the company's latest Sandevistan model has already reached a legendary status with its astounding craftsmanship and precision, while its artificial neural network-powered software is virtually unmatched in the market.
-- Slows time by 10% for 8 sec.
-- Increase any damage dealt by 15% when Sandevistan is active.
-- Increase Crit Chance by 10% and Crit Damage by 50% when Sandevistan is active.
-- Cooldown 30 sec.
{
id = "Items.SandevistanC3MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- ZETATECH BERSERK MK.5 / Cyberware / Operating System / Legendary
-- A true work of beauty from Zetatech - one of the most potent and most valuable Berserk implants on the market. Many private security companies allegedly outfit their mercenaries with this very model.
-- When activated, reduces weapon recoil and increases melee damage, Armor, Resistances by 20% for 10 seconds.
-- While active, defeating enemies restores 5% health and jumping from a high height create a Shockwave.
-- Cooldown 30 seconds.
-- 3 Mod Slots.
{
id = "Items.BerserkC3MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
},
} |
local cfg = {}
-- paycheck and bill for users
cfg.message_paycheck = "Você recebeu seu salario: R$~g~" -- message that will show before payment of salary
cfg.message_bill = "Pagamento de contas: R$~r~" -- message that will show before payment of bill
cfg.post = "." -- message that will show after payment
cfg.bank = true -- if true money goes to bank, false goes to wallet
cfg.minutes_paycheck = 30 -- minutes between payment for paycheck
cfg.minutes_bill = 30 -- minutes between withdrawal for bill
cfg.paycheck_title_picture = "Banco do Brasil" -- define title for paycheck notification picture
cfg.paycheck_picture = "CHAR_BANK_MAZE" -- define paycheck notification picture want's to display
cfg.bill_title_picture = "Companhia de Seguro" -- define title for bill notification picture
cfg.bill_picture = "CHAR_MP_MORS_MUTUAL" -- define bill notificatiosn picture want's to display
cfg.paycheck = { -- ["permission"] = paycheck
--[""] = 0,
["colonel.paycheck"] = 17200,
["tenent-colonel.paycheck"] = 14000,
["major.paycheck"] = 12000,
["capitain.paycheck"] = 10000,
["first-tenent.paycheck"] = 9550,
["second-tenentTenente.paycheck"] = 9000,
["sub-tenent.paycheck"] = 7900,
["first-sargeant.paycheck"] = 7000,
["second-sargeant.paycheck"] = 6000,
["third-sargeant.paycheck"] = 5300,
["cabo.paycheck"] = 4800,
["soldier.paycheck"] = 4500,
["recruit.payceck"] = 2800,
["chefe.paycheck"] = 8000,
["samu.paycheck"] = 3500,
["taxi.paycheck"] = 1300,
["repair.paycheck"] = 1800,
["bankdriver.paycheck"] = 1650,
["diretorchefe.paycheck"] = 1650,
["delivery.paycheck"] = 1700,
["player.paycheck"] = 150,
["sedex.paycheck"] = 2200
}
cfg.bill = { -- ["permission"] = withdrawal
--[""] = 0,
["colonel.paycheck"] = 2200,
["tenent-colonel.paycheck"] = 1400,
["major.paycheck"] = 1300,
["captain.paycheck"] = 1200,
["first-tenent.paycheck"] = 1100,
["second-tenentTenente.paycheck"] = 1000,
["sub-tenent.paycheck"] = 900,
["first-sargeant.paycheck"] = 800,
["second-sargeant.paycheck"] = 700,
["third-sargeant.paycheck"] = 600,
["cabo.paycheck"] = 500,
["soldier.paycheck"] = 400,
["recruit.paceck"] = 300,
["chefe.paycheck"] = 1000,
["samu.paycheck"] = 300,
["taxi.paycheck"] = 100,
["repair.paycheck"] = 350,
["bankdriver.paycheck"] = 150,
["diretorchefe.paycheck"] = 150,
["delivery.paycheck"] = 280,
["sedex.paycheck"] = 150,
["player.paycheck"] = 0
}
return cfg
|
-----------------------------------------------
-- detail.lua
-- Represents a detail when it is in the world
-- Created by HazardousPeach
-----------------------------------------------
local game = require 'game'
local collision = require 'hawk/collision'
local Item = require 'items/item'
local utils = require 'utils'
local Detail = {}
Detail.__index = Detail
Detail.isDetail = true
---
-- Creates a new detail object
-- @return the detail object created
function Detail.new(node, collider)
local detail = {}
setmetatable(detail, Detail)
detail.name = node.name
detail.type = 'detail'
local category = node.properties.category or 'recipe'
detail.image = love.graphics.newImage('images/details/'..category..'.png') -- category can be quest or recipe
detail.image_q = love.graphics.newQuad( 0, 0, 24, 24, detail.image:getDimensions() )
detail.foreground = node.properties.foreground
detail.collider = collider
detail.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
detail.bb.node = detail
collider:setSolid(detail.bb)
collider:setPassive(detail.bb)
detail.position = {x = node.x, y = node.y}
detail.velocity = {x = 0, y = 0}
detail.width = node.width
detail.height = node.height
detail.bb_offset_x = (24 - node.width) / 2 -- positions bb for details smaller than 24px
detail.touchedPlayer = nil
detail.exists = true
detail.dropping = false
return detail
end
---
-- Draws the detail to the screen
-- @return nil
function Detail:draw()
if not self.exists then
return
end
love.graphics.draw(self.image, self.image_q, self.position.x, self.position.y)
end
function Detail:keypressed( button, player )
if button ~= 'INTERACT' then return end
local itemNode = utils.require( 'items/details/' .. self.name )
itemNode.type = 'detail'
local item = Item.new(itemNode, self.quantity)
local callback = function()
self.exists = false
self.containerLevel:saveRemovedNode(self)
self.containerLevel:removeNode(self)
self.collider:remove(self.bb)
end
player.inventory:addItem(item, true, callback)
end
---
-- Called when the detail begins colliding with another node
-- @return nil
function Detail:collide(node, dt, mtv_x, mtv_y)
if node and node.character then
self.touchedPlayer = node
end
end
---
-- Called when the detail finishes colliding with another node
-- @return nil
function Detail:collide_end(node, dt)
if node and node.character then
self.touchedPlayer = nil
end
end
---
-- Updates the detail and allows the player to pick it up.
function Detail:update(dt, player, map)
if not self.exists then
return
end
if self.dropping then
local nx, ny = collision.move(map, self, self.position.x, self.position.y,
self.width, self.height,
self.velocity.x * dt, self.velocity.y * dt)
self.position.x = nx
self.position.y = ny
-- X velocity won't need to change
self.velocity.y = self.velocity.y + game.gravity*dt
self.bb:moveTo(self.position.x + self.width / 2 + self.bb_offset_x, self.position.y + self.height / 2)
end
-- Item has finished dropping in the level
if not self.dropping and self.dropped and not self.saved then
self.containerLevel:saveAddedNode(self)
self.saved = true
end
end
function Detail:drop(player)
if player.footprint then
self:floorspace_drop(player)
return
end
self.dropping = true
self.dropped = true
end
function Detail:floorspace_drop(player)
self.dropping = false
self.position.y = player.footprint.y - self.height
self.bb:moveTo(self.position.x + self.width / 2 + self.bb_offset_x, self.position.y + self.height / 2)
self.containerLevel:saveAddedNode(self)
end
function Detail:floor_pushback()
if not self.exists or not self.dropping then return end
self.dropping = false
self.velocity.y = 0
self.collider:setPassive(self.bb)
end
return Detail
|
--
-- Please see the license.html file included with this distribution for
-- attribution and copyright information.
--
local sortLocked = false;
function setSortLock(isLocked)
sortLocked = isLocked;
end
function onInit()
onEncumbranceChanged();
registerMenuItem(Interface.getString("list_menu_createitem"), "insert", 5);
local node = getDatabaseNode();
DB.addHandler(DB.getPath(node, "*.isidentified"), "onUpdate", onIDChanged);
DB.addHandler(DB.getPath(node, "*.bonus"), "onUpdate", onBonusChanged);
DB.addHandler(DB.getPath(node, "*.ac"), "onUpdate", onArmorChanged);
DB.addHandler(DB.getPath(node, "*.maxstatbonus"), "onUpdate", onArmorChanged);
DB.addHandler(DB.getPath(node, "*.checkpenalty"), "onUpdate", onArmorChanged);
DB.addHandler(DB.getPath(node, "*.spellfailure"), "onUpdate", onArmorChanged);
DB.addHandler(DB.getPath(node, "*.speed20"), "onUpdate", onArmorChanged);
DB.addHandler(DB.getPath(node, "*.speed30"), "onUpdate", onArmorChanged);
DB.addHandler(DB.getPath(node, "*.carried"), "onUpdate", onCarriedChanged);
DB.addHandler(DB.getPath(node, "*.weight"), "onUpdate", onEncumbranceChanged);
DB.addHandler(DB.getPath(node, "*.count"), "onUpdate", onEncumbranceChanged);
DB.addHandler(DB.getPath(node), "onChildDeleted", onEncumbranceChanged);
end
function onClose()
local node = getDatabaseNode();
DB.removeHandler(DB.getPath(node, "*.isidentified"), "onUpdate", onIDChanged);
DB.removeHandler(DB.getPath(node, "*.bonus"), "onUpdate", onBonusChanged);
DB.removeHandler(DB.getPath(node, "*.ac"), "onUpdate", onArmorChanged);
DB.removeHandler(DB.getPath(node, "*.maxstatbonus"), "onUpdate", onArmorChanged);
DB.removeHandler(DB.getPath(node, "*.checkpenalty"), "onUpdate", onArmorChanged);
DB.removeHandler(DB.getPath(node, "*.spellfailure"), "onUpdate", onArmorChanged);
DB.removeHandler(DB.getPath(node, "*.speed20"), "onUpdate", onArmorChanged);
DB.removeHandler(DB.getPath(node, "*.speed30"), "onUpdate", onArmorChanged);
DB.removeHandler(DB.getPath(node, "*.carried"), "onUpdate", onCarriedChanged);
DB.removeHandler(DB.getPath(node, "*.weight"), "onUpdate", onEncumbranceChanged);
DB.removeHandler(DB.getPath(node, "*.count"), "onUpdate", onEncumbranceChanged);
DB.removeHandler(DB.getPath(node), "onChildDeleted", onEncumbranceChanged);
end
function onMenuSelection(selection)
if selection == 5 then
addEntry(true);
end
end
function onIDChanged(nodeField)
local nodeItem = DB.getChild(nodeField, "..");
if (DB.getValue(nodeItem, "carried", 0) == 2) and ItemManager2.isArmor(nodeItem) then
CharManager.calcItemArmorClass(DB.getChild(nodeItem, "..."));
end
end
function onBonusChanged(nodeField)
local nodeItem = DB.getChild(nodeField, "..");
if (DB.getValue(nodeItem, "carried", 0) == 2) and ItemManager2.isArmor(nodeItem) then
CharManager.calcItemArmorClass(DB.getChild(nodeItem, "..."));
end
end
function onArmorChanged(nodeField)
local nodeItem = DB.getChild(nodeField, "..");
if (DB.getValue(nodeItem, "carried", 0) == 2) and ItemManager2.isArmor(nodeItem) then
CharManager.calcItemArmorClass(DB.getChild(nodeItem, "..."));
end
end
function onCarriedChanged(nodeField)
local nodeChar = DB.getChild(nodeField, "....");
if nodeChar then
local nodeItem = DB.getChild(nodeField, "..");
local nCarried = nodeField.getValue();
local sCarriedItem = StringManager.trim(ItemManager.getDisplayName(nodeItem)):lower();
if sCarriedItem ~= "" then
for _,vNode in pairs(DB.getChildren(nodeChar, "inventorylist")) do
if vNode ~= nodeItem then
local sLoc = StringManager.trim(DB.getValue(vNode, "location", "")):lower();
if sLoc == sCarriedItem then
DB.setValue(vNode, "carried", "number", nCarried);
end
end
end
end
if ItemManager2.isArmor(nodeItem) then
CharManager.calcItemArmorClass(nodeChar);
end
end
onEncumbranceChanged();
end
function onEncumbranceChanged()
if CharManager.updateEncumbrance then
CharManager.updateEncumbrance(window.getDatabaseNode());
end
end
function onListChanged()
update();
updateContainers();
end
function update()
local bEditMode = (window.inventorylist_iedit.getValue() == 1);
window.idelete_header.setVisible(bEditMode);
for _,w in ipairs(getWindows()) do
w.idelete.setVisibility(bEditMode);
end
end
function addEntry(bFocus)
local w = createWindow();
if w then
if bFocus then
w.name.setFocus();
end
end
return w;
end
function onClickDown(button, x, y)
return true;
end
function onClickRelease(button, x, y)
if not getNextWindow(nil) then
addEntry(true);
end
return true;
end
function onSortCompare(w1, w2)
if sortLocked then
return false;
end
return ItemManager.onInventorySortCompare(w1, w2);
end
function updateContainers()
ItemManager.onInventorySortUpdate(self);
end
function onDrop(x, y, draginfo)
return ItemManager.handleAnyDrop(window.getDatabaseNode(), draginfo);
end
|
local Tileset = Class()
function Tileset:init(data, path)
self.id = data.id
self.name = data.name
self.tile_count = data.tilecount or 0
self.tile_width = data.tilewidth or 40
self.tile_height = data.tileheight or 40
self.margin = data.margin or 0
self.spacing = data.spacing or 0
self.columns = data.columns or 0
self.tile_info = {}
for _,v in ipairs(data.tiles or {}) do
local info = {}
if v.animation then
info.animation = {duration = 0, frames={}}
for _,anim in ipairs(v.animation) do
table.insert(info.animation.frames, {id = anim.tileid, duration = anim.duration / 1000})
info.animation.duration = info.animation.duration + (anim.duration / 1000)
end
end
self.tile_info[v.id] = info
end
self.texture = Assets.getTexture(Utils.absoluteToLocalPath("assets/sprites/", data.image, path))
self.quads = {}
if self.texture then
local tw, th = self.texture:getWidth(), self.texture:getHeight()
for i = 0, self.tile_count-1 do
local tx = self.margin + (i % self.columns) * (self.tile_width + self.spacing)
local ty = self.margin + math.floor(i / self.columns) * (self.tile_height + self.spacing)
self.quads[i] = love.graphics.newQuad(tx, ty, self.tile_width, self.tile_height, tw, th)
end
end
end
function Tileset:getAnimation(id)
local info = self.tile_info[id]
return info and info.animation
end
function Tileset:drawTile(id, x, y, ...)
local draw_id = id
local info = self.tile_info[id]
if info and info.animation then
local time = love.timer.getTime()
local pos = time % info.animation.duration
local total_duration = 0
for _,frame in ipairs(info.animation.frames) do
draw_id = frame.id
if pos < total_duration + frame.duration then
break
end
total_duration = total_duration + frame.duration
end
end
love.graphics.draw(self.texture, self.quads[draw_id], x or 0, y or 0, ...)
end
return Tileset |
-----------------------------------------------------------------------------
-- Name: plugin_interface.lua
-- Purpose: Plugin Interface library project script.
-- Author: Andrea Zanellato zanellato.andrea@gmail.com
-- Modified by:
-- Created: 2011/10/20
-- Copyright: (c) wxFormBuilder Team
-- Licence: GNU General Public License Version 2
-----------------------------------------------------------------------------
project "plugin-interface"
kind "StaticLib"
files
{
"../../sdk/plugin_interface/**.h",
"../../sdk/plugin_interface/**.cpp",
"../../sdk/plugin_interface/**.fbp"
}
includedirs {"../../sdk/tinyxml"}
targetdir "../../sdk/lib"
flags {"ExtraWarnings"}
defines {"TIXML_USE_TICPP"}
targetsuffix ( "-" .. wxVersion )
if wxArchitecture then
buildoptions {"-arch " .. wxArchitecture}
end
configuration "not windows"
buildoptions {"-fPIC"}
-- Visual C++ 2005/2008
configuration "vs*"
defines {"_CRT_SECURE_NO_DEPRECATE"}
configuration "Debug"
targetname ( CustomPrefix .. wxDebugSuffix .. "_plugin-interface" )
wx_config { Debug="yes", WithoutLibs="yes" }
configuration "Release"
buildoptions {"-fno-strict-aliasing"}
targetname ( CustomPrefix .. "_plugin-interface" )
wx_config { WithoutLibs="yes" }
|
object_intangible_pet_beast_master_bm_snorbal_mount = object_intangible_pet_beast_master_shared_bm_snorbal_mount:new {
}
ObjectTemplates:addTemplate(object_intangible_pet_beast_master_bm_snorbal_mount, "object/intangible/pet/beast_master/bm_snorbal_mount.iff")
|
local array = require "util.array";
describe("util.array", function ()
describe("creation", function ()
describe("from table", function ()
it("works", function ()
local a = array({"a", "b", "c"});
assert.same({"a", "b", "c"}, a);
end);
end);
describe("from iterator", function ()
it("works", function ()
-- collects the first value, ie the keys
local a = array(ipairs({true, true, true}));
assert.same({1, 2, 3}, a);
end);
end);
describe("collect", function ()
it("works", function ()
-- collects the first value, ie the keys
local a = array.collect(ipairs({true, true, true}));
assert.same({1, 2, 3}, a);
end);
end);
end);
describe("metatable", function ()
describe("operator", function ()
describe("addition", function ()
it("works", function ()
local a = array({ "a", "b" });
local b = array({ "c", "d" });
assert.same({"a", "b", "c", "d"}, a + b);
end);
end);
describe("equality", function ()
it("works", function ()
local a1 = array({ "a", "b" });
local a2 = array({ "a", "b" });
local b = array({ "c", "d" });
assert.truthy(a1 == a2);
assert.falsy(a1 == b);
assert.falsy(a1 == { "a", "b" }, "Behavior of metatables changed in Lua 5.3");
end);
end);
describe("division", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
local b = a / function (i) if i ~= "b" then return i .. "x" end end;
assert.same({ "ax", "cx" }, b);
end);
end);
end);
end);
describe("methods", function ()
describe("map", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
local b = a:map(string.upper);
assert.same({ "A", "B", "C" }, b);
end);
end);
describe("filter", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
a:filter(function (i) return i ~= "b" end);
assert.same({ "a", "c" }, a);
end);
end);
describe("sort", function ()
it("works", function ()
local a = array({ 5, 4, 3, 1, 2, });
a:sort();
assert.same({ 1, 2, 3, 4, 5, }, a);
end);
end);
describe("unique", function ()
it("works", function ()
local a = array({ "a", "b", "c", "c", "a", "b" });
a:unique();
assert.same({ "a", "b", "c" }, a);
end);
end);
describe("pluck", function ()
it("works", function ()
local a = array({ { a = 1, b = -1 }, { a = 2, b = -2 }, });
a:pluck("a");
assert.same({ 1, 2 }, a);
end);
end);
describe("reverse", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
a:reverse();
assert.same({ "c", "b", "a" }, a);
end);
end);
-- TODO :shuffle
describe("append", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
a:append(array({ "d", "e", }));
assert.same({ "a", "b", "c", "d", "e" }, a);
end);
end);
describe("push", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
a:push("d"):push("e");
assert.same({ "a", "b", "c", "d", "e" }, a);
end);
end);
describe("pop", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
assert.equal("c", a:pop());
assert.same({ "a", "b", }, a);
end);
end);
describe("concat", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
assert.equal("a,b,c", a:concat(","));
end);
end);
describe("length", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
assert.equal(3, a:length());
end);
end);
describe("slice", function ()
it("works", function ()
local a = array({ "a", "b", "c" });
assert.equal(array.slice(a, 1, 2), array{ "a", "b" });
assert.equal(array.slice(a, 1, 3), array{ "a", "b", "c" });
assert.equal(array.slice(a, 2, 3), array{ "b", "c" });
assert.equal(array.slice(a, 2), array{ "b", "c" });
assert.equal(array.slice(a, -4), array{ "a", "b", "c" });
assert.equal(array.slice(a, -3), array{ "a", "b", "c" });
assert.equal(array.slice(a, -2), array{ "b", "c" });
assert.equal(array.slice(a, -1), array{ "c" });
end);
it("can mutate", function ()
local a = array({ "a", "b", "c" });
assert.equal(a:slice(-1), array{"c"});
assert.equal(a, array{"c"});
end);
end);
end);
-- TODO The various array.foo(array ina, array outa) functions
end);
|
Talk(6, "魔教妖邪,来我峨嵋山有何贵事.", "talkname6", 0);
Talk(0, "上回看你手中那把宝剑,寒芒吞吐,电闪星飞,想必就是传说中的”倚天剑”?小侠我想向你借来用用.", "talkname0", 1);
Talk(6, "光明顶上被你侥幸获胜,你现在还敢来我峨嵋撒野,莫非真视我峨嵋无人.", "talkname6", 0);
if AskBattle() == true then goto label0 end;
Talk(0, "那里,那里.我只不过是来劝师太,与明教间的事能和就和.自古以来冤家宜解不宜结.", "talkname0", 1);
Talk(6, "阁下未免管的太多了吧,难道你真以为你是”武林盟主”吗!", "talkname6", 0);
do return end;
::label0::
if TryBattle(20) == true then goto label1 end;
Dead();
do return end;
::label1::
LightScence();
Talk(0, "宝剑还是应该配英雄,怎样?师太,这”倚天剑”可以让给我了吧.", "talkname0", 1);
Talk(6, "魔教妖孽,想从我灭绝手中拿走倚天剑,等下辈子吧!", "talkname6", 0);
PlayAnimation(2, 5468, 5496);--by fanyu|播放动画。场景33-2
ModifyEvent(-2, -2, -2, -2, 149, -1, -1, 5238, 5238, 5238, -2, -2, -2);--by fanyu|启动脚本-149,改变贴图。场景33-2
Talk(77, "师父,师父!", "talkname77", 0);
Talk(0, "师太,师太!何苦如此呢?若真不想给我,跟我说一声就行了.唉!", "talkname0", 1);
Talk(6, "魔教的淫徒,你若玷污了我爱徒们的清白,我做鬼也不饶过........你!", "talkname6", 0);
Talk(77, "师父,师父!可恶的魔教妖邪,替我师父尝命来.", "talkname77", 0);
if TryBattle(21) == true then goto label2 end;
Dead();
do return end;
::label2::
LightScence();
ModifyEvent(-2, 3, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-3
ModifyEvent(-2, 4, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-4
ModifyEvent(-2, 5, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-5
ModifyEvent(-2, 6, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-6
ModifyEvent(-2, 7, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-7
ModifyEvent(-2, 8, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-8
ModifyEvent(-2, 9, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-9
ModifyEvent(-2, 10, -2, -2, 151, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-151。场景33-10
AddEthics(-5);
AddRepute(8);
do return end;
|
class("MetaCharacterTacticsRequestCommand", pm.SimpleCommand).execute = function (slot0, slot1)
print("63313 request tactics info")
pg.ConnectionMgr.GetInstance():Send(63313, {
ship_id = slot1:getBody().id
}, 63314, function (slot0)
print("63314 requset success")
slot1 = {}
slot2 = ipairs
slot3 = slot0.tasks or {}
for slot5, slot6 in slot2(slot3) do
if not slot1[slot6.skill_id] then
slot1[slot7] = {}
end
table.insert(slot1[slot7], {
taskID = slot6.task_id,
finishCount = slot6.finish_cnt
})
end
slot2 = {}
slot3 = ipairs
slot4 = slot0.skill_exp or {}
for slot6, slot7 in slot3(slot4) do
slot2[slot7.skill_id] = slot7.exp
print("skill", slot7.skill_id, slot7.exp)
end
getProxy(MetaCharacterProxy):setMetaTacticsInfo(slot0)
slot0:sendNotification(GAME.TACTICS_META_INFO_REQUEST_DONE, {
shipID = slot0.ship_id,
doubleExp = slot0.double_exp,
normalExp = slot0.exp,
curSkillID = slot0.skill_id or 0,
switchCount = slot0.switch_cnt,
taskInfoTable = slot1,
skillExpTable = slot2
})
end)
end
return class("MetaCharacterTacticsRequestCommand", pm.SimpleCommand)
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
windranger_focus_fire_lua = class({})
LinkLuaModifier( "modifier_windranger_focus_fire_lua", "lua_abilities/windranger_focus_fire_lua/modifier_windranger_focus_fire_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Ability Start
function windranger_focus_fire_lua:OnSpellStart()
-- unit identifier
local caster = self:GetCaster()
local target = self:GetCursorTarget()
-- cancel if linken
if target:TriggerSpellAbsorb( self ) then return end
-- load data
local duration = self:GetDuration()
-- this version of Focus Fire allows multiple target
-- check existing modifiers
local found = false
local modifiers = caster:FindAllModifiersByName( "modifier_windranger_focus_fire_lua" )
for _,modifier in pairs(modifiers) do
if modifier.target==target then
-- if already exist for current target, refresh
modifier:ForceRefresh()
found = true
break
end
end
if not found then
-- get entindex
local ent = target:entindex()
-- add modifier to new targets
caster:AddNewModifier(
caster, -- player source
self, -- ability source
"modifier_windranger_focus_fire_lua", -- modifier name
{
duration = duration,
target = ent,
} -- kv
)
end
-- Play effects
local sound_cast = "Ability.Focusfire"
EmitSoundOn( sound_cast, caster )
end |
local getEnemyTeam = { RED = "BLUE", BLUE = "RED" }
local blipColors = { RED = {255,0,0}, BLUE = {0,0,255} }
local playerBlips = {}
local blipInfo = {}
--Setup our playerblips
addEventHandler ( "onClientPlayerSpawn", root,
function()
if isElement ( playerBlips[source] ) then
destroyElement ( playerBlips[source] )
end
playerBlips[source] = createBlip ( 0, 0, 0, 0, 2, 255, 0, 0, 0 )
attachElements ( playerBlips[source], source )
end
)
addEventHandler ( "onClientPlayerQuit", root,
function()
destroyElement ( playerBlips[source] )
playerBlips[source] = nil
end
)
addEventHandler ( "onClientPlayerWasted", root,
function()
destroyElement ( playerBlips[source] )
playerBlips[source] = nil
end
)
---
function updateRemoteSoundLevels ()
local localTeam = getPlayerTeam ( thisplayer )
if not localTeam then return end
local localTeamName = getTeamName(localTeam)
local enemyTeam = getTeamFromName( getEnemyTeam[localTeamName] )
local enemyTeamName = getEnemyTeam[localTeamName]
--
for i,player in ipairs(getElementsByType"player") do
local soundlevel = getElementData ( player, "noiselevel" )
local playerTeam = getPlayerTeam(player)
if ( playerTeam ) then
local teamName = getTeamName ( playerTeam )
--Sort out our nametags
if playerTeam == localTeam then
setPlayerNametagShowing(player,true)
if isElement ( playerBlips[player] ) then
if soundlevel == 0 then
setBlipColor ( playerBlips[player], blipColors[teamName][1],blipColors[teamName][2],blipColors[teamName][3], 255 )
setBlipSize ( playerBlips[player], 1 )
else
setBlipSize ( playerBlips[player], 2 )
setBlipColor ( playerBlips[player], blipColors[teamName][1],blipColors[teamName][2],blipColors[teamName][3], 255*(soundlevel/10) )
end
end
else
if soundlevel == 0 then
setPlayerNametagShowing(player,false)
else
setPlayerNametagShowing(player,true)
end
if isElement ( playerBlips[player] ) then
setBlipColor ( playerBlips[player], blipColors[teamName][1],blipColors[teamName][2],blipColors[teamName][3], 255*(soundlevel/10) )
end
end
end
end
end
function table.find ( theTable, value )
for i,v in pairs(theTable) do
if v == value then
return
end
end
return false
end
function destroyBlipsAttachedTo(player)
if not isElement(player) then return false end
--
local attached = getAttachedElements ( player )
if not attached then return false end
for k,element in ipairs(attached) do
if getElementType ( element ) == "blip" then
destroyElement ( element )
end
end
return true
end
|
include("shared.lua")
function ENT:Initialize()
self.speed = 1
self.particleSys = ParticleEmitter(self:GetPos(), true)
end
function ENT:Draw()
if not self:GetIsActive() then return end
self:DrawModel()
end
function ENT:Think()
if not self:GetIsActive() then return end
if not LocalPlayer():IsLineOfSightClear(self) then return end
self.speed = (5000 * FrameTime())
self:SetAngles(self:GetAngles() + (Angle(0, self.speed, 0) * FrameTime()))
if LocalPlayer():GetPos():Distance(self:GetPos()) > 600 then return end
local part = self.particleSys:Add("color", self:GetPos())
part:SetDieTime(3)
part:SetVelocity(Vector(math.random(-100, 50),math.random(-100, 50),math.random(1, 200)))
part:SetColor(math.random(50, 255), math.random(50, 255), math.random(50, 255))
part:SetStartSize(3)
part:SetAngleVelocity(Angle(math.random(-500, 500),math.random(-500,500),math.random(-500,500)))
part:SetEndSize(10)
part:SetBounce(0.8)
part:SetCollide(true)
part:SetGravity(Vector(0,0, -500))
end |
package.path = './spec/?.lua;../lua/?.lua;'..package.path
local path = require "path"
local utils = require "utils"
local LUA, ARGS = utils.lua_args(arg)
local PATH = path.fullpath(".")
local DATE_PAT = "%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d"
local TESTDIR = ".test_log"
local function exec_file(file)
assert(path.isfile(file))
return utils.exec(PATH, LUA, '%s', path.quote(file))
end
local function exec_code(src)
local tmpfile = assert(path.tmpname())
local f = assert(utils.write_file(tmpfile, src))
local a, b, c = exec_file(tmpfile)
path.remove(tmpfile)
return a, b, c
end
do local s = require("say")
local function is_match(state, arguments)
local pat, str = arguments[1], arguments[2]
if type(pat) ~= "string" and type(str) ~= "string" then
return false
end
return (not not string.match(str, pat))
end
s:set("assertion.match.positive", "String `%s` expected match to \n`%s`")
s:set("assertion.match.negative", "String\n`%s` not expected match to \n`%s`")
assert:register("assertion", "match", is_match, "assertion.match.positive", "assertion.match.negative")
end
describe("writers", function()
it('basic format', function()
local ok, status, msg = exec_code[[
local LOG = require"log".new('trace',
require "log.writer.stdout".new()
)
LOG.emerg("can not allocate memory")
LOG.alert("can not allocate memory")
LOG.fatal("can not allocate memory")
LOG.error("file not found")
LOG.warning("cache server is not started")
LOG.notice("message has 2 file")
LOG.info("new message is received")
LOG.debug("message has 2 file")
LOG.trace("message has 2 file")
]]
assert.True(ok, msg)
assert.match(DATE_PAT .. " %[EMERG%] can not allocate memory", msg)
assert.match(DATE_PAT .. " %[ALERT%] can not allocate memory", msg)
assert.match(DATE_PAT .. " %[FATAL%] can not allocate memory", msg)
assert.match(DATE_PAT .. " %[ERROR%] file not found", msg)
assert.match(DATE_PAT .. " %[WARNING%] cache server is not started", msg)
assert.match(DATE_PAT .. " %[NOTICE%] message has 2 file", msg)
assert.match(DATE_PAT .. " %[INFO%] new message is received", msg)
assert.match(DATE_PAT .. " %[DEBUG%] message has 2 file", msg)
assert.match(DATE_PAT .. " %[TRACE%] message has 2 file", msg)
end)
it('level', function()
local ok, status, msg = exec_code[[
local LOG = require"log".new('notice',
require "log.writer.stdout".new()
)
LOG.emerg("can not allocate memory")
LOG.alert("can not allocate memory")
LOG.fatal("can not allocate memory")
LOG.error("file not found")
LOG.warning("cache server is not started")
LOG.notice("message has 2 file")
LOG.info("new message is received")
LOG.debug("message has 2 file")
LOG.trace("message has 2 file")
]]
assert.True(ok, msg)
assert.match (DATE_PAT .. " %[EMERG%] can not allocate memory", msg)
assert.match (DATE_PAT .. " %[ALERT%] can not allocate memory", msg)
assert.match (DATE_PAT .. " %[FATAL%] can not allocate memory", msg)
assert.match (DATE_PAT .. " %[ERROR%] file not found", msg)
assert.match (DATE_PAT .. " %[WARNING%] cache server is not started", msg)
assert.match (DATE_PAT .. " %[NOTICE%] message has 2 file", msg)
assert.not_match(DATE_PAT .. " %[INFO%] new message is received", msg)
assert.not_match(DATE_PAT .. " %[DEBUG%] message has 2 file", msg)
assert.not_match(DATE_PAT .. " %[TRACE%] message has 2 file", msg)
end)
it('formatter', function()
local ok, status, msg = exec_code[[
local writer = require "log.writer.stdout".new()
local LOG = require"log".new(writer,
require "log.formatter.concat".new(':')
)
local LOG_FMT = require"log".new(writer,
require "log.formatter.format".new()
)
LOG.info('new', 'message', 'is', 'received')
LOG_FMT.notice("message has %d %s", 2, 'file')
]]
assert.True(ok, msg)
assert.match('new:message:is:received', msg)
assert.match('message has 2 file', msg)
end)
it('async_zmq', function()
local ok, status, msg = exec_code[[
local ztimer = require "lzmq.timer"
local writer = require "log.writer.async.zmq".new('inproc://async.logger',
"return require 'log.writer.stdout'.new()"
)
ztimer.sleep(500)
local LOG = require"log".new(writer)
ztimer.sleep(500)
LOG.fatal("can not allocate memory")
ztimer.sleep(5000)
require "lzmq.threads".context():destroy()
ztimer.sleep(5000)
]]
assert.True(ok, msg)
assert.match('can not allocate memory', msg)
end)
it('async_udp', function()
local ok, status, msg = exec_code[[
local writer = require "log.writer.async.udp".new('127.0.0.1', '5555',
"return require 'log.writer.stdout'.new()"
)
local LOG = require"log".new(writer)
LOG.fatal("can not allocate memory")
require 'lzmq.timer'.sleep(1000)
]]
assert.True(ok, msg)
assert.match('can not allocate memory', msg)
end)
if _G.jit then pending"FIXME: makes LuaLane work with LuaJIT"
else it('async_lane', function()
local ok, status, msg = exec_code[[
local writer = require "log.writer.async.lane".new('lane.logger',
"return require 'log.writer.stdout'.new()"
)
local LOG = require"log".new(writer)
LOG.fatal("can not allocate memory")
require 'lzmq.timer'.sleep(1000)
]]
assert.True(ok, msg)
assert.match('can not allocate memory', msg)
end) end
it('async_proxy', function()
local ok, status, msg = exec_code[[
local zthreads = require "lzmq.threads"
local ztimer = require 'lzmq.timer'
-- create log thread
local LOG = require"log".new(
require "log.writer.async.zmq".new('inproc://async.logger',
"return require 'log.writer.stdout'.new()"
)
)
ztimer.sleep(500)
-- log from separate thread via proxy
local Thread = function()
local LOG = require"log".new(
require "log.writer.async.zmq".new('inproc://async.logger')
)
LOG.error("(Thread) file not found")
end
local child_thread = zthreads.xrun(Thread):start()
ztimer.sleep(500)
LOG.fatal("can not allocate memory")
child_thread:join()
ztimer.sleep(5000)
zthreads.context():destroy()
ztimer.sleep(1500)
]]
assert.True(ok, msg)
assert.match('can not allocate memory', msg)
assert.match('%(Thread%) file not found', msg)
end)
it('async_filter_le', function()
local ok, status, msg = exec_code[[
local writer = require 'log.writer.stdout'.new()
local Filter = require "log.writer.filter"
local LOG = require"log".new(
Filter.new('warning', writer)
)
LOG.fatal("can not allocate memory")
LOG.warning("cache server is not started")
LOG.info("new message is received")
require 'lzmq.timer'.sleep(1000)
]]
assert.True(ok, msg)
assert.match('can not allocate memory', msg)
assert.match('cache server is not started', msg)
assert.not_match('new message is received', msg)
end)
it('async_filter_eq', function()
local ok, status, msg = exec_code[[
local writer = require 'log.writer.stdout'.new()
local Filter = require "log.writer.filter.lvl.eq"
local LOG = require"log".new(
Filter.new('warning', writer)
)
LOG.fatal("can not allocate memory")
LOG.warning("cache server is not started")
LOG.info("new message is received")
require 'lzmq.timer'.sleep(1000)
]]
assert.True(ok, msg)
assert.not_match('can not allocate memory', msg)
assert.match('cache server is not started', msg)
assert.not_match('new message is received', msg)
end)
it('formatter_mix', function()
local ok, status, msg = exec_code[[
local LOG = require"log".new('trace',
require "log.writer.stdout".new(),
require "log.formatter.mix".new()
)
LOG.emerg("can not allocate memory")
LOG.alert(function(str) return str end, "can not allocate memory")
LOG.fatal("can not allocate %s", "memory")
]]
assert.True(ok, msg)
assert.match(DATE_PAT .. " %[EMERG%] can not allocate memory", msg)
assert.match(DATE_PAT .. " %[ALERT%] can not allocate memory", msg)
assert.match(DATE_PAT .. " %[FATAL%] can not allocate memory", msg)
end)
end) |
--------------------Made by TobyPlowy-----------------------
minetest.register_node('ruins:old_skeleton', {
description = 'Old Skeleton',
drawtype = 'mesh',
mesh = 'decoblocks_old_skeleton.obj',
tiles = {name='decoblocks_old_skeleton.png'},
visual_scale = 0.5,
groups = {cracky=2, oddly_breakable_by_hand=5},
paramtype = 'light',
paramtype2 = 'facedir',
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
collision_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
})
minetest.register_node('ruins:old_skeleton2', {
description = 'Old Skeleton',
drawtype = 'mesh',
mesh = 'decoblocks_old_skeleton2.obj',
tiles = {name='decoblocks_old_skeleton.png'},
visual_scale = 0.5,
groups = {cracky=2, oddly_breakable_by_hand=5},
paramtype = 'light',
paramtype2 = "facedir",
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
collision_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
})
minetest.register_node("ruins:human_skull", {
description = "Human Skull",
drawtype = "mesh",
mesh = "human_skull.obj",
tiles = {
"human_skull.png",
},
visual_scale = 0.5,
wield_image = "skeleton_head_item.png",
wield_scale = {x=1.0, y=1.0, z=1.0},
paramtype = "light",
paramtype2 = "facedir",
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
collision_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
inventory_image = "skeleton_head_item.png",
groups = {choppy = 1, oddly_breakable_by_hand = 1},
})
minetest.register_node("ruins:carrot", {
description = "Carrot",
drawtype = "mesh",
mesh = "carrot.obj",
tiles = {
"crops.png",
},
visual_scale = 0.5,
paramtype = "light",
paramtype2 = "facedir",
inventory_image= "ws_carrot.png",
wield_image= "ws_carrot.png",
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
collision_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
groups = {choppy = 1, oddly_breakable_by_hand = 1, flora = 1, attached_node = 1},
})
minetest.register_node("ruins:melons", {
description = "Melons",
drawtype = "mesh",
mesh = "melons.obj",
tiles = {
"crops.png",
},
visual_scale = 0.5,
paramtype = "light",
paramtype2 = "facedir",
inventory_image= "ws_melons.png",
wield_image= "ws_melons.png",
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
collision_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
groups = {choppy = 1, oddly_breakable_by_hand = 1, flora = 1, attached_node = 1},
})
minetest.register_node("ruins:tomato_plant", {
description = "Tomato Plant",
drawtype = "mesh",
mesh = "tomato.obj",
tiles = {
"crops.png",
},
visual_scale = 0.5,
paramtype = "light",
paramtype2 = "facedir",
inventory_image= "ws_tomato.png",
wield_image= "ws_tomato.png",
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
collision_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0.0, 0.3}
},
groups = {choppy = 1, oddly_breakable_by_hand = 1},
})
------------------------
minetest.register_node('ruins:concrete', {
description = 'Concrete',
tiles = {name='ws_concrete.png'},
groups = {cracky=3},
paramtype = 'light',
paramtype2 = 'facedir',
})
minetest.register_node('ruins:brick_burnt', {
description = 'Burnt Brick',
tiles = {name='ws_brick_ruin.png'},
groups = {cracky=3},
paramtype = 'light',
paramtype2 = 'facedir',
})
minetest.register_node("ruins:block", {
description = "Block",
tiles = {"ws_burnt_stone.png",
{name = "ws_burnt_stone.png",
tileable_vertical = false}},
groups = {crumbly = 3},
})
local fdir_to_front = {
{x=0, z=1},
{x=1, z=0},
{x=0, z=-1},
{x=-1, z=0}
}
local function checkwall(pos)
local fdir = minetest.get_node(pos).param2
local second_node_x = pos.x + fdir_to_front[fdir + 1].x
local second_node_z = pos.z + fdir_to_front[fdir + 1].z
local second_node_pos = {x=second_node_x, y=pos.y, z=second_node_z}
local second_node = minetest.get_node(second_node_pos)
if not second_node or not minetest.registered_nodes[second_node.name]
or not minetest.registered_nodes[second_node.name].buildable_to then
return true
end
return false
end
local dumpster_selectbox = {-0.5, -0.5625, -0.5, 0.5, 0.5, 1.5}
local dumpster_nodebox = {
-- Main Body
{-0.4375, -0.375, -0.4375, 0.4375, 0.5, 1.4375},
-- Feet
{-0.4375, -0.5, -0.4375, -0.25, -0.375, -0.25},
{0.25, -0.5, -0.4375, 0.4375, -0.375, -0.25},
{0.25, -0.5, 1.25, 0.4375, -0.375, 1.4375},
{-0.4375, -0.5, 1.25, -0.25, -0.375, 1.4375},
-- Border
{-0.5, 0.25, -0.5, 0.5, 0.375, 1.5},
}
-- Dumpster
minetest.register_node("ruins:dumpster", {
description = "Dumpster",
paramtype = "light",
paramtype2 = "facedir",
inventory_image = "dumpster_wield.png",
tiles = {
"dumpster_top.png",
"dumpster_bottom.png",
"dumpster_side.png",
"dumpster_side.png",
"dumpster_side.png",
"dumpster_side.png"
},
drawtype = "nodebox",
selection_box = {
type = "fixed",
fixed = dumpster_selectbox,
},
node_box = {
type = "fixed",
fixed = dumpster_nodebox,
},
groups = {
cracky = 3,
oddly_breakable_by_hand = 1,
},
sounds = default and default.node_sound_metal_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec",
"size[8,9]" ..
"list[context;main;1,1;6,3;]" ..
"list[current_player;main;0,5;8,4;]"..
"listring[context;main]"..
"listring[current_player;main]"
)
meta:set_string("infotext", "Dumpster")
local inv = meta:get_inventory()
inv:set_size("main", 8*4)
end,
after_place_node = function(pos, placer, itemstack)
if checkwall(pos) then
minetest.set_node(pos, {name = "air"})
return true
end
end,
can_dig = function(pos,player)
local meta = minetest.get_meta(pos);
local inv = meta:get_inventory()
return inv:is_empty("main")
end,
on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
minetest.log("action", player:get_player_name() ..
" moves stuff in dumpster at " .. minetest.pos_to_string(pos))
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" moves stuff to dumpster at " .. minetest.pos_to_string(pos))
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" takes stuff from dumpster at " .. minetest.pos_to_string(pos))
end,
})
--[[ Dumpster craft
minetest.register_craft({
output = 'ruins:dumpster',
recipe = {
{'default:coalblock', 'default:coalblock', 'default:coalblock'},
{'default:steel_ingot', 'dye:dark_green', 'default:steel_ingot'},
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
}
})]]
|
--////////////////////////////////////////////////////////////////////////
--
-- LuaCwrap - Lua <-> C
-- Copyright (C) 2011-2021 Klaus Oberhofer. See Copyright Notice in luacwrap.h
--
-- unit tests for LuaCwrap
--
--////////////////////////////////////////////////////////////////////////
lu = require("luaunit")
luacwrap = require("luacwrap")
-- wrapper for the test struct type
testluacwrap = require("testluacwrap")
--
-- helper function to get a table as a string
-- outputs members sorted by member names
-- used for table comparison
--
local function getTable(t)
local keys = {}
for k, _ in pairs(t) do
keys[#keys+1] = k
end
table.sort(keys)
local tmp = {}
for _, k in ipairs(keys) do
local v = t[k]
tmp[#tmp+1] = type(v) .. " " .. k
end
return table.concat(tmp, ", ")
end
--
-- test suite
--
TestTESTSTRUCT = {}
--
-- test different struct creation methods
--
function TestTESTSTRUCT:testCreateTESTSTRUCT()
-- create a ne struct instance
local struct = TESTSTRUCT:new()
assert(nil ~= struct)
-- semantic of attach()
local attached = TESTSTRUCT:attach(struct)
lu.assertEquals(attached, struct)
lu.assertEquals(struct.__ptr, attached.__ptr)
-- check metatable
assert(nil ~= getmetatable(struct))
assert(getTable(getmetatable(struct)) == [[function __index, function __len, function __newindex, function __tostring, userdata getouter]])
-- check inner struct access
assert(nil ~= getmetatable(struct.inner))
assert(getTable(getmetatable(struct.inner)) == [[function __gc, function __index, function __len, function __newindex, function __tostring, userdata getouter]])
assert(1 == testluacwrap.checkInnerStructAccess(struct, struct.inner))
-- check $ref init values
-- by default references should have the value nil
assert(nil == struct.ref.value)
-- and the reserved index 0
assert(0 == struct.ref.ref)
-- access __ptr
assert("userdata" == type(struct.__ptr))
assert("userdata" == type(struct.intarray.__ptr))
assert("userdata" == type(struct.inner.__ptr))
-- access psztext member
assert("nil" == type(struct.inner.pszText))
assert(nil == struct.inner.pszText)
end
--
-- test assignment to struct members
--
function TestTESTSTRUCT:testAssignment()
local struct = TESTSTRUCT:new()
struct.u8 = 11
struct.i8 = 22
struct.u16 = 33
struct.i16 = 44
struct.u32 = 55
struct.i32 = 66
struct.ptr = "hello"
struct.chararray = "hello"
struct.intarray[1] = 10
struct.intarray[2] = 20
struct.intarray[3] = 30
struct.intarray[4] = 40
-- check assigned values
assert(struct.u8 == 11)
assert(struct.i8 == 22)
assert(struct.u16 == 33)
assert(struct.i16 == 44)
assert(struct.u32 == 55)
assert(struct.i32 == 66)
assert(struct.ptr == "hello")
assert(tostring(struct.chararray) == "hello\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
assert(struct.intarray[1] == 10)
assert(struct.intarray[2] == 20)
assert(struct.intarray[3] == 30)
assert(struct.intarray[4] == 40)
end
--
-- test references
--
function TestTESTSTRUCT:testReference()
local struct = TESTSTRUCT:new()
-- test pointer reset (reference removal)
struct.ptr = "hello2"
assert(struct.ptr == "hello2")
struct.ptr = nil
assert(struct.ptr == nil)
struct.ptr = "hello2"
assert(struct.ptr == "hello2")
struct.ptr = 0
assert(struct.ptr == nil)
end
--
-- test assignment of table to struct via set function
--
function TestTESTSTRUCT:testTableAssignment()
local struct = TESTSTRUCT:new()
-- test table assignment
struct:set{
u8 = 91,
i8 = 92,
u16 = 93,
i16 = 94,
u32 = 95,
i32 = 96,
ptr = "hello",
chararray = "hello",
intarray = { 19,
29,
39,
49,
},
}
assert(struct.u8 == 91)
assert(struct.i8 == 92)
assert(struct.u16 == 93)
assert(struct.i16 == 94)
assert(struct.u32 == 95)
assert(struct.i32 == 96)
assert(struct.ptr == "hello")
assert(tostring(struct.chararray) == "hello\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
assert(struct.intarray[1] == 19)
assert(struct.intarray[2] == 29)
assert(struct.intarray[3] == 39)
assert(struct.intarray[4] == 49)
end
--
-- test assignment of table to struct during new
--
function TestTESTSTRUCT:testNewWithTableAssignment()
-- test new with table assignment
local struct = TESTSTRUCT:new{
u8 = 91,
i8 = 92,
u16 = 93,
i16 = 94,
u32 = 95,
i32 = 96,
ptr = "hello",
chararray = "hello",
intarray = { 19,
29,
39,
49,
}
}
assert(struct.u8 == 91)
assert(struct.i8 == 92)
assert(struct.u16 == 93)
assert(struct.i16 == 94)
assert(struct.u32 == 95)
assert(struct.i32 == 96)
assert(struct.ptr == "hello")
assert(tostring(struct.chararray) == "hello\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
assert(struct.intarray[1] == 19)
assert(struct.intarray[2] == 29)
assert(struct.intarray[3] == 39)
assert(struct.intarray[4] == 49)
assert(nil == struct.inner.pszText)
-- test new with assignment from existing struct
local struct2 = TESTSTRUCT:new(struct)
assert(struct2.u8 == 91)
assert(struct2.i8 == 92)
assert(struct2.u16 == 93)
assert(struct2.i16 == 94)
assert(struct2.u32 == 95)
assert(struct2.i32 == 96)
assert(struct2.ptr == "hello")
assert(tostring(struct2.chararray) == "hello\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
assert(struct2.intarray[1] == 19)
assert(struct2.intarray[2] == 29)
assert(struct2.intarray[3] == 39)
assert(struct2.intarray[4] == 49)
assert(nil == struct2.inner.pszText)
-- test __dup() from existing struct
local struct3 = struct:__dup()
assert(struct3.u8 == 91)
assert(struct3.i8 == 92)
assert(struct3.u16 == 93)
assert(struct3.i16 == 94)
assert(struct3.u32 == 95)
assert(struct3.i32 == 96)
assert(struct3.ptr == "hello")
assert(tostring(struct3.chararray) == "hello\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
assert(struct3.intarray[1] == 19)
assert(struct3.intarray[2] == 29)
assert(struct3.intarray[3] == 39)
assert(struct3.intarray[4] == 49)
end
--
-- test member size operator
--
function TestTESTSTRUCT:testSizes()
local struct = TESTSTRUCT:new()
-- check sizes
-- assert(#struct == 88) -- depends on packing
assert(#struct.intarray == 4)
assert(#struct.chararray == 32)
assert(0 == struct.ref.ref)
assert(nil == struct.ref.value)
-- check $ref types
struct.ref = "my unique reference string"
assert(0 ~= struct.ref.ref)
assert("string" == type(struct.ref.value))
assert("my unique reference string" == struct.ref.value)
end
--
-- test attaching to a given pointer
--
function TestTESTSTRUCT:testAttach()
-- test attach
function myfunc(s)
local wrap = TESTSTRUCT:attach(s)
assert(nil ~= wrap.ptr)
assert(wrap.u8 == 8)
assert(wrap.i8 == - 8)
assert(wrap.u16 == 16)
assert(wrap.i16 == -16)
assert(wrap.u32 == 32)
assert(wrap.i32 == -32)
-- print(wrap)
end
testluacwrap.callwithTESTSTRUCT(myfunc)
end
--
-- test attach to inner struct
--
function TestTESTSTRUCT:testAttachWithLightEmbeddedStructs()
-- semantic of attach() with light embedded structs
function myfunc(struct)
local wrap = TESTSTRUCT:attach(struct)
local attached = INNERSTRUCT:attach(wrap)
-- check if they point to the same memory
assert(wrap.__ptr == attached.__ptr)
end
testluacwrap.callwithTESTSTRUCT(myfunc)
end
--
-- test access to boxed object
--
function TestTESTSTRUCT:testBoxed()
-- test boxed
function myfunc(struct)
-- print(struct)
-- print(testluacwrap.printTESTSTRUCT(struct))
assert(struct.u8 == 8)
assert(struct.i8 == - 8)
assert(struct.u16 == 16)
assert(struct.i16 == -16)
assert(struct.u32 == 32)
assert(struct.i32 == -32)
end
testluacwrap.callwithBoxedTESTSTRUCT(myfunc)
end
--
-- test access to wrapped stack based objects
--
function TestTESTSTRUCT:testCallwithwrappedTESTSTRUCT()
-- callwithwrappedTESTSTRUCT")
-- test wrapped stack based objects
function wrapfunc(wrap)
-- print(wrap)
assert(wrap.u8 == 8)
assert(wrap.i8 == - 8)
assert(wrap.u16 == 16)
assert(wrap.i16 == -16)
assert(wrap.u32 == 32)
assert(wrap.i32 == -32)
end
testluacwrap.callwithwrappedTESTSTRUCT(wrapfunc)
end
--
-- test call with reference type
--
function TestTESTSTRUCT:testCallwithRefType()
-- callwithRefType
-- test wrapped stack based objects
function wrapfunc(wrap)
-- print(wrap)
assert(wrap.u8 == 8)
assert(wrap.i8 == - 8)
assert(wrap.u16 == 16)
assert(wrap.i16 == -16)
assert(wrap.u32 == 32)
assert(wrap.i32 == -32)
-- print("wrap.__ptr", wrap.__ptr)
assert(0 ~= wrap.ref.ref)
assert("string" == type(wrap.ref.value))
assert("callwithRefType" == wrap.ref.value)
-- print(testluacwrap.printTESTSTRUCT(wrap))
end
testluacwrap.callwithRefType(wrapfunc, "callwithRefType")
end
--
-- test fixed memory buffers
--
function TestTESTSTRUCT:testBuffers()
-- checkbuffers
local mybuf = luacwrap.createbuffer(256)
-- print(mybuf)
local mybuf2 = luacwrap.createbuffer(256)
-- print(mybuf2)
-- create instance
mybuf = "hello"
assert("hello" == mybuf)
-- print("content of mybuf:", mybuf)
end
--
-- test array type
--
function TestTESTSTRUCT:testArrays()
-- create type descriptor
local type_double128 = luacwrap.registerarray("double128", 128, "$dbl")
-- create instance
local myarray = type_double128:new()
-- print(myarray)
assert(#myarray == 128)
assert("number" == type(myarray[1]))
for idx=1, 128 do
myarray[idx] = idx
end
for idx=1, 128 do
assert(myarray[idx] == idx)
end
end
--
-- test registering custom struct type
--
function TestTESTSTRUCT:testRegisterStructType()
-- create type descriptor
local type_mystruct = luacwrap.registerstruct("mystruct", 8,
{
{ "member1", 0, "$i32" },
{ "member2", 4, "$i32" }
}
)
-- create struct instance
local mystruct = type_mystruct:new()
-- access members
mystruct.member1 = 10
mystruct.member2 = 22
assert(mystruct.member1 == 10)
assert(mystruct.member2 == 22)
end
os.exit(lu.run())
|
--------------------
-- Sassilization
-- By Sassafrass / Spacetech / LuaPineapple
--------------------
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
end
function ENT:Setup(ProjModel)
self:SetModel(ProjModel)
self:SetSolid(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_NONE)
self:PhysicsInit(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_WEAPON)
self:DrawShadow(false)
self.Trail = util.SpriteTrail(self, 0, Color(180, 180, 180, 80), false, 1, 0.01, 0.5, 0.5, "trails/laser.vmt")
timer.Simple(2, function() SafeRemoveEntity(self) end )
end
function ENT:Shoot(Damage, Dir)
self.Damage = Damage
local Phys = self:GetPhysicsObject()
if (Phys:IsValid()) then
Phys:Wake()
Phys:SetVelocity(Dir:Forward() * Phys:GetMass() * 10)
end
end
function ENT:GetEmpire()
return self.empire
end
function ENT:SetControl(Empire)
self.empire = Empire
self:SetColor(Empire:GetColor())
end
function ENT:StartTouch(Ent)
if (self.Fail) then
return
end
self:HitEnt(Ent, self:GetPhysicsObject())
SafeRemoveEntity(self)
end
function ENT:PhysicsCollide(data, Phys)
if (self.Fail) then
return
end
if (data.HitEntity:IsWorld()) then
self.Fail = true
Phys:EnableMotion(false)
else
self:HitEnt(data.HitEntity, Phys)
SafeRemoveEntity(self)
end
end
function ENT:HitEnt(Ent, Phys)
if (Ent:IsUnit() or Ent:IsBuilding()) then
if (self.empire != Ent:GetEmpire() and !Allied(self.empire, Ent:GetEmpire())) then
self.Fail = true
if (Ent.Damage) then
self.Damage.dmgpos = Phys:GetPos()
Ent:Damage(self.Damage)
end
end
end
end |
--************************
--name : ppid_001.lua
--ver : 0.1
--author : Ferron
--date : 2004/09/21
--lang : en
--desc : General Faction Information
--npc : Hacknet Broadcast Daemon v0.1.1
--************************
--changelog:
--2004/09/21(0.1): built from snows template
--************************
-- faction information
DBNAME="ProtoPharm Broadcasting Daemon v0.0.1"
FACNAME="ProtoPharm"
FACSLOGAN="Your hope. Your strength. Your cure."
FACGENERAL="General Faction Information\n ProtoPharm produces most of the pharmaceutical supplies in Neocron. In this regard, virtually everything is produced, from standard Medkits to miracle cures."
FACHQ="Faction Headquarter\n Located in ViaRosso 2, can also be reached through Plaza 2 trough the PP Labs."
FACPERS="Key Personalities\n Chairwoman Sandra Frasier, 42, is a brilliant and tough strategist who made her way up from the street. Currently she is rumored to have a relationship with Seymor Jordan, manager of Biotech Industries."
FACHISTORY="Faction History\n In 2646 the medical company ProtoPharm emerged from a merger of several medical and chemical companies. Management was handed over to Jakob Finster, a young business attorney. In 2652 the development of cryogenic sleeping chambers for the 'Avenger' was successfully completed, in 2658 a version for rich customers in Neocron was developed. Some years later Jakob Finster - fallen ill to an incurable disease - entered a CryoVault(tm) himself in the hope of future progresses in medicine. In 2670 ProtoPharm started production for the mass market. Research into a multipurpose medication was pushed ahead, the fruits of which were harvested in the form of the formula for 'Vitae(tm)' in 2678. Three years later cheap generics of Vitae(tm) are supplied on the black market, which drove the company into a crisis. In 2739 'Spirula', a remedy for radiation damage, was introduced to the market by ProtoPharm. After a short boom, things changed drastically one year later when it was revealed that side effects of the drug caused devastating genetic damage on Neocron's population. In 2741, Sandra Frasier, the firm's successful attorney in the Spirula case, was made head of the company. Three years later there is still no cure for cryogenical preserved Jakob Finster. In 2747 the 'Spirula' scandal flared up again when it was revealed that the mutants who were created by Spirula were becoming sexually mature and fertile much faster than normal human beings. They were declared non-human beings by Lioon Reza. Killing them was regarded an act of mercy. In 2750 ProtoPharm and BioTech Industries enter a cooperation agreement."
FACRUMORS="Faction Rumors\n Many odd stories float around the intriguing Sandra Frasier. For instance it is said that there is more to BioTech's and ProtoPharm's recent alliance than meets the eye and that Seymour Jordan's motives are far from being all business related. In the same direction go numerous stories about the means Ms Frasier used on her way into the upper levels of management. Some of those stories might be true, but others depict a Sandra Frasier so cold blooded and calculating, that they cannot be believed by anyone in his or her right mind. Rumor has it that the founder of ProtoPharm, Jakob Finster, fell terminally ill and therefore saw no other chance than to preserve himself in one of ProtoPharm's cryogenic chamber. Supposedly he is woken up every 20 years to see if he can be cured yet. But even if there was a cure, those who spread this rumor also say that Ms Frasier doesn't have the slightest interest in saving the old man."
FACREL="Faction Relations\n Miss Frasier has very good contacts with both BioTech Ind. and its manager, Seymour Jordan. The CityMercs have an agreement of 'protection for equipment' with ProtoPharm, also accepting sabotage jobs against NEXT Systems. The Brotherhood of Crahn is a valuable source of information for Sandra Frasier. The good relations between ProtoPharm and the Administration of Neocron date back to the days of the 'Avenger' construction and the Great Trek, the success of which, among other things, was very much dependent on the CryoVaults(tm) produced by ProtoPharm. \n The animosities with NEXT Systems seem to stem from Sandra's rather tough business practices, while the aversion on Madame Veronique's side, the leader of the Tsunami Syndicate, seems to be of a more personal nature. Aside from weakness, Sandra Frasier hates unpredictable people. She finds the chaos and the freethinking ideas of the Breed very dubious and ProtoPharm supports all allies who work actively against the Anarchists. All mutants are the testimony of ProtoPharm's fallibility and unscrupulousness. If Sandra (and many other managerial employees of the company) had her way, all mutants would be eradicated for good."
-- main dialog
function DIALOG()
NODE(0)
SAY("Broadcast system establishing link ...... Link established ...... System ready:"..DBNAME)
ANSWER(" - Continue",10)
ANSWER(" - Abort",25)
NODE(10)
SAY("Information categories")
ANSWER(" - General Faction Information",15)
ANSWER(" - Faction Headquarter",16)
ANSWER(" - Key Personalities",17)
ANSWER(" - Faction History",18)
ANSWER(" - Faction Rumors",19)
ANSWER(" - Faction Relations",20)
ANSWER(" - Abort",25)
NODE(15)
SAY(""..FACGENERAL)
ANSWER("Back",10)
NODE(16)
SAY(""..FACHQ)
ANSWER("Back",10)
NODE(17)
SAY(""..FACPERS)
ANSWER("Back",10)
NODE(18)
SAY(""..FACHISTORY)
ANSWER("Back",10)
NODE(19)
SAY(""..FACPERS)
ANSWER("Back",10)
NODE(20)
SAY(""..FACRUMORS)
ANSWER("Back",10)
NODE(25)
SAY("Closing Link ...... Disconnecting ......"..FACNAME.." - "..FACSLOGAN)
ANSWER(" - Disconnect",26)
ANSWER(" - Cancel",0)
NODE(26)
SAY("Disconnecting")
ENDDIALOG()
end
|
-- SPDX-FileCopyrightText: 2020 Henri Chain <henri.chain@enioka.com>
--
-- SPDX-License-Identifier: Apache-2.0
local BasePlugin = require "kong.plugins.base_plugin"
local UpstreamOAuth2 = BasePlugin:extend()
local tokens = require "kong.plugins.upstream-oauth2.tokens"
local socket = require "socket"
UpstreamOAuth2.PRIORITY = 802
UpstreamOAuth2.VERSION = "1.0.0"
function UpstreamOAuth2:new()
UpstreamOAuth2.super.new(self, "upstream-oauth2")
end
function UpstreamOAuth2:access(conf)
UpstreamOAuth2.super.access(self)
local curtime = socket.gettime()
local cache_key = tokens.get_cache_key(conf.token_url, conf.client_id, conf.scope)
local err, res
for i = 1, 2 do
res, err =
kong.cache:get(
cache_key,
nil,
tokens.get_access_token,
conf.token_url,
conf.client_id,
conf.client_secret,
"client_credentials",
conf.scope
)
-- preventively ask for new access token if about to expire
if res and res.expires_at and res.expires_at < curtime + 5 then
kong.cache:invalidate_local(cache_key)
kong.response.set_header("X-Token-Expired", curtime - res.expires_at)
elseif res and res.access_token then
break
else
kong.cache:invalidate_local(cache_key)
return kong.response.exit(400, res or err)
end
end
kong.service.request.set_header("Authorization", "Bearer " .. res.access_token)
if (res.expires_at) then
kong.response.set_header("X-Token-Expires-In", res.expires_at - curtime)
end
end
function UpstreamOAuth2:header_filter(conf)
local status = kong.response.get_status()
-- If auth doesn't work, delete token from cache
if status == 401 then
kong.cache:invalidate(tokens.get_cache_key(conf.token_url, conf.client_id, conf.scope))
end
end
return UpstreamOAuth2
|
require "tundra.syntax.osx-bundle"
Program {
Name = "foo",
Sources = { "main.m", "delegate.m" },
Frameworks = { "Cocoa" },
}
local mybundle = OsxBundle {
Depends = { "foo" },
Target = "$(OBJECTDIR)/MyApp.app",
InfoPList = "Info.plist",
Executable = "$(OBJECTDIR)/foo",
Resources = {
CompileNib { Source = "appnib.xib", Target = "appnib.nib" },
"icon.icns",
},
}
Default(mybundle)
|
local M = {}
M.cmd = "vusted"
M.working_dir = require("cmdhndlr.util").working_dir.upward_pattern(".git")
local handler = require("cmdhndlr.handler.test_runner.lua.busted")
return setmetatable(M, {
__index = function(_, k)
return rawget(M, k) or handler[k]
end,
})
|
--[[---------------------------------------------
AdvLib (C) Mijyuoon 2014-2020
Contains various helper functions
-----------------------------------------------]]
adv = {
-- Constants here
HttpCache = {},
Markup = {},
}
----- Config section ----------------------------
local Use_MoonScript = true
local Use_PrintTable = false
-------------------------------------------------
local MODLOAD = {}
adv._MODLOAD = MODLOAD
function loadmodule(name)
if MODLOAD[name] then
return MODLOAD[name]
end
local kname = "mods/base/" .. name:gsub("%.", "/") .. ".lua"
local file = io.open(kname, "r")
io.input(file)
local s = io.read("*all")
io.close(file)
local func = loadstring(s)
if func then
MODLOAD[name] = func() or true
return MODLOAD[name]
end
end
loadmodule("moonscript.lulpeg"):register(_G)
lpeg.re = loadmodule("moonscript.lpeg_re")
local trmv = table.remove
function adv.StrFormat(text, subst)
if subst == nil then
subst = text
text = trmv(text, 1)
end
text = text:gsub("$([%w_]+)", function(s)
local ns = tonumber(s) or s
local subs = subst[ns]
if subs == nil then return end
return tostring(subs)
end)
return text
end
function adv.StrSet(text, pos, rep)
pos = (pos < 0) and #text+pos+1 or pos
if pos > #text or pos < 1 then return text end
return text:sub(1, pos-1) .. rep .. text:sub(pos+1, -1)
end
function adv.StrSplit(str, sep)
sep = lpeg.re.compile(sep)
local elem = lpeg.C((1 - sep)^0)
local gs = lpeg.Ct(elem * (sep * elem)^0)
return gs:match(str)
end
adv.StrPatt = lpeg.re.compile
adv.StrFind = lpeg.re.find
adv.StrMatch = lpeg.re.match
adv.StrSubst = lpeg.re.gsub
function adv.TblMap(tbl, func)
for ki, vi in pairs(tbl) do
tbl[ki] = func(vi)
end
return tbl
end
function adv.TblMapN(tbl, func)
local res = {}
for ki, vi in pairs(tbl) do
res[ki] = func(vi)
end
return res
end
function adv.TblFold(tbl, acc, func)
local init = nil
if func == nil then
func = acc
acc = tbl[1]
init = acc
end
for _, vi in next, tbl, init do
acc = func(acc, vi)
end
return acc
end
function adv.TblFilt(tbl, func)
for ki, vi in pairs(tbl) do
if not func(vi) then
tbl[ki] = nil
end
end
return tbl
end
function adv.TblFiltN(tbl, func)
local res = {}
for ki, vi in pairs(tbl) do
if func(vi) then
res[ki] = vi
end
end
return res
end
function adv.TblSlice(tbl, from, to, step)
local res = {}
from = from or 1
to = to or #tbl
step = step or 1
for i = from, to, step do
res[#res+1] = tbl[i]
end
return res
end
function adv.TblAny(tbl, func)
for ki, vi in pairs(tbl) do
if func(vi) then
return true
end
end
return false
end
function adv.TblAll(tbl, func)
for ki, vi in pairs(tbl) do
if not func(vi) then
return false
end
end
return true
end
function adv.TblKeys(tbl)
local res = {}
for k in pairs(tbl) do
res[#res+1] = k
end
return res
end
for _, kn in pairs{"K", "V", "KV"} do
adv["TblWeak" .. kn] = function()
return setmetatable({}, {
__mode = kn:lower()
})
end
end
local function prefix(str)
local stri = tostring(str)
return (stri:gsub("^[a-z]+: ", ""))
end
local function do_printr(arg, spaces, passed)
local ty = type(arg)
if ty == "table" then
passed[arg] = true
Msg(adv.StrFormat{"(table) $v {\n",
v = prefix(arg)})
for k ,v in pairs(arg) do
if not passed[v] then
Msg(adv.StrFormat{" $s($t) $k => ",
s = spaces, t = type(k), k = k})
do_printr(rawget(arg, k), spaces.." ", passed)
else
Msg(adv.StrFormat{" $s($t) $k => [RECURSIVE TABLE: $v]\n",
s = spaces, t = type(k), k = k, v = prefix(v)})
end
end
Msg(spaces .. "}\n")
elseif ty == "function" then
Msg(adv.StrFormat{"($t) $v\n",
t = ty, v = prefix(arg)})
elseif ty == "string" then
Msg(adv.StrFormat{"($t) '$v'\n",
t = ty, v = arg})
elseif ty == "nil" then
Msg(adv.StrFormat{"($t)\n",
t = ty})
else
Msg(adv.StrFormat{"($t) $v\n",
t = ty, v = arg})
end
end
function adv.TblPrint(...)
local arg = {...}
for i = 1, #arg do
do_printr(arg[i], "", {})
end
end
if Use_MoonScript then
moonscript = loadmodule "moonscript.base"
end
|
local t = Def.ActorFrame{};
local frameWidth = 280
local frameHeight = 20
local frameX = SCREEN_WIDTH-5
local frameY = 15
local sortTable = {
SortOrder_Preferred = 'Preferred',
SortOrder_Group = 'Group',
SortOrder_Title = 'Title',
SortOrder_BPM = 'BPM',
SortOrder_Popularity = 'Popular',
SortOrder_TopGrades = 'Grade',
SortOrder_Artist = 'Artist',
SortOrder_Genre = 'Genre',
SortOrder_ModeMenu = 'Mode Menu',
SortOrder_Length = 'Song Length',
SortOrder_Recent = 'Recently Played',
SortOrder_Favorites = 'Favorites'
}
t[#t+1] = Def.Quad{
Name="CurrentSort";
InitCommand=cmd(xy,frameX,frameY;halign,1;zoomto,frameWidth,frameHeight;diffuse,getMainColor('frames'););
};
t[#t+1] = LoadFont("_wendy small") .. {
InitCommand=cmd(xy,frameX,frameY+5;halign,1;zoom,0.55;maxwidth,(frameWidth-40)/0.35);
BeginCommand=cmd(queuecommand,"Set");
SetCommand=function(self)
local sort = GAMESTATE:GetSortOrder()
local song = GAMESTATE:GetCurrentSong()
if sort == nil then
self:settext("Sort: ")
elseif sort == "SortOrder_Group" and song ~= nil then
self:settext(song:GetGroupName())
else
self:settext("Sort: "..sortTable[sort])
end
end;
SortOrderChangedMessageCommand=cmd(queuecommand,"Set";diffuse,getMainColor('positive'));
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
return t
|
#!/usr/bin/env tarantool
test = require("sqltester")
test:plan(3)
--!./tcltestrunner.lua
-- 2008 January 13
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, never taking more than you give.
--
-------------------------------------------------------------------------
-- This file implements regression tests for SQLite library.
--
-- This file implements tests to verify that ticket #3581 has been
-- fixed.
--
-- $Id: tkt3581.test,v 1.1 2009/01/14 01:10:40 drh Exp $
-- ["set","testdir",[["file","dirname",["argv0"]]]]
-- ["source",[["testdir"],"\/tester.tcl"]]
test:do_test(
"tkt3581-1.1",
function()
return test:execsql [[
CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
INSERT INTO t1 VALUES(0,544,846);
INSERT INTO t1 VALUES(1,345,51);
CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c);
INSERT INTO t2 SELECT * FROM t1;
CREATE INDEX i2 on t2(c);
]]
end, {
-- <tkt3581-1.1>
-- </tkt3581-1.1>
})
test:do_test(
"tkt3581-1.2",
function()
return test:execsql [[
SELECT a FROM t1
WHERE (b > 45 AND c < 356)
OR b <= 733
OR b >= 557
OR (b >= 614 AND c < 251)
ORDER BY b;
]]
end, {
-- <tkt3581-1.2>
1, 0
-- </tkt3581-1.2>
})
test:do_test(
"tkt3581-1.3",
function()
return test:execsql [[
SELECT a FROM t2
WHERE (b > 45 AND c < 356)
OR b <= 733
OR b >= 557
OR (b >= 614 AND c < 251)
ORDER BY b;
]]
end, {
-- <tkt3581-1.3>
1, 0
-- </tkt3581-1.3>
})
test:finish_test()
|
--[[
psz-sklepy: Kupno obiektow przyczepialnych, zapis do EQ gracza
@author Jakub 'XJMLN' Starzak <jack@pszmta.pl
@package PSZMTA.psz-sklepy
@copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl>
Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie.
]]--
local sw, sh = guiGetScreenSize()
local sklep = {}
sklep.wnd = guiCreateWindow(sw*168/800, sh*120/600, sw*520/sw, sh*414/sh, "Sklep", false)
sklep.gridlist = guiCreateGridList(0.02, 0.07, 0.55, 0.90, true, sklep.wnd)
sklep.gridlist_nazwa = guiGridListAddColumn(sklep.gridlist, "Nazwa", 0.5)
sklep.gridlist_cena = guiGridListAddColumn(sklep.gridlist, "Cena", 0.5)
sklep.img = guiCreateStaticImage(0.59, 0.13, 0.39, 0.32, "s_general/i/empty.png", true, sklep.wnd)
sklep.label1 = guiCreateLabel(0.59, 0.06, 0.39, 0.05, "Wygląd przedmiotu: ", true, sklep.wnd)
sklep.btn_buy = guiCreateButton(0.58, 0.65, 0.40, 0.15, "Kup przedmiot", true, sklep.wnd)
sklep.btn_cancel = guiCreateButton(0.58, 0.83, 0.40 ,0.15, "Anuluj", true, sklep.wnd)
guiSetVisible(sklep.wnd, false)
local function shop_fill(npc)
local shopOffer = getElementData(npc, "shop_offer")
if (not shopOffer) then
outputChatBox("Sprzedawca: Niestety, nie mamy nic w ofercie.",255,0,0)
return false
end
sklep.sprzedawca = npc
guiGridListClear(sklep.gridlist)
for i, v in ipairs(shopOffer) do
local row = guiGridListAddRow(sklep.gridlist)
guiGridListSetItemText(sklep.gridlist, row, sklep.gridlist_nazwa, v.itemName, false, false)
guiGridListSetItemData(sklep.gridlist, row, sklep.gridlist_nazwa, v)
guiGridListSetItemText(sklep.gridlist, row, sklep.gridlist_cena, v.buyprice.."$", false, false)
if (tonumber(v.buyprice)>getPlayerMoney()) then
guiGridListSetItemColor(sklep.gridlist, row, sklep.gridlist_cena, 255,0,0)
else
guiGridListSetItemColor(sklep.gridlist, row, sklep.gridlist_cena, 155, 255, 155)
end
end
return true
end
function shop_refreshPhoto()
local selRow, selCol = guiGridListGetSelectedItem(sklep.gridlist)
if (not selRow) then return end
local data = guiGridListGetItemData(sklep.gridlist, selRow, sklep.gridlist_nazwa)
local img
if (not data) then
img = "s_general/i/empty.png"
else
img = "s_general/i/eq-"..data.itemID..".png"
end
guiStaticImageLoadImage(sklep.img, img)
end
function shop_buyOffer()
local selRow, selCol = guiGridListGetSelectedItem(sklep.gridlist)
if (not selRow) then return end
local data = guiGridListGetItemData(sklep.gridlist, selRow, sklep.gridlist_nazwa)
end
addEventHandler("onClientGUIClick", sklep.gridlist, shop_refreshPhoto, false)
addEventHandler("onClientGUIClick", sklep.btn_buy, shop_buyOffer, false)
addEventHandler("onClientColShapeHit", resourceRoot, function(he,md)
if (he~=localPlayer or not md or getElementInterior(localPlayer)~=getElementInterior(source)) then return end
local npc = getElementParent(source)
if (npc and getElementType(npc)=="ped") then
if shop_fill(npc) then
guiSetVisible(sklep.wnd,true)
showCursor(true,false)
sklep.enabled=true
toggleControl("fire", false)
end
end
end)
addEventHandler("onClientColShapeLeave", resourceRoot, function(he,md)
if (he~=localPlayer or not md or getElementInterior(localPlayer)~=getElementInterior(source)) then return end
local npc=getElementParent(source)
if (npc and getElementType(npc)=="ped") then
guiSetVisible(sklep.wnd,false)
sklep.sprzedawca=nil
showCursor(false)
sklep.enabled=false
toggleControl("fire",true)
end
end)
addEventHandler("onClientGUIClick", sklep.btn_cancel, function()
if (not sklep.enabled) then return end
guiSetVisible(sklep.wnd,false)
showCursor(false)
sklep.enabled=false
sklep.sprzedawca=nil
toggleControl("fire",true)
end,false) |
-- Copyright (C) Izio, Inc - All Rights Reserved
-- Unauthorized copying of this file, via any medium is strictly prohibited
-- Proprietary and confidential
-- Written by Romain Billot <romainbillot3009@gmail.com>, Jully 2017
allJob = {}
allZoneJob = {}
addCapactity = 10
timeCapactity = 300000
timePay = 180000
minTimePay = timePay/2
enablePay = false
addjobautomatic = false
debugg = true
local usableTreatItem = {48}-- TO CHANGE
------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------ON RESOURCE START---------------------------------------------
------------------------------------------------------------------------------------------------------------------------
AddEventHandler("onMySQLReady", function()
TriggerEvent("iJob:startLoading")
end)
AddEventHandler("iJob:loadingAfterRestart", function()
TriggerEvent("iJob:startLoading")
end)
AddEventHandler("iJob:startLoading", function()
if addjobautomatic == true then
tableTest = {
rank = { {name = "Gérant", salary = 500}, {name="Confirmé", salary = 100}, {name="Stagiaire", salary = 300}},
blacklist = {{p = "steamTest", dhm = "14 6 5"} },
lost = { {p = "steamTest2", a = 10, re = "essence", dmh = "14 6 5"}, {p = "steamTest3", a = 10, re = "essence", dmh = "14 6 5"} },
benefit = { {p = "steamTest2", a = 10, re = "venteTest", dmh = "14 6 5"}, {p = "steamTest3", a = 10, re = "venteTest", dmh = "14 6 5"} },
capital = 100000,
name = "pompiste",
employe = { {pl = "steam:110000104bd6595", rank = "interne", displayName = "test Test"} },
default = {rank = "stagiaire"},
id = 7
}
local encodedRank = json.encode(tableTest.rank)
local encodedBlacklist = json.encode(tableTest.blacklist)
local encodedLost = json.encode(tableTest.lost)
local encodedBenefit = json.encode(tableTest.benefit)
local encodedEmploye = json.encode(tableTest.employe)
local capital = tostring(tableTest.capital)
local default = json.encode(tableTest.default)
MySQL.Sync.execute("INSERT INTO job (`capital`, `benefit`, `lost`, `default`, `rank`, `employe`, `blacklist`, `name`, `id`) VALUES (@capital, @benefit, @lost, @default, @rank, @employe, @blacklist, @name, @id)", {
['@capital'] = capital,
['@benefit'] = encodedBenefit,
['@lost'] = encodedLost,
['@default'] = default,
['@rank'] = encodedRank,
['@employe'] = encodedEmploye,
['@blacklist'] = encodedBlacklist,
['@name'] = tableTest.name,
['@id'] = tableTest.id
})
end
local results = MySQL.Sync.fetchAll("SELECT * FROM job")
local results2 = MySQL.Sync.fetchAll("SELECT * FROM zone")
if results[1] ~= nil then
for i = 1, #results do
v = 0
for j = 1, #results2 do
if (results2[j].categorie == results[i].name or results2[j].categorie == "shared") and results2[j].instructions then
table.insert(allZoneJob, {
nom = results2[j].nom,
coords = json.decode(results2[j].coords),
gravityCenter = json.decode(results2[j].gravityCenter),
longestDistance = json.decode(results2[j].longestDistance),
categorie = results2[j].categorie,
instructions = json.decode(results2[j].instructions)
})
v = 1
elseif results2[j].categorie == results[i].name then
table.insert(allZoneJob, {
nom = results2[j].nom,
coords = json.decode(results2[j].coords),
gravityCenter = json.decode(results2[j].gravityCenter),
longestDistance = json.decode(results2[j].longestDistance),
categorie = results2[j].categorie
})
elseif IsHarvestJob(results[i].name) and results2[j].categorie == "rec" then
table.insert(allZoneJob, {
nom = results2[j].nom,
coords = json.decode(results2[j].coords),
gravityCenter = json.decode(results2[j].gravityCenter),
longestDistance = json.decode(results2[j].longestDistance),
categorie = results2[j].categorie,
instructions = json.decode(results2[j].instructions)
})
end
end
if v == 0 then -- to prevent the job without zone assigned (which is not supposed to happend)
LoadJob(results[i], nil)
else
LoadJob(results[i], allZoneJob)
allZoneJob = {}
end
end
end
saveJobIfChanged()
end)
function LoadJob(test, test2)
if test2 ~= nil then
allJob[test.name] = CreateJob(test.capital, json.decode(test.benefit), json.decode(test.lost), test.name, json.decode(test.default), json.decode(test.rank), json.decode(test.employe), test2, json.decode(test.blacklist)) -- zone contain { zone1 = { }, zone2 = { }, zone3 = { } }
else -- the job got a zone assigned by the categorie name
allJob[test.name] = CreateJob(test.capital, json.decode(test.benefit), json.decode(test.lost), test.name, json.decode(test.default), json.decode(test.rank), json.decode(test.employe), nil, json.decode(test.blacklist))
end
end
RegisterServerEvent("ijob:retreiveIfRestart")
AddEventHandler("ijob:retreiveIfRestart", function()
local source = source
TriggerEvent("es:getPlayerFromId", source, function(user)
if user ~= nil then
TriggerClientEvent("ijob:updateJob", user.get('source'), user.get('job'), user.get('rank'))
TriggerClientEvent("ijob:addBlip", user.get('source'), allJob[user.get('job')].getBlip(), true)
end
end)
end)
AddEventHandler("es:playerLoaded", function(source)
TriggerEvent("es:getPlayerFromId", source, function(user)
TriggerClientEvent("ijob:addBlip", source, allJob[user.get('job')].getBlip(), true)
end)
end)
------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------COMMANDES-----------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------PARTIE API----------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent("ijob:getJobFromName")
AddEventHandler("ijob:getJobFromName", function(jobName, cb)
if allJob[jobName] then
cb(allJob[jobName])
else
cb(nil)
end
end)
RegisterServerEvent("ijob:getAllJob")
AddEventHandler("ijob:getAllJob", function(cb)
cb(allJob)
end)
------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------SAVE----------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
function saveJobIfChanged()
SetTimeout(60000, function()
for k,v in pairs(allJob)do
print("Job changed ? : ".. tostring(v.get('haveChanged')))
if v.get('haveChanged') == true then -- only if changed
MySQL.Sync.execute("UPDATE job SET `capital`=@vcapital, `benefit`=@vbenefit, `lost`=@vlost, `rank`=@vrank, `employe`=@vemploye, `blacklist`=@vblacklist, `name`=@vname WHERE name = @vname",{
['@vcapital'] = tostring(v.get('capital')),
['@vbenefit'] = json.encode(v.get('benefit')),
['@vlost'] = json.encode(v.get('lost')),
['@vrank'] = json.encode(v.get('rank')),
['@vemploye'] = json.encode(v.get('employe')),
['@vblacklist'] = json.encode(v.get('blacklist')),
['@vname'] = v.get('name')
})
v.set('haveChanged', false)
print("Job changed saved to the DB.")
end
end
saveJobIfChanged()
end)
end
function saveJob()
for k,v in pairs(allJob)do
MySQL.Sync.execute("UPDATE job SET `capital`=@vcapital, `benefit`=@vbenefit, `lost`=@vlost,`rank`=@vrank, `employe`=@vemploye, `blacklist`=@vblacklist, `name`=@vname WHERE name = @vname",{
['@vcapital'] = tostring(v.get('capital')),
['@vbenefit'] = json.encode(v.get('benefit')),
['@vlost'] = json.encode(v.get('lost')),
['@vrank'] = json.encode(v.get('rank')),
['@vemploye'] = json.encode(v.get('employe')),
['@vblacklist'] = json.encode(v.get('blacklist')),
['@vname'] = v.get('name')
})
allJob[v.name].set('haveChanged', false)
end
print("Job changed saved to the DB.")
end
------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------NewPlayer--------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
AddEventHandler("es:newPlayerLoaded", function(userSource, user)
allJob["chomeur"].addEmployeWithRefresh(user)
end)
------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------Harvest---------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
function AddHarvestCapacity()
SetTimeout(timeCapactity, function()
for k,v in pairs(allJob) do
v.addCapacityToAll(addCapactity)
end
AddHarvestCapacity()
end)
end
AddHarvestCapacity()
RegisterServerEvent("iJob:harvestillegal")
AddEventHandler("iJob:harvestillegal", function(result)
local source = source -- Thanks FXS
TriggerEvent("es:getPlayerFromId", source, function(user)
local item = {}
local quantity = {}
local lucky = false
local randomHarvest = math.random(1, 100)
if randomHarvest < 20 then -- 20% de change d'avoir deux item normaux
item = result.receive.normal
lucky = true
else -- et 80% de chance d'avoir jsute un item normal
item = result.receive.normal
end
for i=1, #item do
if lucky then
quantity[i] = 2
else
quantity[i] = 1
end
end
local resultFromHarvest = allJob["illegal"].harvest(result.displayMessageInZone, quantity, false)
if resultFromHarvest then
ProcessHarvest(source, result, item, quantity)
else
TriggerClientEvent("ijob:stopHarvest", source)
user.notify("Tu ne peux pas récolter, la zone de récolte est vide. Attends un peu", "error", "centerLeft", true, 5000)
TriggerClientEvent("anim:Play", source, "stopAll")
end
end)
end)
RegisterServerEvent("iJob:otherIllegal")
AddEventHandler("iJob:otherIllegal", function(result)
local source = source -- Thanks FXS
TriggerEvent("es:getPlayerFromId", source, function(user)
local item = result.receive.normal
local quantity = {}
for i=1, #item do
quantity[i] = 1
end
ProcessOther(source, result, item, quantity)
end)
end)
RegisterServerEvent("iJob:checkHarvest")
AddEventHandler("iJob:checkHarvest", function(result)
local source = source -- Thanks FXS
local job
local lucky
TriggerEvent("es:getPlayerFromId", source, function(user)
if not(IsHarvestJob(user.get('job'))) then
user.notify("Tu n'as pas ce métier.", "error", "topCenter", true, 5000)
CancelEvent()
return
end
local finalItemsArray, totalQuantity = GenerateLucky(result) -- TODO
job = string.lower(user.get('job')) --
local resultFromHarvest = allJob[job].harvest(result.displayMessageInZone, totalQuantity, false)
if resultFromHarvest then
ProcessHarvest(source, result, finalItemsArray)
else
TriggerClientEvent("ijob:stopHarvest", source)
user.notify("Tu ne peux pas récolter, la zone de récolte est vide. Attends un peu", "error", "topCenter", true, 5000)
TriggerClientEvent("anim:Play", source, "stopAll")
end
end)
end)
RegisterServerEvent("iJob:askForItemsArray")
AddEventHandler("iJob:askForItemsArray", function(result, plate)
local source = source
TriggerEvent("es:getPlayerFromId", source, function(user)
TriggerEvent("car:getPlayerJobCar", user.get('identifier'), function(car)
if car ~= nil then
local items = {}
local quantity = {}
for i = 1, #result.need do
table.insert(items, result.need[i].id)
table.insert(quantity, result.need[i].quantity)
end
local quantityGotten = car.howMuchItContainOfArray(items)
if car.isAbleToReceiveItems(items, quantity) then
TriggerClientEvent("iJob:returnFromAskForItemsArray", source, result, quantityGotten, plate)
else
user.notify("Tu n'as plus rien à revendre de ton véhicule ici.")
TriggerClientEvent("iJob:returnFromAskForItemsArray", source, result, nil, plate)
end
else
user.notify("Contact Izio iJiob server : nil veh for job when selling", "error", "topCenter", true, 5000)
end
end)
end)
end)
RegisterServerEvent("iJob:sellItemsFromVeh")
AddEventHandler("iJob:sellItemsFromVeh", function(itemsNeeded, plate)
local source = source
TriggerEvent("es:getPlayerFromId", source, function(user)
TriggerEvent("car:getPlayerJobCar", user.get('identifier'), function(car)
local items = {}
local quantity = {}
for i = 1, #itemsNeeded do
table.insert(items, itemsNeeded[i].id)
table.insert(quantity, itemsNeeded[i].quantity)
end
local items = user.get('item')
local totalPrice = 0
for i = 1, #itemsNeeded do
totalPrice = totalPrice + items[itemsNeeded[i].id] * itemsNeeded[i].quantity
end
user.addMoney(totalPrice)
local message = GetMessage(items, quantity, items)
user.notity("Tu viens de vendre " .. message .. "pour " .. totalPrice .. "$.", "success", "topCenter", true, 5000)
car.removeQuantityArray(items, quantity)
end)
end)
end)
function GenerateLucky(result)
local finalItems = {}
local quantity = {}
for i = 1, #result.receive.normal do
local luck = math.random(1,100)
if luck <= 2 then
if result.receive.rare then
local picker = math.random(1, #result.receive.rare)
table.insert(finalItems, result.receive.rare[picker])
table.insert(quantity, result.receive.rare[picker].quantity * 5)
else
table.insert(finalItems, {id = result.receive.normal[i].id, quantity = result.receive.normal[i].quantity * 2})
table.insert(quantity, result.receive.normal[i].quantity * 2)
end
elseif luck <= 15 then
table.insert(finalItems, {id = result.receive.normal[i].id, quantity = result.receive.normal[i].quantity * 2})
table.insert(quantity, result.receive.normal[i].quantity * 2)
elseif luck <= 100 then
table.insert(finalItems, {id = result.receive.normal[i].id, quantity = result.receive.normal[i].quantity})
table.insert(quantity, result.receive.normal[i].quantity)
end
end
return finalItems, quantity
end
RegisterServerEvent("ijob:process")
AddEventHandler("ijob:process", function(result)
local source = source -- Thanks FXS
local job
TriggerEvent("es:getPlayerFromId", source, function(user)
local item = {}
local quantity = {}
local lucky = false
local randomReceive = math.random(1, 100)
if randomReceive < 2 then -- 2% de chance d'avoir un item rare
item = result.receive.rare
elseif randomReceive < 17 then -- 15% de change d'avoir deux item normaux
item = result.receive.normal
lucky = true
else -- et 83% de chance d'avoir jsute un item normal
item = result.receive.normal
end
for i=1, #item do
if lucky then
quantity[i] = 2
else
quantity[i] = 1
end
end
ProcessOther(source, result, item, quantity)
end)
end)
function IsHarvestJob(job)
if string.lower(job) == string.lower("Fermier") or string.lower(job) == string.lower("Bucheron") or string.lower(job) == string.lower("Pompiste") then
return true
else
return false
end
end
function ProcessHarvest(source, result, allItems) -- create = true / false
TriggerEvent("es:getPlayerFromId", source, function(user)
local item, quantity = ConvertToBeTreated(allItems)
local bool = user.isAbleToReceiveItems(item , quantity) -- deux array
if bool then
user.addQuantityArray(item, quantity)
local itemInfos = user.get('item')
local generatedMessage = GetMessage(item, quantity, itemInfos)
user.notify("Tu viens de récolter" .. generatedMessage .. ".", "success", "topCenter", true, 5000)
allJob[user.get('job')].harvest(result.displayMessageInZone, quantity, true)
user.refreshInventory()
TriggerClientEvent("inventory:change", source, user.sendDatas())
else
user.notify("Tu n'as pas assez de place dans ton inventaire", "error", "topCenter", true, 5000)
TriggerClientEvent("ijob:stopHarvest", source)
end
end)
end
function ConvertToBeTreated(allItems)
local items = {}
local quantity = {}
for i = 1, #allItems do
table.insert(items, allItems[i].id)
table.insert(quantity, allItems[i].quantity)
end
return items, quantity
end
function ProcessOther(source, result, item, quantity)
TriggerEvent("es:getPlayerFromId", source, function(user)
local quantityToRemove = {}
user.addQuantityArray(item, quantity)
for i = 1, #result.need do
table.insert(quantityToRemove, 1)
end
for i=1, #result.need do
for j=1, #usableTreatItem do
if result.need[i] == usableTreatItem[j] then
table.remove(result.need, i)
end
end
end
user.removeQuantityArray(result.need, quantityToRemove)
local itemInfos = user.get('item')
local message = GetMessage(item, quantity, itemInfos)
user.notify("Tu viens de recevoir" .. message .. ".", "success", "topCenter", true, 5000)
TriggerClientEvent("inventory:change", source, json.decode(user.sendDatas()))
end)
end
function GetMessage(item, quantity, itemInfos)
local message = ""
for i=1, #item do
-- name est nill visiblement
message = message .. " " .. quantity[i] .. " " .. itemInfos[item[i]].name
if i ~= 1 and i ~= #item then
message = message .. " et "
end
end
return message
end
------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------PARTIE API-------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
AddEventHandler("ijob:getJobFromName", function(name, cb)
if allJob[name] ~= nil then
cb(allJob[name])
else
cb(nil)
end
end)
------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------EVENT JOB--------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent('ijob:changeJobPoleEmplois') -- Le joueur est nécéssairement Online
AddEventHandler('ijob:changeJobPoleEmplois', function(job)
local job = string.lower(job)
--RconPrint("Job Changed to " .. tostring(job))
TriggerEvent("es:getPlayerFromId", source, function(user)
if allJob[job].isBlacklisted(user.get('identifier')) then
user.notify("Tu es <span style='color:red'>blacklisté</span> du métier, attends encore un peu.", "error", true, 5000)
else
local result = allJob[job].addEmployeWithRefresh(user)
if result == "already" then
user.notify("Tu viens de quitter le métier de <span style='color:yellow' > " ..job.. "</span>, attends encode un peu.", "error", "leftCenter", true, 5000)
else
if result == "hireFirst" then
user.notify("Tu ne peux pas faire ça, tu es <span style='color:yellow' > ".. user.get('job') .. "</span> quitte d'abord ton emploie (/demission).", "error", "centerLeft", true, 5000)
else
user.notify("Bienvenue chez les <span style='color:yellow' > "..job.. "</span> contact ton patron, il te donnera les infos dont tu as besoin.", "success", "topCenter", true, 5000)
TriggerClientEvent("ijob:addBlip", user.get('source'), allJob[user.get('job')].getBlip(), true)
TriggerClientEvent("ijob:updateJob", user.get('source'), user.get('job'), user.get('rank'))
end
end
end
end)
end)
TriggerEvent('es:addGroupCommand', 'addjob', "mod", function(source, args, user)
local source = source
TriggerEvent("es:getPlayerFromId", tonumber(args[2]), function(targetUser) -- job, employeNetId
if args[2] == "help" or #args ~= 3 then
print("test")
TriggerClientEvent('chatMessage', source, "SYSTEM", {255, 0, 0}, "Usage: /addjob [serverId] [job], ex : /addjob 1 bucheron")
CancelEvent()
return
end
if targetUser ~= nil then
print("different de nil")
if allJob[targetUser.get('job')] ~= nil then
print("diff nil 2")
if allJob[targetUser.get('job')].isBlacklisted(targetUser) then
print("je suis blacklisté ?")
targetUser.notify("Tu es <span style='color:red'>blacklisté</span> du métier de " .. targetUser.get('job') .. ".", "error", true, 5000)
else
print("pas blacklisté")
if allJob[args[3]] then
result = allJob[args[3]].addEmployeWithRefresh(targetUser)
print(result)
if result == "already" then
TriggerEvent("es:getPlayerFromId", source, function(user)
user.set('job', args[3])
user.set('rank', allJob[args[3]].get('default.rank'))
TriggerClientEvent("ijob:addBlip", targetUser.get('source'), allJob[args[3]].getBlip(), true)
TriggerClientEvent("ijob:updateJob", targetUser.get('source'), args[3], targetUser.get('rank'))
user.notify("Le joueur à déjà ce job.", "error", "topCenter", true, 5000)
end)
elseif result == "hireFirst" then
allJob[targetUser.get('job')].removeEmploye(targetUser)
targetUser.notify("Tu es retiré du métier de " .. targetUser.get('job') .. ".", "success", "topCenter", true, 5000)
print(targetUser.get('job') .. targetUser.get('rank'))
TriggerEvent('es:getPlayerFromId', tonumber(args[2]), function(targetUserr)
print(targetUserr.get('job') .. targetUserr.get('rank'))
allJob[args[3]].addEmployeWithRefresh(targetUser)
TriggerClientEvent("ijob:updateJob", targetUserr.get('source'), args[3], targetUserr.get('rank'))
TriggerClientEvent("ijob:addBlip", targetUserr.get('source'), allJob[args[3]].getBlip(), true)
targetUser.notify("Tu es ajouté au métier de " .. targetUserr.get('job') .. ".", "success", "topCenter",true, 5000)
end)
else
TriggerClientEvent("ijob:updateJob", targetUser.get('source'), args[3], targetUser.get('rank'))
TriggerClientEvent("ijob:addBlip", targetUser.get('source'), allJob[args[3]].getBlip(), true)
targetUser.notify("Tu es <span style='color:green'>ajouté</span> au métier de " .. targetUser.get('job') .. ".", "success", "topCenter", true, 5000)
end
else
user.notify("Le job n'existe pas.", "error", "topCenter", true, 5000)
end
end
else
TriggerEvent("es:getPlayerFromId", source, function(user)
user.notify("Le job spécifié n'existe pas", "error", "topCenter", true, 5000)
end)
end
else
TriggerEvent("es:getPlayerFromId", source, function(user)
user.notify("Le serverId " .. args[2] .. " n'existe pas.", "error", "topCenter", true, 5000)
end)
end
end)
end, function(source, args, user)
print("TEST")
local source = source
TriggerClientEvent('chatMessage', source, "SYSTEM", {255, 0, 0}, "permission insuffisante!")
end)
-- commande démission (provisoire) :
TriggerEvent('es:addCommand', 'demission', function(source, args, user)
if #args ~= 1 then
user.notify("Utilisation : /demission.", "error", "topCenter",true, 5000)
else
user.notify("Tu viens de quitter ton métier.", "success", "topCenter",true, 5000)
local test = allJob[user.get('job')].removeEmploye(user)
if test == "L employe n a pas ete trouve" then
local result = nil
for k,v in pairs(allJob) do
result = v.isEmploye(user)
if result then
user.set("job", k)
user.set("rank", result)
TriggerClientEvent("ijob:updateJob", user.get('source'), user.get('job'), user.get('rank'))
return
CancelEvent()
end
end
user.set("job", "chomeur")
user.set("rank", allJob["chomeur"].default.rank)
TriggerClientEvent("ijob:updateJob", user.get('source'), user.get('job'), user.get('rank'))
end
end
end)
------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------PAY--------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
function PayAllPlayer()
SetTimeout(timePay, function()
if enablePay then
TriggerEvent("es:getPlayers", function(Users)
for i=1, #Users do
if allJob[Users[i].get('job')] then
allJob[Users[i].get('job')].getPaid(Users[i])
else
print("Job : " .. Users[i].get('job') .. " not reconized by the iJob")
end
end
end)
else
print("Pay not enable : see iJob/iJob_server.lua")
end
PayAllPlayer()
end)
end
PayAllPlayer()
------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------OnResourceStop---------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
AddEventHandler("onResourceStop", function(resource)
if resource == "iJob" then
saveJob()
end
end)
------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------DEBUG------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
function PrintAllIndexArray(array)
for i=1, #array do
for k,v in pairs(array[i]) do
print("k : " .. tostring(k) .. " v : " ..tostring(v))
end
end
end
function debugMsg(msg)
if(msg) and debugg then
print("iJob_Debug: " .. msg)
end
end
-------------------Futur poubelle :
------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------Test Rcon Cmd-------------------------------------------------
------------------------------------------------------------Hardcoding--------------------------------------------------
AddEventHandler('rconCommand', function(commandName, args) -- Je ne fais aucune vérification car je m'en fou, c'est juste pour tester et vous montrer comment ça fonctionne
local msg = table.concat(args, ' ')
local job = args[2]
--[[if commandName == "addZone" then
local zone = nil
allJob[job]:addZone(zone)
CancelEvent()
elseif commandName == "addEmploye" then
local employe = args[3] -- steamID64 Hexa
allJob[job]:addEmploye(employe)
CancelEvent()
elseif commandName == "removeEmploye" then
local employe = args[3]
allJob[job]:removeEmploye(employe)
CancelEvent()
elseif commandName == "addRank" then
local rank = args[3] -- juste un string avec le nom du rank
allJob[job]:addRank(rank)
CancelEvent()
elseif commandName == "removeRank" then
local rank = args[3]
allJob[job]:removeRank(rank)
CancelEvent()
elseif commandName == "setRank" then
local player = args[3] -- steam ID 64 Hexa
local rank = args[4] -- un rank déjà existant dans le job
allJob[job]:setRank(player, rank)
CancelEvent()
elseif commandName == "getEmployeWithRank" then
local employe = allJob[job]:getEmployeWithRank() -- employe = { {pl = employe, rank = defaultRank}, {pl = employe2, rank = rankOsef} }
CancelEvent()
elseif commandName == "getEmployeName" then
local employeId = allJob[job]:getEmployeId() -- employeId = { {pl = employe1}, {pl = employe2} }
CancelEvent()
elseif commandName == "getCapital" then
local capital = allJob[job]:getCapital() -- float ou int 100 / 1542.2 / 486542.36
CancelEvent()
elseif commandName == "setCapital" then
local amount = args[3]
allJob[job]:setCapital(amount) -- enleve 152.2 au capital. sinon job:setCapital(565) ajoute 565 au capital
CancelEvent()
elseif commandName == "getBenefit" then
local allBenefit = allJob[job]:getBenefit() -- { {p = pl, a = m, re = r, dm = tostring(temp.day) .. " " .. tostring(temp.month)}, {p = pl, a = m, re = r, dm = tostring(temp.day) .. " " .. tostring(temp.month)} }
CancelEvent()
elseif commandName == "addBenefit" then
local pl = args[3] -- SteamId64 Hex
local m = args[4] -- le montant (automatiquement transformé en positif, donc pas de soucis avec le - ou +) et est transformé en number
local r = args[5] -- la raison : "vente de drogue", "course taxi" etc..
allJob[job]:addBenefit(pl, m, r)
CancelEvent()
elseif commandName == "addLost" then
local pl = args[3] -- SteamId64 Hex
local m = args[4] -- le montant (automatiquement transformé en négatif, donc pas de soucis avec le - ou +) et est transformé en number
local r = args[5] -- la raison : "essence", "achat outils", "réparation vehicule" etc..
allJob[job]:addLost(pl, m, r)
CancelEvent()
elseif commandName == "addBlacklist" then
local pl = args[3] -- SteamId64 Hex
local isReturned = allJob[job]:addBlacklist(pl)
print(isReturned)
CancelEvent()
elseif commandName == "isBlacklisted" then -- Ne fonctionne pas pour le moment
local pl = args[3]
local isBlacklisted = Job:isBlacklisted(pl)
CancelEvent()
elseif commandName == "removeBlacklist" then
local pl = args[3] -- SteamId64 Hex
allJob[job]:removeBlacklist(pl)
CancelEvent()
elseif commandName == "getSalaryForRank" then
local rank = args[3] -- le rank en string
local salary = allJob[job]:getSalaryForRank(rank) -- retourne un number du montant correspondant au rank
CancelEvent()
elseif commandName == "setSalaryForRank" then
local m = args[3] -- un montant pour le rank préciser au dessous
local rank = args[4] -- le rank en string
CancelEvent()
allJob[job]:setSalaryForRank(m, rank)
end ]]
end) |
--[[
Lua XML parser. Originally created by Paul Chakravarti (paulc@passtheaardvark.com).
Modified to work with Garry's Mod.
This code is freely distributable under the terms of the Lua license
(http://www.lua.org/copyright.html)
]]
local function simpleTreeHandler()
local obj = {}
obj.root = { _name = "root" }
obj.current = obj.root
obj.options = { noreduce = {} }
obj.stack = { }
obj.starttag = function(self, name, attribs)
if not self.current.children then
self.current.children = { }
end
self.current.children[#self.current.children + 1] = {
name = name,
}
self.stack[#self.stack + 1] = self.current.children[#self.current.children]
self.current = self.current.children[#self.current.children]
end
obj.endtag = function(self, name, attribs)
table.remove(self.stack, #self.stack)
self.current = self.stack[#self.stack]
end
obj.text = function(self, text)
self.current.value = text
end
obj.cdata = obj.text
return obj
end
SF.Editor.Themes.CreateXMLParser = function()
local obj = {}
-- Public attributes
obj.options = { stripWS = 1,
expandEntities = 1,
errorHandler = function(err, pos)
error(string.format("%s [char=%d]\n",
err or "Parse Error", pos))
end,
}
-- Public methods
obj.parse = function(self, string)
local match, endmatch, pos = 0, 0, 1
local text, endt1, endt2, tagstr, tagname, attrs, starttext, endtext
local errstart, errend, extstart, extend
while match do
-- Get next tag (first pass - fix exceptions below)
match, endmatch, text, endt1, tagstr, endt2 = string.find(string, self._XML, pos)
if not match then
if string.find(string, self._WS, pos) then
-- No more text - check document complete
if table.getn(self._stack) ~= 0 then
self:_err(self._errstr.incompleteXmlErr, pos)
else
break
end
else
-- Unparsable text
self:_err(self._errstr.xmlErr, pos)
end
end
-- Handle leading text
starttext = match
endtext = match + string.len(text) - 1
match = match + string.len(text)
text = self:_parseEntities(self:_stripWS(text))
if text ~= "" and self._handler.text then
self._handler:text(text, nil, match, endtext)
end
-- Test for tag type
if string.find(string.sub(tagstr, 1, 5), "?xml%s") then
-- XML Declaration
match, endmatch, text = string.find(string, self._PI, pos)
if not match then
self:_err(self._errstr.declErr, pos)
end
if match ~= 1 then
-- Must be at start of doc if present
self:_err(self._errstr.declStartErr, pos)
end
tagname, attrs = self:_parseTag(text)
-- TODO: Check attributes are valid
-- Check for version (mandatory)
if attrs.version == nil then
self:_err(self._errstr.declAttrErr, pos)
end
if self._handler.decl then
self._handler:decl(tagname, attrs, match, endmatch)
end
elseif string.sub(tagstr, 1, 1) == "?" then
-- Processing Instruction
match, endmatch, text = string.find(string, self._PI, pos)
if not match then
self:_err(self._errstr.piErr, pos)
end
if self._handler.pi then
-- Parse PI attributes & text
tagname, attrs = self:_parseTag(text)
local pi = string.sub(text, string.len(tagname) + 1)
if pi ~= "" then
if attrs then
attrs._text = pi
else
attrs = { _text = pi }
end
end
self._handler:pi(tagname, attrs, match, endmatch)
end
elseif string.sub(tagstr, 1, 3) == "!--" then
-- Comment
match, endmatch, text = string.find(string, self._COMMENT, pos)
if not match then
self:_err(self._errstr.commentErr, pos)
end
if self._handler.comment then
text = self:_parseEntities(self:_stripWS(text))
self._handler:comment(text, next, match, endmatch)
end
elseif string.sub(tagstr, 1, 8) == "!DOCTYPE" then
-- DTD
match, endmatch, attrs = self:_parseDTD(string, pos)
if not match then
self:_err(self._errstr.dtdErr, pos)
end
if self._handler.dtd then
self._handler:dtd(attrs._root, attrs, match, endmatch)
end
elseif string.sub(tagstr, 1, 8) == "![CDATA[" then
-- CDATA
match, endmatch, text = string.find(string, self._CDATA, pos)
if not match then
self:_err(self._errstr.cdataErr, pos)
end
if self._handler.cdata then
self._handler:cdata(text, nil, match, endmatch)
end
else
-- Normal tag
-- Need theck for embedded '>' in attribute value and extend
-- match recursively if necessary eg. <tag attr="123>456">
while 1 do
errstart, errend = string.find(tagstr, self._ATTRERR1)
if errend == nil then
errstart, errend = string.find(tagstr, self._ATTRERR2)
if errend == nil then
break
end
end
extstart, extend, endt2 = string.find(string, self._TAGEXT, endmatch + 1)
tagstr = tagstr .. string.sub(string, endmatch, extend-1)
if not match then
self:_err(self._errstr.xmlErr, pos)
end
endmatch = extend
end
-- Extract tagname/attrs
tagname, attrs = self:_parseTag(tagstr)
if (endt1=="/") then
-- End tag
if self._handler.endtag then
if attrs then
-- Shouldnt have any attributes in endtag
self:_err(string.format("%s (/%s)",
self._errstr.endTagErr,
tagname)
, pos)
end
if table.remove(self._stack) ~= tagname then
self:_err(string.format("%s (/%s)",
self._errstr.unmatchedTagErr,
tagname)
, pos)
end
self._handler:endtag(tagname, nil, match, endmatch)
end
else
-- Start Tag
table.insert(self._stack, tagname)
if self._handler.starttag then
self._handler:starttag(tagname, attrs, match, endmatch)
end
-- Self-Closing Tag
if (endt2=="/") then
table.remove(self._stack)
if self._handler.endtag then
self._handler:endtag(tagname, nil, match, endmatch)
end
end
end
end
pos = endmatch + 1
end
end
-- Private attrobures/functions
obj._handler = simpleTreeHandler()
obj._stack = {}
obj._XML = '^([^<]*)<(%/?)([^>]-)(%/?)>'
obj._ATTR1 = '([%w-:_]+)%s*=%s*"(.-)"'
obj._ATTR2 = '([%w-:_]+)%s*=%s*\'(.-)\''
obj._CDATA = '<%!%[CDATA%[(.-)%]%]>'
obj._PI = '<%?(.-)%?>'
obj._COMMENT = '<!%-%-(.-)%-%->'
obj._TAG = '^(.-)%s.*'
obj._LEADINGWS = '^%s+'
obj._TRAILINGWS = '%s+$'
obj._WS = '^%s*$'
obj._DTD1 = '<!DOCTYPE%s+(.-)%s+(SYSTEM)%s+["\'](.-)["\']%s*(%b[])%s*>'
obj._DTD2 = '<!DOCTYPE%s+(.-)%s+(PUBLIC)%s+["\'](.-)["\']%s+["\'](.-)["\']%s*(%b[])%s*>'
obj._DTD3 = '<!DOCTYPE%s+(.-)%s*(%b[])%s*>'
obj._DTD4 = '<!DOCTYPE%s+(.-)%s+(SYSTEM)%s+["\'](.-)["\']%s*>'
obj._DTD5 = '<!DOCTYPE%s+(.-)%s+(PUBLIC)%s+["\'](.-)["\']%s+["\'](.-)["\']%s*>'
obj._ATTRERR1 = '=%s*"[^"]*$'
obj._ATTRERR2 = '=%s*\'[^\']*$'
obj._TAGEXT = '(%/?)>'
obj._ENTITIES = { ["<"] = "<",
[">"] = ">",
["&"] = "&",
["""] = '"',
["'"] = "'",
["&#(%d+);"] = function (x)
local d = tonumber(x)
if d >= 0 and d < 256 then
return string.char(d)
else
return "&#"..d..";"
end
end,
["&#x(%x+);"] = function (x)
local d = tonumber(x, 16)
if d >= 0 and d < 256 then
return string.char(d)
else
return "&#x"..x..";"
end
end,
}
obj._err = function(self, err, pos)
if self.options.errorHandler then
self.options.errorHandler(err, pos)
end
end
obj._errstr = { xmlErr = "Error Parsing XML",
declErr = "Error Parsing XMLDecl",
declStartErr = "XMLDecl not at start of document",
declAttrErr = "Invalid XMLDecl attributes",
piErr = "Error Parsing Processing Instruction",
commentErr = "Error Parsing Comment",
cdataErr = "Error Parsing CDATA",
dtdErr = "Error Parsing DTD",
endTagErr = "End Tag Attributes Invalid",
unmatchedTagErr = "Unbalanced Tag",
incompleteXmlErr = "Incomplete XML Document",
}
obj._stripWS = function(self, s)
if self.options.stripWS then
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
end
return s
end
obj._parseEntities = function(self, s)
if self.options.expandEntities then
for k, v in pairs(self._ENTITIES) do
s = string.gsub(s, k, v)
end
end
return s
end
obj._parseDTD = function(self, s, pos)
-- match,endmatch,root,type,name,uri,internal
local m, e, r, t, n, u, i
m, e, r, t, u, i = string.find(s, self._DTD1, pos)
if m then
return m, e, { _root = r, _type = t, _uri = u, _internal = i }
end
m, e, r, t, n, u, i = string.find(s, self._DTD2, pos)
if m then
return m, e, { _root = r, _type = t, _name = n, _uri = u, _internal = i }
end
m, e, r, i = string.find(s, self._DTD3, pos)
if m then
return m, e, { _root = r, _internal = i }
end
m, e, r, t, u = string.find(s, self._DTD4, pos)
if m then
return m, e, { _root = r, _type = t, _uri = u }
end
m, e, r, t, n, u = string.find(s, self._DTD5, pos)
if m then
return m, e, { _root = r, _type = t, _name = n, _uri = u }
end
return nil
end
obj._parseTag = function(self, s)
local attrs = {}
local tagname = string.gsub(s, self._TAG, '%1')
string.gsub(s, self._ATTR1, function (k, v)
attrs[string.lower(k)] = self:_parseEntities(v)
attrs._ = 1
end)
string.gsub(s, self._ATTR2, function (k, v)
attrs[string.lower(k)] = self:_parseEntities(v)
attrs._ = 1
end)
if attrs._ then
attrs._ = nil
else
attrs = nil
end
return tagname, attrs
end
return obj
end
|
-- Developer
-- MIT License © 2019 Arthur Corenzan
-- More on https://github.com/haggen/wow
local function ParseQuery(message)
local query = {
patterns = {},
};
for term in string.gmatch(message, "%S+") do
if (string.sub(term, 0, 5) == "type:") then
query.type = string.sub(term, 6);
else
table.insert(query.patterns, term);
end
end
return query;
end
local function MatchAll(subject, patterns)
for i = 1, #patterns do
if (not string.find(subject, patterns[i], nil, false)) then
return false;
end
end
return true;
end
SlashCmdList["GLOBALS"] = function(message)
local query = ParseQuery(string.lower(message));
local globals = {};
local checkpoint = GetTime();
local total = 0;
for key, value in pairs(_G) do
local name = string.lower(tostring(key));
if (query.type == nil or query.type == type(value)) then
if MatchAll(name, query.patterns) then
globals[key] = tostring(value);
total = total + 1;
end
end
end
UIParentLoadAddOn("Blizzard_DebugTools");
DevTools_Dump(globals);
print(string.format("Found %d result(s) in %.3f sec.", total, GetTime() - checkpoint));
end;
SLASH_GLOBALS1 = "/globals";
|
--Regen doesn't heal in combat anymore
kAlienRegenerationCombatModifier = 0
function Alien:UpdateAutoHeal()
PROFILE("Alien:UpdateAutoHeal")
if self:GetIsHealable() and ( not self.timeLastAlienAutoHeal or self.timeLastAlienAutoHeal + kAlienRegenerationTime <= Shared.GetTime() ) then
local healRate = 1
local hasRegenUpgrade = GetHasRegenerationUpgrade(self)
local shellLevel = GetShellLevel(self:GetTeamNumber())
local maxHealth = self:GetBaseHealth()
if hasRegenUpgrade and shellLevel > 0 then
healRate = Clamp(kAlienRegenerationPercentage * maxHealth, kAlienMinRegeneration, kAlienMaxRegeneration) * (shellLevel/3)
else
healRate = Clamp(kAlienInnateRegenerationPercentage * maxHealth, kAlienMinInnateRegeneration, kAlienMaxInnateRegeneration)
end
if self:GetTimeLastDamageTaken() + kAlienRegenerationTime + 1 > Shared.GetTime() then
healRate = healRate * kAlienRegenerationCombatModifier
end
self:AddHealth(healRate, false, false, not hasRegenUpgrade)
self.timeLastAlienAutoHeal = Shared.GetTime()
end
end |
sk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) ledmate.push_msg(c) end )
sk:connect(3344,"149.210.234.62")
--sk:connect(3344,"192.168.1.100")
|
--[[
Project: SA-MP-API
Author: Tim4ukys
My url: vk.com/tim4ukys
]]
local sys = require 'SA-MP API.kernel'
sys.safely_include 'SA-MP API.samp.0_3_7-R4-2.stGangzone'
sys.ffi.cdef[[
struct stGangzonePool {
stGangzone *pGangzone[1024];
int iIsListed[1024];
}__attribute__ ((packed));
]]
|
local obs = obslua;
local var = {}
--
-- Helpers
--
local info = function(msg)
obs.script_log(obs.LOG_INFO, "INFO: "..msg)
end
local warn = function(msg)
obs.script_log(obs.LOG_WARNING, "WARNING: "..msg)
end
local split = function(s, sep)
local fields = {}
local sep = sep or " "
local pattern = string.format("([^%s]+)", sep)
string.gsub(s, pattern, function(c) fields[#fields + 1] = c end)
return fields
end
--
-- Code
--
local start_recording_timerproc = function()
obs.remove_current_callback()
obs.obs_frontend_recording_start()
info("RECORDING STARTED")
end
local stop_recording_timerproc = function()
obs.remove_current_callback()
obs.obs_frontend_recording_stop()
info ("RECORDING STOPPED")
end
local check_for_active_sources = function()
if not (var.sources_count > 0) or var.enabled == false then
return
end
local source_active = false
for i,s in ipairs(var.sources) do
if var.sources[s] == true then
source_active = true
break
end
end
if var.source_active ~= source_active then
obs.timer_remove(start_recording_timerproc)
obs.timer_remove(stop_recording_timerproc)
if source_active then -- begin recording
if (var.start_timer > 0) then
info("Recording timer started. ("..var.start_timer.."s)")
else
start_recording_timerproc()
end
obs.timer_add(start_recording_timerproc, var.start_timer * 1000)
elseif var.source_active ~= nil then -- stop recording
if (var.stop_timeout > 0) then
info("There are no sources active. Recording will stop in "..var.stop_timeout.."s")
else
stop_recording_timerproc()
end
obs.timer_add(stop_recording_timerproc, var.stop_timeout * 1000)
end
var.source_active = source_active
end
end
--
-- handlers
--
local on_source_activated = function(cd)
local src = obs.calldata_source(cd, "source")
if src == nil then
warn("Source activated but calldata is nil")
return
end
local name = obs.obs_source_get_name(src)
if var.sources[name] ~= nil then
info("Source activated: "..name)
var.sources[name] = true
end
check_for_active_sources()
end
local on_source_deactivated = function(cd)
local src = obs.calldata_source(cd, "source")
if src == nil then
warn("Source deactivated but calldata is nil")
return
end
local name = obs.obs_source_get_name(src)
if var.sources[name] ~= nil then
info("Source deactivated: "..name)
var.sources[name] = false
end
check_for_active_sources()
end
--
-- Script setup
--
function script_description()
return "Automatically begin recording when a source is activated, and stop recording when the source is deactivated after a specified timeout"
end
function script_properties()
local props = obs.obs_properties_create()
obs.obs_properties_add_bool(props, "enabled", "Enabled")
obs.obs_properties_add_text(props, "source_list", "Sources", obs.OBS_TEXT_MULTILINE)
obs.obs_properties_add_int(props, "start_timer", "Start timer (sec)", 0, 100000, 1)
obs.obs_properties_add_int(props, "stop_timeout", "Stop timeout (sec)", 0, 100000, 1)
return props
end
function script_defaults(settings)
obs.obs_data_set_default_int(settings, "stop_timeout", 10)
obs.obs_data_set_default_bool(settings, "enabled", true)
end
function script_update(settings)
var.enabled = obs.obs_data_get_bool(settings, "enabled")
var.stop_timeout = obs.obs_data_get_int(settings, "stop_timeout")
var.start_timer = obs.obs_data_get_int(settings, "start_timer")
var.sources = split(obs.obs_data_get_string(settings, "source_list"), "\n")
info("Settings changed")
info("Stop timeout: "..var.stop_timeout..". Start timer: "..var.start_timer)
local sources_count = 0
info("Sources:")
for i, s in ipairs(var.sources) do
var.sources[s] = false
info(s)
sources_count = sources_count + 1
end
if not (sources_count > 0) then info("<No sources specified>") end
var.sources_count = sources_count
local enable_str
if var.enabled then enable_str = "ENABLED" else enable_str = "DISABLED" end
info("Currently "..enable_str)
check_for_active_sources()
end
function script_load(settings)
local sh = obs.obs_get_signal_handler()
obs.signal_handler_connect(sh, "source_activate", on_source_activated)
obs.signal_handler_connect(sh, "source_deactivate", on_source_deactivated)
end |
local M = {}
function M.file_exists(name)
local f = io.open(name, "r")
return f ~= nil and io.close(f)
end
function M.esc(x)
return (x:gsub('%%', '%%%%')
:gsub('^%^', '%%^')
:gsub('%$$', '%%$')
:gsub('%(', '%%(')
:gsub('%)', '%%)')
:gsub('%.', '%%.')
:gsub('%[', '%%[')
:gsub('%]', '%%]')
:gsub('%*', '%%*')
:gsub('%+', '%%+')
:gsub('%-', '%%-')
:gsub('%?', '%%?'))
end
return M
|
require 'torch'
local argcheck = require "argcheck"
local doc = require "argcheck.doc"
local tnt
if (doc.__record) then
doc.stop()
tnt = require "torchnet"
doc.record()
else
v = require "torchnet"
end
doc[[
## Df_Subset
The subset class contains all the information for a specific subset of an
associated Dataframe. It is generally owned by a dataframe and simply initiates
values/functions associated with subsetting, e.g. samplers, which indexes are
in a particular subset.
]]
-- create class object
local subset, parent_class = torch.class('Df_Subset', 'Dataframe')
subset.__init = argcheck{
doc = [[
<a name="Df_Subset.__init">
### Df_Subset.__init(@ARGP)
Creates and initializes a Df_Subset class.
@ARGT
]],
{name="self", type="Df_Subset"},
{name="parent", type="Dataframe", doc="The parent Dataframe that will be stored by reference"},
{name="indexes", type="Df_Array", doc="The indexes in the original dataset to use for sampling"},
{name="sampler", type="string", opt=true,
doc="The sampler to use with this data"},
{name="label_column", type="string", opt=true,
doc="The column with all the labels (a local copy will be generated)"},
{name="sampler_args", type="Df_Dict", opt=true,
doc=[[Optional arguments for the sampler function, currently only used for
the label-distribution sampler.]]},
{name='batch_args', type='Df_Tbl', opt=true,
doc="Arguments to be passed to the Batchframe class initializer"},
call=function(self, parent,
indexes, sampler, label_column,
sampler_args, batch_args)
parent_class.__init(self)
self:
_clean():
set_idxs(indexes)
self.parent = parent
if (label_column) then
self:set_labels(label_column)
end
if (sampler) then
if (sampler_args) then
self:set_sampler(sampler, sampler_args)
else
self:set_sampler(sampler)
end
end
if (batch_args) then
self.batch_args = batch_args.data
end
end}
subset._clean = argcheck{
doc = [[
<a name="Df_Subset._clean">
### Df_Subset._clean(@ARGP)
Reset the internal data
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
call=function(self)
parent_class._clean(self)
self.indexes = {}
self.sampler = nil
self.reset = nil
self.label_column = nil
return self
end}
subset.set_idxs = argcheck{
doc = [[
<a name="Df_Subset.set_idxs">
### Df_Subset.set_idxs(@ARGP)
Set the indexes
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
{name="indexes", type="Df_Array", doc="The indexes in the original dataset to use for sampling"},
call=function(self, indexes)
for i=1,#indexes.data do
local idx = indexes.data[i]
assert(isint(idx) and idx > 0,
"The index must be a positive integer, you've provided " .. tostring(idx))
end
-- Remove previous column if it exists
if (self:has_column('indexes')) then
assert(#indexes.data == self:size(1),
("The rows of the new (%d) and old data (%d) don't match"):
format(#indexes.data, self:size(1)))
self:drop('indexes')
end
self:add_column('indexes', Dataseries(indexes))
return self
end}
subset.get_idx = argcheck{
doc = [[
<a name="Df_Subset.get_idx">
### Df_Subset.get_idx(@ARGP)
Get the index fromm the parent Dataframe that a local index corresponds to
@ARGT
_Return value_: integer
]],
{name="self", type="Df_Subset"},
{name="index", type="number", doc="The subset's index that you want the original index for"},
call=function(self, index)
self:assert_is_index(index)
return self:get_column('indexes')[index]
end}
subset.set_labels = argcheck{
doc = [[
<a name="Df_Subset.set_labels">
### Df_Subset.set_labels(@ARGP)
Set the labels needed for certain samplers
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
{name="label_column", type="string",
doc="The column with all the labels"},
call=function(self, label_column)
-- Remove previous column if it exists
if (self:has_column('labels')) then
self:drop('labels')
end
self.parent:assert_has_column(label_column)
label_column = self.parent:get_column(label_column)
-- A little hacky but it should speed up and re-checking makes no sense
local labels = Df_Array()
local indexes = self:get_column("indexes")
for i=1,self:size() do
labels.data[#labels.data + 1] = label_column[indexes[i]]
end
-- TODO: an appealing alternative would be to store the label by ref. but this requires quite a few changes...
-- Column does not have to be numerical for this to work
self:add_column('labels', Dataseries(labels))
return self
end}
subset.set_sampler = argcheck{
doc = [[
<a name="Df_Subset.set_sampler">
### Df_Subset.set_sampler(@ARGP)
Set the sampler function that is associated with this subset
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
{name="sampler", type="string", doc="The indexes in the original dataset to use for sampling"},
{name="sampler_args", type="Df_Dict",
doc=[[Optional arguments for the sampler function, currently only used for
the label-distribution sampler.]],
default=false},
call=function(self, sampler, sampler_args)
if (sampler_args) then
self.sampler, self.reset = self:get_sampler(sampler, sampler_args)
else
self.sampler, self.reset = self:get_sampler(sampler)
end
return self
end}
-- Load the extensions
local ext_path = string.gsub(paths.thisfile(), "[^/]+$", "") .. "subset_extensions/"
load_dir_files(ext_path, {subset})
subset.get_batch = argcheck{
doc = [[
<a name="Df_Subset.get_batch">
### Df_Subset.get_batch(@ARGP)
Retrieves a batch of given size using the set sampler. If sampler needs resetting
then the second return statement will be `true`. Note that the last batch may be
smaller than the requested number when using samplers that require resetting. Once
you ave retrieved all available examples using one of the resetting samplers the
returned batch will be `nil`.
@ARGT
_Return value_: Batchframe, boolean (if reset_sampler() should be called)
]],
{name="self", type="Df_Subset"},
{name='no_lines', type='number', doc='The number of lines/rows to include (-1 for all)'},
{name='class_args', type='Df_Tbl', opt=true,
doc='Arguments to be passed to the class initializer'},
call=function(self, no_lines, class_args)
assert(isint(no_lines) and
(no_lines > 0 or
no_lines == -1),
"The number of files to load has to be either -1 for all files or " ..
" a positive integer." ..
" You provided " .. tostring(no_lines))
if (not class_args) then
class_args = Df_Tbl(self.batch_args)
end
local reset = false
if (no_lines == -1 or
no_lines > self:size(1)) then
no_lines = self:size(1)
reset = true -- The sampler only triggers the reset after passing > 1 epoch
end
local indexes = {}
for i=1,no_lines do
local idx
idx, reset = self.sampler()
if (idx == nil) then
reset = true
break
end
table.insert(indexes, idx)
if (reset) then
break;
end
end
if (#indexes == 0) then
return nil, reset
end
return self.parent:_create_subset{index_items = Df_Array(indexes),
frame_type = "Batchframe",
class_args = class_args}, reset
end}
subset.reset_sampler = argcheck{
doc = [[
<a name="Df_Subset.reset_sampler">
### Df_Subset.reset_sampler(@ARGP)
Resets the sampler. This is needed for a few samplers and is easily checked for
in the 2nd return value from `get_batch`
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
call=function(self)
self.reset()
return self
end}
subset.get_iterator = argcheck{
doc = [[
<a name="Df_Subset.get_iterator">
### Df_Subset.get_iterator(@ARGP)
**Important**: See the docs for Df_Iterator
@ARGT
_Return value_: `Df_Iterator`
]],
{name="self", type="Df_Subset"},
{name="batch_size", type="number", doc="The size of the batches"},
{name='filter', type='function', default=function(sample) return true end,
doc="See `tnt.DatasetIterator` definition"},
{name='transform', type='function', default=function(sample) return sample end,
doc="See `tnt.DatasetIterator` definition. Runs immediately after the `get_batch` call"},
{name='input_transform', type='function', default=function(val) return val end,
doc="Allows transforming the input (data) values after the `Batchframe:to_tensor` call"},
{name='target_transform', type='function', default=function(val) return val end,
doc="Allows transforming the target (label) values after the `Batchframe:to_tensor` call"},
call=function(self, batch_size, filter, transform, input_transform, target_transform)
return Df_Iterator{
dataset = self,
batch_size = batch_size,
filter = filter,
transform = transform,
input_transform = input_transform,
target_transform = target_transform
}
end}
subset.get_parallel_iterator = argcheck{
doc = [[
<a name="Df_Subset.get_parallel_iterator">
### Df_Subset.get_parallel_iterator(@ARGP)
**Important**: See the docs for Df_Iterator and Df_ParallelIterator
@ARGT
_Return value_: `Df_ParallelIterator`
]],
{name="self", type="Df_Subset"},
{name="batch_size", type="number", doc="The size of the batches"},
{name='init', type='function', default=function(idx)
-- Load the libraries needed
require 'torch'
require 'Dataframe'
end,
doc=[[`init(threadid)` (where threadid=1..nthread) is a closure which may
initialize the specified thread as needed, if needed. It is loading
the libraries 'torch' and 'Dataframe' by default.]]},
{name='nthread', type='number',
doc='The number of threads used to parallelize is specified by `nthread`.'},
{name='filter', type='function', default=function(sample) return true end,
doc=[[is a closure which returns `true` if the given sample
should be considered or `false` if not. Note that filter is called _after_
fetching the data in a threaded manner and _before_ the `to_tensor` is called.]]},
{name='transform', type='function', default=function(sample) return sample end,
doc='a function which maps the given sample to a new value. This transformation occurs before filtering.'},
{name='input_transform', type='function', default=function(val) return val end,
doc="Allows transforming the input (data) values after the `Batchframe:to_tensor` call"},
{name='target_transform', type='function', default=function(val) return val end,
doc="Allows transforming the target (label) values after the `Batchframe:to_tensor` call"},
{name='ordered', type='boolean', opt=true,
doc=[[This option is particularly useful for repeatable experiments.
By default `ordered` is false, which means that order is not guaranteed by
`run()` (though often the ordering is similar in practice).]]},
call =
function(self, batch_size, init, nthread,
filter, transform, input_transform, target_transform, ordered)
return Df_ParallelIterator{
dataset = self,
batch_size = batch_size,
init = init,
nthread = nthread,
filter = filter,
transform = transform,
input_transform = input_transform,
target_transform = target_transform,
ordered = ordered
}
end}
subset.__tostring__ = argcheck{
doc=[[
<a name="Df_Subset.__tostring__">
### Df_Subset.__tostring__(@ARGP)
@ARGT
_Return value_: string
]],
{name="self", type="Dataframe"},
call=function (self)
return ("\nThis is a subset with %d rows and %d columns."):
format(self:size(1), self:size(2)) ..
"\n ------ \n" ..
" the subset core data consists of: \n" ..
parent_class.__tostring__(self)
end}
subset.set_data_retriever = argcheck{
doc = [[
<a name="Df_Subset.set_data_retriever">
### Df_Subset.set_data_retriever(@ARGP)
Sets the self.batch_args.data to either a function for loading data or
a set of columns that should be used in the to_tensor functions.
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
{name="data", type="function|Df_Array", opt=true,
doc="The data loading procedure/columns. If omitted the retriever will be erased"},
call=function(self, data)
if (not self.batch_args) then
self.batch_args = {}
end
self.batch_args.data = data
return self
end}
subset.set_label_retriever = argcheck{
doc = [[
<a name="Df_Subset.set_label_retriever">
### Df_Subset.set_label_retriever(@ARGP)
Sets the self.batch_args.data to either a function for loading data or
a set of columns that should be used in the to_tensor functions.
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
{name="label", type="function|Df_Array", opt=true,
doc="The label loading procedure/columns. If omitted the retriever will be erased"},
call=function(self, label)
if (not self.batch_args) then
self.batch_args = {}
end
self.batch_args.label = label
return self
end}
subset.set_label_shape = argcheck{
doc = [[
<a name="Df_Subset.set_label_shape">
### Df_Subset.set_label_shape(@ARGP)
Sets the self.batch_args.label_shape for transforming the data into
requested format
@ARGT
_Return value_: self
]],
{name="self", type="Df_Subset"},
{name="label_shape", type="string", opt=true,
doc=[[The shape in witch the labels should be provided. Some criterion require
to subset the labels on the column and not the row, e.g. `nn.ParallelCriterion`,
and thus the shape must be `NxM` or `NxMx1` for it to work as expected.]]},
call=function(self, label_shape)
if (not self.batch_args) then
self.batch_args = {}
end
self.batch_args.label_shape = label_shape
return self
end}
return subset
|
--[[
FiveM Scripts
Copyright C 2018 Sighmir
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
at your option any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- MAIN THREAD
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
for k,v in pairs(cfg.hotkeys) do
if IsControlJustPressed(v.group, k) or IsDisabledControlJustPressed(v.group, k) then
v.pressed()
end
if IsControlJustReleased(v.group, k) or IsDisabledControlJustReleased(v.group, k) then
v.released()
end
end
end
end)
--[[Citizen.CreateThread(function()
while true do
if crouchedState == 2 then
if IsControlPressed(1, 32) and not movFwd then
movFwd = true
TaskPlayAnimAdvanced(GetPlayerPed(-1), "move_crawl", "onfront_fwd", GetEntityCoords(GetPlayerPed(-1)), 0.0, 0.0, GetEntityHeading(GetPlayerPed(-1)), -1, 1.0, -1, 47, 1.0, 0, 0)
elseif IsControlJustReleased(1,32) and movFwd then
TaskPlayAnimAdvanced(GetPlayerPed(-1), "move_crawl", "onfront_fwd", GetEntityCoords(GetPlayerPed(-1)), 0.0, 0.0, GetEntityHeading(GetPlayerPed(-1)), -1, 1.0, -1, 46, 1.0, 0, 0)
movFwd = false
end
if IsControlPressed(1, 34) then
SetEntityHeading(GetPlayerPed(-1), GetEntityHeading(GetPlayerPed(-1)) + 2)
end
if IsControlPressed(1, 9) then
SetEntityHeading(GetPlayerPed(-1), GetEntityHeading(GetPlayerPed(-1)) - 2)
end
end
Citizen.Wait(1)
end
end)]]
-- OTHER THREADS
-- THIS IS FOR CROUCH
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if DoesEntityExist(GetPlayerPed(-1)) and not IsEntityDead(GetPlayerPed(-1)) then
DisableControlAction(0,36,true) -- INPUT_DUCK
end
end
end)
-- OTHER THREADS
-- THIS IS FOR KNEEL
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if IsEntityPlayingAnim(GetPlayerPed(PlayerId()), "random@arrests@busted", "idle_a", 3) then
DisableControlAction(1, 140, true)
DisableControlAction(1, 141, true)
DisableControlAction(1, 142, true)
DisableControlAction(0, 21, true)
DisableControlAction(0,37,true) -- disable tab
DisableControlAction(0,22,true) -- disable jump
end
end
end)
-- THIS IS FOR HANDSUP
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if handsup then
SetPedStealthMovement(GetPlayerPed(-1),true,"")
DisableControlAction(0,21,true) -- disable sprint
DisableControlAction(0,24,true) -- disable attack
DisableControlAction(0,25,true) -- disable aim
DisableControlAction(0,47,true) -- disable weapon
DisableControlAction(0,58,true) -- disable weapon
DisableControlAction(0,71,true) -- veh forward
DisableControlAction(0,72,true) -- veh backwards
DisableControlAction(0,63,true) -- veh turn left
DisableControlAction(0,64,true) -- veh turn right
DisableControlAction(0,263,true) -- disable melee
DisableControlAction(0,264,true) -- disable melee
DisableControlAction(0,257,true) -- disable melee
DisableControlAction(0,140,true) -- disable melee
DisableControlAction(0,141,true) -- disable melee
DisableControlAction(0,142,true) -- disable melee
DisableControlAction(0,143,true) -- disable melee
DisableControlAction(0,73,true) -- disable menu K
DisableControlAction(0,37,true) -- disable tab
DisableControlAction(0,22,true) -- disable jump
--DisableControlAction(0,75,true) -- disable exit vehicle
--DisableControlAction(27,75,true) -- disable exit vehicle
end
end
end)
-- THIS IS FOR POINTING
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if pointing then
local camPitch = GetGameplayCamRelativePitch()
if camPitch < -70.0 then
camPitch = -70.0
elseif camPitch > 42.0 then
camPitch = 42.0
end
camPitch = (camPitch + 70.0) / 112.0
local camHeading = GetGameplayCamRelativeHeading()
local cosCamHeading = Cos(camHeading)
local sinCamHeading = Sin(camHeading)
if camHeading < -180.0 then
camHeading = -180.0
elseif camHeading > 180.0 then
camHeading = 180.0
end
camHeading = (camHeading + 180.0) / 360.0
local blocked = 0
local nn = 0
local coords = GetOffsetFromEntityInWorldCoords(GetPlayerPed(-1), (cosCamHeading * -0.2) - (sinCamHeading * (0.4 * camHeading + 0.3)), (sinCamHeading * -0.2) + (cosCamHeading * (0.4 * camHeading + 0.3)), 0.6)
local ray = Cast_3dRayPointToPoint(coords.x, coords.y, coords.z - 0.2, coords.x, coords.y, coords.z + 0.2, 0.4, 95, GetPlayerPed(-1), 7);
nn,blocked,coords,coords = GetRaycastResult(ray)
Citizen.InvokeNative(0xD5BB4025AE449A4E, GetPlayerPed(-1), "Pitch", camPitch)
Citizen.InvokeNative(0xD5BB4025AE449A4E, GetPlayerPed(-1), "Heading", camHeading * -1.0 + 1.0)
Citizen.InvokeNative(0xB0A6CFD2C69C1088, GetPlayerPed(-1), "isBlocked", blocked)
Citizen.InvokeNative(0xB0A6CFD2C69C1088, GetPlayerPed(-1), "isFirstPerson", Citizen.InvokeNative(0xEE778F8C7E1142E2, Citizen.InvokeNative(0x19CAFA3C87F7C2FF)) == 4)
end
end
end)
-- THIS IS FOR ENGINE-CONTROL
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if DoesEntityExist(GetVehiclePedIsTryingToEnter(PlayerPedId())) then
local veh = GetVehiclePedIsTryingToEnter(PlayerPedId())
engine = IsVehicleEngineOn(veh)
end
if IsPedInAnyVehicle(GetPlayerPed(-1), false) and not engine then
local vehicle = GetVehiclePedIsIn(GetPlayerPed(-1), false)
local damage = GetVehicleBodyHealth(vehicle)
SetVehicleEngineOn(vehicle, engine, false, false)
if damage <= 0 then
SetVehicleUndriveable(vehicle, true)
vRP.notify({"~r~Este veículo está muito danificado."})
end
end
end
end)
--[[ THIS IS FOR NO DOC COMA
Citizen.CreateThread(function() -- coma thread
while true do
Citizen.Wait(1000)
if vRP.isInComa({}) then
if called == 0 then
HKserver.canSkipComa({"coma.skipper","coma.caller"},function(skipper, caller) -- change them on cfg too if you do
if skipper or caller then
HKserver.docsOnline({},function(docs)
if docs == 0 and skipper then
vRP.notify({"~r~There's nobody to revive you.\n~b~Press ~g~E~b~ to respawn."})
elseif docs > 0 and caller then
vRP.notify({"~g~There are doctors online.\n~b~Press ~g~E~b~ to call an ambulance."})
end
end)
end
end)
else
called = called - 1
end
else
called = 0
end
end
end)]]
-- Scoreboard
local playerList = {}
local showPlayerList = false
function vRPhk.showScoreboard(playerListSended)
playerList = playerListSended
showPlayerList = not showPlayerList
end
local function DrawPlayerList()
local count = 0
for k, v in pairs( playerList ) do
count = count +1
end
--Top bar
DrawRect( 0.5, 0.045, 0.2, 0.03, 0, 0, 0, 220 )
--Top bar title
SetTextFont( 4 )
SetTextProportional( 0 )
SetTextScale( 0.45, 0.45 )
SetTextColour( 255, 255, 255, 255 )
SetTextDropShadow( 0, 0, 0, 0, 255 )
SetTextEdge( 1, 0, 0, 0, 255 )
SetTextEntry( "STRING" )
AddTextComponentString( "B2K Roleplay - Players: " .. count)
DrawText( 0.405, 0.028 )
count = 1
for k, v in pairs( playerList ) do
local r
local g
local b
if count % 2 == 0 then
r = 28
g = 47
b = 68
else
r = 38
g = 57
b = 74
end
--Row BG
DrawRect( 0.50, 0.045 + ( count * 0.03 ), 0.2, 0.03, r, g, b, 220 )
--Name Label
SetTextFont( 4 )
SetTextScale( 0.45, 0.45 )
SetTextColour( 255, 255, 255, 255 )
SetTextEntry( "STRING" )
AddTextComponentString("["..k.."] ".. v)
DrawText( 0.402, 0.030 + ( count * 0.03 ) )
count = count +1
end
end
Citizen.CreateThread( function()
RequestStreamedTextureDict( "mplobby" )
RequestStreamedTextureDict( "mpleaderboard" )
while true do
Wait(0)
if showPlayerList then
DrawPlayerList()
end
end
end)
-- OTHER FUNCTIONS
function vRPhk.lockVehicle(lockStatus, vehicle)
if lockStatus == 1 or lockStatus == 0 then -- locked or unlocked
if IsVehicleEngineOn(vehicle) and not isPlayerInside then
SetVehicleUndriveable(vehicle, true)
end
SetVehicleDoorsLocked(vehicle, 2)
SetVehicleDoorsLockedForPlayer(vehicle, PlayerId(), true)
HKserver.lockSystemUpdate({2, plate})
-- ## Notifications
local eCoords = GetEntityCoords(vehicle)
HKserver.playSoundWithinDistanceOfCoordsForEveryone({eCoords.x, eCoords.y, eCoords.z, 10, "lock", 1.0})
Citizen.InvokeNative(0xAD738C3085FE7E11, vehicle, true, true) -- set as mission entity
vRP.notifyPicture({"CHAR_LIFEINVADER", 3, "LockSystem", "vRP Hotkeys", "Vehicle locked."})
-- ## Notifications
elseif lockStatus == 2 then -- if it is locked
if not IsVehicleEngineOn(vehicle) then
Citizen.CreateThread(function()
while true do
Wait(0)
if isPlayerInside then
SetVehicleUndriveable(vehicle, false)
break
end
end
end)
end
SetVehicleDoorsLocked(vehicle, 1)
SetVehicleDoorsLockedForPlayer(vehicle, PlayerId(), false)
HKserver.lockSystemUpdate({1, plate})
-- ## Notifications
local eCoords = GetEntityCoords(vehicle)
HKserver.playSoundWithinDistanceOfCoordsForEveryone({eCoords.x, eCoords.y, eCoords.z, 10, "unlock", 1.0})
vRP.notifyPicture({"CHAR_LIFEINVADER", 3, "LockSystem", "vRP Hotkeys", "Vehicle unlocked."})
-- ## Notifications
end
end
function vRPhk.playSoundWithinDistanceOfCoords(x, y, z, maxDistance, soundFile, soundVolume)
local lCoords = GetEntityCoords(GetPlayerPed(-1))
local distIs = Vdist(lCoords.x, lCoords.y, lCoords.z, x, y, z)
local Sreduc = 1.0 - (distIs/maxDistance)
local reducedVolume = Sreduc*soundVolume
if(distIs <= maxDistance) then
SendNUIMessage({
transactionType = 'playSound',
transactionFile = soundFile,
transactionVolume = reducedVolume
})
end
end |
if select("#", ...) == 0 then
io.stderr:write "usage: lua client.lua <time of client 1>, <time of client 2>, ..."
os.exit(-1)
end
local arg = {...}
--------------------------------------------------------------------------------
require "oil"
oil.main(function()
local orb = oil.init()
------------------------------------------------------------------------------
local proxy = orb:newproxy(oil.readfrom("proxy.ior"))
local padpt = orb:newproxy(oil.readfrom("proxyadaptor.ior"))
local sadpt = orb:newproxy(oil.readfrom("serveradaptor.ior"))
------------------------------------------------------------------------------
local function showprogress(id, time)
print(id, "about to request work for "..time.." seconds")
local result = proxy:request_work_for(time)
print(id, "got", result)
end
------------------------------------------------------------------------------
local maximum = 0
for id, time in ipairs(arg) do
time = tonumber(time)
oil.newthread(showprogress, id, time)
maximum = math.max(time, maximum)
end
------------------------------------------------------------------------------
local NewServerIDL = [[
module Concurrent {
interface Server {
string do_something_for(in double seconds);
};
};
]]
local NewServerImpl = [[
local server_impl = ...
function server_impl:do_something_for(seconds)
local message = "about to sleep for "..seconds.." seconds"
oil.sleep(seconds)
return message
end
]]
local NewProxyIDL = [[
module Concurrent {
interface Proxy {
string request_work_for(in double seconds);
};
};
]]
oil.sleep(maximum/2)
orb:loadidl(NewProxyIDL)
sadpt:update(NewServerIDL, NewServerImpl)
padpt:update(NewServerIDL, "")
padpt:update(NewProxyIDL, "")
for id, time in ipairs(arg) do
oil.newthread(showprogress, id, tonumber(time))
end
------------------------------------------------------------------------------
end)
|
CobralHideoutScreenPlay = ScreenPlay:new {
numberOfActs = 1,
screenplayName = "CobralHideoutScreenPlay",
lootContainers = {
6475949,
6475950,
6475951,
6475952,
6475953,
6475954
},
lootLevel = 13,
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 100000},
{group = "junk", chance = 5500000},
{group = "melee_weapons", chance = 1500000},
{group = "heavy_weapons_consumable", chance = 800000},
{group = "pistols", chance = 500000},
{group = "carbines", chance = 500000},
{group = "rifles", chance = 500000},
{group = "clothing_attachments", chance = 300000},
{group = "armor_attachments", chance = 300000}
},
lootChance = 8000000
}
},
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("CobralHideoutScreenPlay", true)
function CobralHideoutScreenPlay:start()
if (isZoneEnabled("rori")) then
self:spawnMobiles()
self:initializeLootContainers()
end
end
function CobralHideoutScreenPlay:spawnMobiles()
spawnMobile("rori", "neo_cobral_thug", 300, 5443.0, 87.0, 5029.0, 19, 0)
spawnMobile("rori", "neo_cobral_thug", 300, 5448.4, 87.0, 5029.2, -15, 0)
spawnMobile("rori", "neo_cobral_runner", 300, 5444.9, 87.0, 5044.1, 64, 0)
spawnMobile("rori", "neo_cobral_runner", 300, 5470.9, 86.7, 5031.5, 18, 0)
spawnMobile("rori", "neo_cobral_runner", 300, 5421.8, 91.6, 5041.4, -52, 0)
spawnMobile("rori", "neo_cobral_thug", 300, 0.6, 0.3, 2.6, -13, 6055630)
spawnMobile("rori", "neo_cobral_thug", 300, -0.6, 0.3, 2.4, 9, 6055630)
spawnMobile("rori", "neo_cobral_thief", 300, -3.6, 0.3, -3.1, 0, 6055630)
spawnMobile("rori", "neo_cobral_thief", 300, 4.5, 0.3, -4.4, -89, 6055631)
spawnMobile("rori", "neo_cobral_thief", 300, -5.1, -6.8, 5.3, 94, 6055632)
spawnMobile("rori", "neo_cobral_thief", 300, 6.1, -13.8, 9.0, -149, 6055635)
spawnMobile("rori", "neo_cobral_thug", 300, 6.5, -13.8, 7.3, -134, 6055635)
spawnMobile("rori", "neo_cobral_thug", 300, 4.2, -13.8, 9.4, -176, 6055635)
spawnMobile("rori", "neo_cobral_hitman", 300, -10.9, -13.8, 7.0, 86, 6055635)
spawnMobile("rori", "neo_cobral_thief", 300, -8.5, -13.8, 9.9, 132, 6055635)
spawnMobile("rori", "neo_cobral_thief", 300, -9.1, -13.8, 4.9, 26, 6055635)
spawnMobile("rori", "neo_cobral_hitman", 300, -1.9, -20.7, 5.5, -110, 6055637)
spawnMobile("rori", "neo_cobral_hitman", 300, 4.8, -20.7, 5.0, 83, 6055637)
spawnMobile("rori", "neo_cobral_assassin", 300, 1.3, -20.7, 11.5, 176, 6055637)
spawnMobile("rori", "neo_cobral_assassin", 300,-2.5, -20.8, 22.8, 157, 6055638)
spawnMobile("rori", "neo_cobral_assassin", 300,5.3, -20.8, 22.2, -162, 6055638)
spawnMobile("rori", "neo_cobral_hitman", 300, 5.2, -20.8, 31.8, -168, 6055638)
spawnMobile("rori", "neo_cobral_hitman", 300, -2.1, -20.8, 32.2, 155, 6055638)
spawnMobile("rori", "neo_cobral_boss", 300, 1.6, -20.8, 31.5, 179, 6055638)
end
|
--
-- 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.
--
-- The ResNet model definition
--
local nn = require 'nn'
require 'cunn'
local Convolution = cudnn.SpatialConvolution
local Avg = cudnn.SpatialAveragePooling
local ReLU = cudnn.ReLU
local Max = nn.SpatialMaxPooling
local SBatchNorm = nn.SpatialBatchNormalization
local function createModel(opt)
if opt.nGPU == 0 then
Convolution = nn.SpatialConvolution
Avg = nn.SpatialAveragePooling
ReLU = nn.ReLU
Max = nn.SpatialMaxPooling
SBatchNorm = nn.SpatialBatchNormalization
end
local function ConvBN(ich, och, kW, kH, stride, padding)
local unit = nn.Sequential()
unit:add(Convolution(ich, och, kW, kH, stride, stride, padding, padding))
unit:add(SBatchNorm(och))
unit:add(ReLU(true))
return unit
end
local function inceptionFactoryA(ich, num_1x1, num_3x3red, num_3x3, num_d3x3red, num_d3x3, pool, proj)
local depthConcat = nn.Concat(2)
local conv1 = ConvBN(ich,num_1x1,1,1,1,0)
local conv3 = nn.Sequential()
conv3:add(ConvBN(ich,num_3x3red,1,1,1,0))
conv3:add(ConvBN(num_3x3red,num_3x3,3,3,1,1))
local reduce3 = nn.Sequential()
reduce3:add(ConvBN(ich,num_d3x3red,1,1,1,0))
reduce3:add(ConvBN(num_d3x3red,num_d3x3,3,3,1,1))
reduce3:add(ConvBN(num_d3x3,num_d3x3,3,3,1,1))
local pooling = nn.Sequential()
if pool == "Avg" then
pooling:add(Avg(3,3,1,1,1,1))
else
pooling:add(Max(3,3,1,1,1,1))
end
pooling:add(ConvBN(ich,proj,1,1,1,0))
depthConcat:add(conv1)
depthConcat:add(conv3)
depthConcat:add(reduce3)
depthConcat:add(pooling)
--return nn.Sequential()
-- :add(depthConcat)
return depthConcat
end
local function inceptionFactoryB(ich, num_3x3red, num_3x3, num_d3x3red, num_d3x3)
local depthConcat = nn.Concat(2)
local reduce = nn.Sequential()
reduce:add(ConvBN(ich,num_3x3red,1,1,1,0))
reduce:add(ConvBN(num_3x3red,num_3x3,3,3,2,1))
local doubleReduce = nn.Sequential()
doubleReduce:add(ConvBN(ich,num_d3x3red,1,1,1,0))
doubleReduce:add(ConvBN(num_d3x3red,num_d3x3,3,3,1,1))
doubleReduce:add(ConvBN(num_d3x3,num_d3x3,3,3,2,1))
local pooling = Max(3,3,2,2,1,1)
depthConcat:add(reduce)
depthConcat:add(doubleReduce)
depthConcat:add(pooling)
--return nn.Sequential()
-- :add(depthConcat)
return depthConcat
end
local model = nn.Sequential()
-- STAGE 1
model:add(ConvBN(3,96,7,7,2,3))
model:add(Max(3,3,2,2,0,0))
-- STAGE 2
model:add(ConvBN(96,128,1,1,1,0))
model:add(ConvBN(128,288,3,3,1,1))
model:add(Max(3,3,2,2,0,0))
-- STAGE 2
model:add(inceptionFactoryA(288,96,96,96,96,144,"Avg",48))
model:add(inceptionFactoryA(384,96,96,144,96,144,"Avg",96))
model:add(inceptionFactoryB(480,192,240,96,144))
-- STAGE 3
model:add(inceptionFactoryA(864,224,64,96,96,128,"Avg",128))
model:add(inceptionFactoryA(576,192,96,128,96,128,"Avg",128))
model:add(inceptionFactoryA(576,160,128,160,128,160,"Avg",128))
model:add(inceptionFactoryA(608,96,128,192,160,96,"Avg",128))
model:add(inceptionFactoryB(512,128,192,192,256))
-- STAGE 4
model:add(inceptionFactoryA(960,352,192,320,160,224,"Avg",128))
model:add(inceptionFactoryA(1024,352,192,320,192,224,"Max",128))
-- global average pooling
model:add(Avg(7,7,1,1))
model:add(nn.View(1024):setNumInputDims(3))
model:add(nn.Linear(1024,1000))
local function ConvInit(name)
for k,v in pairs(model:findModules(name)) do
local n = v.kW*v.kH*v.nOutputPlane
v.weight:normal(0,math.sqrt(2/n))
if opt.nGPU > 0 then
if cudnn.version >= 4000 then
v.bias = nil
v.gradBias = nil
else
v.bias:zero()
end
end
end
end
local function BNInit(name)
for k,v in pairs(model:findModules(name)) do
v.weight:fill(1)
if opt.nGPU > 0 then
v.bias:zero()
end
end
end
ConvInit('cudnn.SpatialConvolution')
ConvInit('nn.SpatialConvolution')
BNInit('fbnn.SpatialBatchNormalization')
BNInit('cudnn.SpatialBatchNormalization')
BNInit('nn.SpatialBatchNormalization')
for k,v in pairs(model:findModules('nn.Linear')) do
v.bias:zero()
end
model:cuda()
if opt.cudnn == 'deterministic' then
model:apply(function(m)
if m.setMode then m:setMode(1,1,1) end
end)
end
model:get(1).gradInput = nil
return model
end
return createModel
|
--- Utility methods for JSON
-- @module JSONUtils
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local HttpService = game:GetService("HttpService")
local Promise = require("Promise")
local JSONUtils = {}
function JSONUtils.promiseJSONDecode(str)
if type(str) ~= "string" then
return Promise.rejected("Not a string")
end
return Promise.new(function(resolve, reject)
local decoded
local ok, err = pcall(function()
decoded = HttpService:JSONDecode(str)
end)
if not ok then
reject(err)
return
elseif decoded then
resolve(decoded)
return
else
reject("Failed to decode any value")
return
end
end)
end
return JSONUtils |
--- 场景控制器 非必需,对于一些复杂的场景建议使用,把场景中一些处理挪到这里实现
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by yzx.
--- DateTime: 2019/5/30 13:25
--- 使用方法:对应场景如XX场景, 建立XXSceneCtrl 继承BaseSceneCtrl
--- 在XXScene中持有,跟随XXScene生命周期
---@class BattleSceneCtrl:BaseSceneCtrl
local BattleSceneCtrl = BaseClass("BattleSceneCtrl", BaseSceneCtrl)
local base = BaseSceneCtrl
function BattleSceneCtrl:OnCreate()
base.OnCreate(self)
---@type CoBattleScene
self.scene = self.scene
Logger.Log(">>>BattleSceneCtrl:OnCreate")
end
function BattleSceneCtrl:OnCompleteEnter()
base.OnCompleteEnter(self)
Logger.Log(">>>BattleSceneCtrl:OnCompleteEnter")
end
function BattleSceneCtrl:OnLeave()
base.OnLeave(self)
Logger.Log(">>>BattleSceneCtrl:OnLeave")
end
function BattleSceneCtrl:Clear()
end
function BattleSceneCtrl:OnDestroy()
base.OnDestroy(self)
end
--region local 私有
--endregion
--region 一些监听回调处理
--endregion
return BattleSceneCtrl
|
local panelName = "autoParty"
local autopartyui = setupUI([[
Panel
height: 38
BotSwitch
id: status
anchors.top: parent.top
anchors.left: parent.left
text-align: center
width: 130
height: 18
text: Auto Party
Button
id: editPlayerList
anchors.top: prev.top
anchors.left: prev.right
anchors.right: parent.right
margin-left: 3
height: 17
text: Setup
Button
id: ptLeave
text: Leave Party
anchors.left: parent.left
anchors.top: prev.bottom
width: 86
height: 17
margin-top: 3
color: #ee0000
Button
id: ptShare
text: Share XP
anchors.left: prev.right
anchors.top: prev.top
margin-left: 5
height: 17
width: 86
]], parent)
g_ui.loadUIFromString([[
AutoPartyName < Label
background-color: alpha
text-offset: 2 0
focusable: true
height: 16
$focus:
background-color: #00000055
Button
id: remove
text: x
anchors.right: parent.right
margin-right: 15
width: 15
height: 15
AutoPartyListWindow < MainWindow
text: Auto Party
size: 180 275
@onEscape: self:hide()
Label
id: lblLeader
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.right: parent.right
text-align: center
text: Leader Name
TextEdit
id: txtLeader
anchors.left: parent.left
anchors.right: parent.right
anchors.top: prev.bottom
margin-top: 5
Label
id: lblParty
anchors.left: parent.left
anchors.top: prev.bottom
anchors.right: parent.right
margin-top: 5
text-align: center
text: Party List
TextList
id: lstAutoParty
anchors.top: prev.bottom
anchors.left: parent.left
anchors.right: parent.right
margin-top: 5
margin-bottom: 5
padding: 1
height: 83
vertical-scrollbar: AutoPartyListListScrollBar
VerticalScrollBar
id: AutoPartyListListScrollBar
anchors.top: lstAutoParty.top
anchors.bottom: lstAutoParty.bottom
anchors.right: lstAutoParty.right
step: 14
pixels-scroll: true
TextEdit
id: playerName
anchors.left: parent.left
anchors.top: lstAutoParty.bottom
margin-top: 5
width: 120
Button
id: addPlayer
text: +
anchors.right: parent.right
anchors.left: prev.right
anchors.top: prev.top
margin-left: 3
HorizontalSeparator
id: separator
anchors.right: parent.right
anchors.left: parent.left
anchors.top: prev.bottom
margin-top: 8
CheckBox
id: creatureMove
anchors.left: parent.left
anchors.right: parent.right
anchors.top: prev.bottom
margin-top: 6
text: Invite on move
tooltip: This will activate the invite on player move.
HorizontalSeparator
id: separator
anchors.right: parent.right
anchors.left: parent.left
anchors.bottom: closeButton.top
margin-bottom: 8
Button
id: closeButton
text: Close
font: cipsoftFont
anchors.right: parent.right
anchors.bottom: parent.bottom
size: 45 21
]])
if not storage[panelName] then
storage[panelName] = {
leaderName = 'Leader',
autoPartyList = {},
enabled = true,
}
end
if not storage[panelName].onMove then
storage[panelName].onMove = false
end
rootWidget = g_ui.getRootWidget()
if rootWidget then
tcAutoParty = autopartyui.status
autoPartyListWindow = UI.createWindow('AutoPartyListWindow', rootWidget)
autoPartyListWindow:hide()
autopartyui.editPlayerList.onClick = function(widget)
autoPartyListWindow:show()
autoPartyListWindow:raise()
autoPartyListWindow:focus()
end
autopartyui.ptShare.onClick = function(widget)
g_game.partyShareExperience(not player:isPartySharedExperienceActive())
end
autopartyui.ptLeave.onClick = function(widget)
g_game.partyLeave()
end
autoPartyListWindow.closeButton.onClick = function(widget)
autoPartyListWindow:hide()
end
if storage[panelName].autoPartyList and #storage[panelName].autoPartyList > 0 then
for _, pName in ipairs(storage[panelName].autoPartyList) do
local label = g_ui.createWidget("AutoPartyName", autoPartyListWindow.lstAutoParty)
label.remove.onClick = function(widget)
table.removevalue(storage[panelName].autoPartyList, label:getText())
label:destroy()
end
label:setText(pName)
end
end
autoPartyListWindow.addPlayer.onClick = function(widget)
local playerName = autoPartyListWindow.playerName:getText()
if playerName:len() > 0 and not (table.contains(storage[panelName].autoPartyList, playerName, true)
or storage[panelName].leaderName == playerName) then
table.insert(storage[panelName].autoPartyList, playerName)
local label = g_ui.createWidget("AutoPartyName", autoPartyListWindow.lstAutoParty)
label.remove.onClick = function(widget)
table.removevalue(storage[panelName].autoPartyList, label:getText())
label:destroy()
end
label:setText(playerName)
autoPartyListWindow.playerName:setText('')
end
end
autopartyui.status:setOn(storage[panelName].enabled)
autopartyui.status.onClick = function(widget)
storage[panelName].enabled = not storage[panelName].enabled
widget:setOn(storage[panelName].enabled)
end
autoPartyListWindow.creatureMove:setChecked(storage[panelName].onMove)
autoPartyListWindow.creatureMove.onClick = function(widget)
storage[panelName].onMove = not storage[panelName].onMove
widget:setChecked(storage[panelName].onMove)
end
autoPartyListWindow.playerName.onKeyPress = function(self, keyCode, keyboardModifiers)
if not (keyCode == 5) then
return false
end
autoPartyListWindow.addPlayer.onClick()
return true
end
autoPartyListWindow.playerName.onTextChange = function(widget, text)
if table.contains(storage[panelName].autoPartyList, text, true) then
autoPartyListWindow.addPlayer:setColor("#FF0000")
else
autoPartyListWindow.addPlayer:setColor("#FFFFFF")
end
end
autoPartyListWindow.txtLeader.onTextChange = function(widget, text)
storage[panelName].leaderName = text
end
autoPartyListWindow.txtLeader:setText(storage[panelName].leaderName)
onTextMessage(function(mode, text)
if tcAutoParty:isOn() then
if mode == 20 then
if text:find("has joined the party") then
local data = regexMatch(text, "([a-z A-Z-]*) has joined the party")[1][2]
if data then
if table.contains(storage[panelName].autoPartyList, data, true) then
if not player:isPartySharedExperienceActive() then
g_game.partyShareExperience(true)
end
end
end
elseif text:find("has invited you") then
if player:getName():lower() == storage[panelName].leaderName:lower() then
return
end
local data = regexMatch(text, "([a-z A-Z-]*) has invited you")[1][2]
if data then
if storage[panelName].leaderName:lower() == data:lower() then
local leader = getCreatureByName(data, true)
if leader then
g_game.partyJoin(leader:getId())
return
end
end
end
end
end
end
end)
function creatureInvites(creature)
if not creature:isPlayer() or creature == player then return end
if creature:getName():lower() == storage[panelName].leaderName:lower() then
if creature:getShield() == 1 then
g_game.partyJoin(creature:getId())
return
end
end
if player:getName():lower() ~= storage[panelName].leaderName:lower() then return end
if not table.contains(storage[panelName].autoPartyList, creature:getName(), true) then return end
if creature:isPartyMember() or creature:getShield() == 2 then return end
g_game.partyInvite(creature:getId())
end
onCreatureAppear(function(creature)
if tcAutoParty:isOn() then
creatureInvites(creature)
end
end)
onCreaturePositionChange(function(creature, newPos, oldPos)
if tcAutoParty:isOn() and storage[panelName].onMove then
creatureInvites(creature)
end
end)
end
|
local sprotoparser = require "sprotoparser"
local proto = {}
proto.c2s = sprotoparser.parse [[
.package {
type 0 : integer
session 1 : integer
}
handshake 1 {
response {
msg 0 : string
}
}
get 2 {
request {
what 0 : string
}
response {
result 0 : string
}
}
set 3 {
request {
what 0 : string
value 1 : string
}
}
quit 4 {}
login_account 5 {
request {
account 0 : string
password 1 : string
}
}
add_account 6 {
request {
account 1 : string
password 2 : string
}
}
add_user 7 {
request {
name 0 : string
}
}
login_user 8 {
request {
uid 0 : integer
name 1 : string
}
}
]]
proto.s2c = sprotoparser.parse [[
.package {
type 0 : integer
session 1 : integer
}
heartbeat 1 {}
login_account 2 {
request {
result 0 : integer
desc 1 : string
}
}
add_account 3 {
request {
result 0 : integer
account 1 : string
password 2 : string
desc 3 : string
}
}
add_user 4 {
request {
result 0 : integer
name 1 : string
desc 2 : string
uid 3 : integer
}
}
login_user 5 {
request {
result 0 : integer
desc 1 : string
uid 2 : integer
}
}
]]
return proto
|
hook.Add("PopulatePropMenu", "SupinePandora43_Hook_SpawnList", function()
local contents = {}
table.insert(
contents,
{
type = "header",
text = "Hello World!"
}
)
table.insert(
contents,
{
type = "model",
model = "models/props_c17/oildrum001.mdl"
}
)
if CustomizableWeaponry then
table.insert(
contents,
{
type = "weapon",
spawnname = "cw_ak74",
nicename = "Kalash",
material = "entities/weapon_crowbar.png"
}
)
table.insert(
contents,
{
type = "entity",
spawnname = "cw_ammo_545x39",
nicename = "Ammo",
material = "entities/sent_ball.png"
}
)
end
table.insert(
contents,
{
type = "entity",
spawnname = "combine_mine",
nicename = "Hopper Mine",
material = "entities/combine_mine.png"
}
)
-- Vehicles
table.insert(
contents,
{
type = "vehicle",
spawnname = "Airboat",
nicename = "Half-Life 2 Airboat",
material = "entities/Airboat.png"
}
)
table.insert(
contents,
{
type = "vehicle",
spawnname = "Chair_Office2",
nicename = "Executive's Chair",
material = "entities/Chair_Office2.png"
}
)
-- NPCs
table.insert(
contents,
{
type = "npc",
spawnname = "npc_citizen",
nicename = "A random citizen",
material = "entities/npc_citizen.png",
weapon = {"weapon_smg1", "weapon_crowbar"}
}
)
table.insert(
contents,
{
type = "npc",
spawnname = "npc_headcrab",
nicename = "Headhumper",
material = "entities/npc_headcrab.png"
}
)
-- Weapons
table.insert(
contents,
{
type = "weapon",
spawnname = "weapon_smg1",
nicename = "SMG",
material = "entities/weapon_smg1.png"
}
)
spawnmenu.AddPropCategory("SupinePandora43_PropCategory_SpawnList", "IDK", contents, "icon16/page.png")
end) |
if not AI then
return false
end
local Stack = {}
local PriorityQueue = {}
local function lessThan(a, b) return a < b end
-- Stack
function Stack:New()
local stack = {}
setmetatable(stack, {__index = Stack})
return stack
end
function Stack:Push(v)
table.insert(self, v)
end
function Stack:Pop()
local val = self[table.size(self)]
table.remove(self)
return val
end
function Stack:Top()
return self[table.size(self)]
end
function Stack:Size()
return table.size(self)
end
function Stack:IsEmpty()
return table.size(self) == 0
end
-- Queue
--[[function Queue:New()
local queue = {}
setmetatable(queue, {__index = Queue})
return queue
end
function Queue:Push(v)
table.insert(self, v)
end
function Queue:Pop()
local v = self[1]
table.remove(self, 1)
return v
end
function Queue:Size()
return #self
end
function Queue:Top()
return self[1]
end
function Queue:IsEmpty()
return #self == 0
end ]]
-- Priority Queue
local function upi(h, lt, obj, i)
local j = math.floor(i / 2)
local hj = h[j]
while j > 0 and lt(obj, hj) do
h[i] = hj
i, j = j, math.floor(j / 2)
hj = h[j]
end
h[i] = obj
end
local function downi(h, lt, obj, i, n)
local j = i * 2
while j <= n do
local hj = h[j]
if j < n then
local hj1 = h[j + 1]
if lt(hj1, hj) then
j = j + 1
hj = hj1
end
end
if lt(obj, hj) then
break
end
h[i] = hj
i = j
j = j * 2
end
h[i] = obj
end
function PriorityQueue:New(lt)
local heap = { compareCallback = lt or lessThan }
setmetatable(heap, {__index = PriorityQueue})
return heap
end
function PriorityQueue:Top()
return self[1]
end
function PriorityQueue:Push(v)
return upi(self, self.compareCallback, v, table.size(self) + 1)
end
function PriorityQueue:Pop()
local size = table.size(self)
assert(size > 0, "PriorityQueue:Pop() Heap is empty")
local ret = self[1]
if size > 1 then
local last = self[size]
self[1] = last
self[size] = nil
downi(self, self.compareCallback, last, 1, size - 1)
else
self[1] = nil
end
return ret
end
function PriorityQueue:Size()
return table.size(self)
end
function PriorityQueue:IsEmpty()
return table.size(self) == 0
end
-- Register
AI.Stack = Stack
AI.PriorityQueue = PriorityQueue |
local dr = require "deadReckoner"
local loc= Locus.new(0,0,0)
local function testBearTo()
dr.bearTo(dr.PORT)
assert(dr.heading==dr.PORT,
"should be PORT now; instead"..
" it's ".. dr.WAYS[dr.heading] )
dr.bearTo(dr.FORE)
assert(dr.heading==dr.FORE,
"should be FORE; instead"..
" it's ".. dr.WAYS[dr.heading])
print("heading: "..
dr.WAYS[dr.heading] )
end
-- testBearTo()
local function testLocus()
loc.x = 1
assert( loc.x==1, "Locus.x 1" )
end
local function testHowFarFromHome()
dr.place.x= 1
dr.place.y= 2
dr.place.z= 3
assert(6== dr.howFarFromHome(),
"howFarFromHome() FAILED")
end
local function testMove()
dr.place.x= 0
dr.place.y= 0
dr.place.z= 0
dr.move(dr.AHEAD)
assert(dr.place.z==1, "z should be 1")
dr.bearTo( dr.PORT )
dr.move(dr.AHEAD)
assert(dr.place.x==-1,"x should be -1")
end
local function testFurthestWay()
dr.place.x= 0
dr.place.y= 0
dr.place.z= 0
loc.x= -50
loc.y= 25
loc.z= 10
local way = 0
local dist = 0
way, dist= dr.furthestWay(loc)
assert( way==dr.PORT,
"furthestWay way is wrong" )
assert( dist==50,
"furthestWay dist is wrong" )
end
local vm = require "veinMiner"
local function testIsVeinExplored()
table.insert(vm.cubeStack, loc )
assert( not vm.isVeinExplored(),
"isVeinExplored should be false")
local l=table.remove(vm.cubeStack)
assert( vm.isVeinExplored(),
"isVeinExplored should be true")
end
local function testIsFuelOK()
assert( vm.isFuelOK(),
"fuel should be OK" )
vm.previousDistance = 145
assert( not vm.isFuelOK(),
"fuel should *not* be OK" )
end
local function testCheck()
vm.targetBlockName="minecraft:log"
assert(vm.check(dr.AHEAD),"AHEAD")
assert(vm.check(dr.DOWN),"DOWN")
assert(vm.check(dr.UP),"UP")
assert(table.maxn(vm.cubeStack)==3,
"Should be 3 cubes in stack." )
vm.explore(dr.STARBOARD,1)
vm.targetBlockName="somethingElse"
assert(not vm.check(dr.AHEAD),"AHEAD")
assert(not vm.check(dr.DOWN),"DOWN")
assert(not vm.check(dr.UP),"UP")
assert(table.maxn(vm.cubeStack)==3,
"Should be 3 cubes in stack." )
end
local function testInspected()
vm.setInspected(1,-20,3)
vm.setInspected(100,-20,3)
assert( vm.isInspected(1,-20,3),
"1,-2,3 should be inspected." )
assert( not vm.isInspected(1,2,3),
"1,2,3 should not be inspected.")
end
local function testDig()
assert( vm.dig(dr.AHEAD), "AHEAD" )
assert( vm.dig(dr.UP), "UP" )
assert( vm.dig(dr.DOWN), "DOWN" )
end
local function testExplore()
vm.explore( dr.FORE, 2 )
assert(dr.place.z==2,"z should be 2")
end
local function testXYandZ()
local dest= Locus.new(10,20,30)
vm.exploreTo(dest)
end
local function testGolookAt()
vm.goLookAt(-1,1,1)
assert(dr.place.x==-1, "X no good")
assert(dr.place.y==0, "Y no good")
assert(dr.place.z==1, "Z no good")
end
local function testInspectACube()
table.insert( vm.cubeStack, loc )
vm.inspectACube()
local count=vm.inspectedCount
assert(count==26,
"inspected count: ".. count )
end
local function testIsInvtrySpaceAvail()
local isOK = vm.isInvtrySpaceAvail()
assert(isOK,"should've been enough")
end
local function testMine()
local args = { "-r" }
vm.mine( args )
-- assert( not vm.isFuelOK4Cube(),
-- "fuel should be low" )
end
testMine()
|
function EFFECT:Init(data)
self.Origin = data:GetOrigin()
local emitter = ParticleEmitter( self.Origin + Vector( 0, 0, 16 ) )
local light = DynamicLight(self:EntIndex())
if (light) then
light.Pos = self:GetPos()
light.r = 225
light.g = 155
light.b = 200
light.Brightness = 3
light.Decay = 10
light.Size = 512
light.DieTime = CurTime() + 0.3
end
local particle = emitter:Add("effects/halo_ce/flare_generic2", self.Origin)
particle:SetVelocity( 25 * VectorRand() )
particle:SetDieTime( 0.2 )
particle:SetStartAlpha( 255 )
particle:SetEndAlpha( 0 )
particle:SetStartSize( math.Rand(5,15) )
particle:SetEndSize( math.Rand(150,300) )
particle:SetRoll( math.Rand(0,360) )
particle:SetRollDelta( math.Rand(0,0) )
particle:SetColor( 255, 255, 255 )
particle:SetAirResistance( 55 )
particle:SetLighting( false )
particle:SetCollide( false )
for i= 0,5 do
local particle = emitter:Add("effects/halo3/smoke_dark", self.Origin)
particle:SetVelocity( Vector(math.Rand(75, 100),math.Rand(75, 100),math.Rand(300, 750)) )
particle:SetDieTime( math.Rand(2,3) )
particle:SetStartAlpha( 55 )
particle:SetEndAlpha( 255 )
particle:SetStartSize( math.Rand(95,100) )
particle:SetEndSize( math.Rand(125,135) )
particle:SetRoll( math.Rand(0,360) )
particle:SetRollDelta( math.Rand(-0.5,0.5) )
particle:SetColor( 255, 225, 225 )
particle:SetAirResistance( 55 )
particle:SetGravity( Vector( 0, 0, math.Rand(-325,-425) ) )
particle:SetLighting( true )
particle:SetCollide( false )
end
for i = 0,5 do
particle = emitter:Add( "effects/halo_ce/flare_generic" , self.Origin )
particle:SetVelocity( 1 * VectorRand() )
particle:SetDieTime( math.Rand(0.15, 0.2) )
particle:SetStartAlpha( 200 )
particle:SetEndAlpha( 0 )
particle:SetStartSize( math.Rand(20,35) )
particle:SetEndSize( math.Rand(175,225) )
particle:SetRoll( math.Rand(0,360) )
particle:SetRollDelta( math.Rand(-1,1) )
particle:SetColor( 255,255,200 )
particle:SetAirResistance( 200 )
particle:SetGravity( Vector( 0, 0, math.Rand(10,40) ) )
particle:SetLighting( false )
particle:SetCollide( true )
particle:SetBounce( 0.5 )
end
particle = emitter:Add( "effects/halo_ce/flare_generic2a", self.Origin )
particle:SetVelocity( 1 * VectorRand() )
particle:SetDieTime( math.Rand(0.15, 0.2) )
particle:SetStartAlpha( 200 )
particle:SetEndAlpha( 0 )
particle:SetStartSize( math.Rand(20,35) )
particle:SetEndSize( math.Rand(250,400) )
particle:SetRoll( math.Rand(0,360) )
particle:SetRollDelta( math.Rand(-1,1) )
particle:SetColor( 255,200,50 )
particle:SetAirResistance( 200 )
particle:SetGravity( Vector( 0, 0, math.Rand(10,40) ) )
particle:SetLighting( false )
particle:SetCollide( true )
particle:SetBounce( 0.5 )
emitter:Finish()
end
function EFFECT:Think()
return false
end
function EFFECT:Render()
end |
local vgc = vgui.Create
function CreateWindowFrame(parent)
parent = parent or nil
local window = vgc("DFrame", parent)
window.lblTitle:SetFont("VBFONT_DERMANORMAL")
window.lblTitle:SetTextColor(COLOR_WHITE)
function window:Paint()
draw.RoundedBoxEx(5, 0, 25, window:GetWide(), window:GetTall() - 25, COLOR_MENU_BAR, false, false, true, true)
draw.RoundedBoxEx(5, 0, 0, window:GetWide(), 25, COLOR_MENU_BACK, true, true, false, false)
surface.SetDrawColor(Color(20, 20, 20, 100))
surface.DrawOutlinedRect(0, 0, window:GetWide(), window:GetTall())
end
return window
end |
return {
shocker = {
areaofeffect = 192,
avoidfeature = 0,
avoidfriendly = 0,
collidefriendly = 0,
craterboost = 0,
cratermult = 0,
edgeeffectiveness = 0.5,
explosiongenerator = "custom:FLASHSMALLBUILDING",
heightboostfactor = 2.8,
impulseboost = 0.5,
impulsefactor = 0.5,
name = "ShockerHeavyCannon",
noselfdamage = 1,
predictboost = 0.75,
range = 1325,
reloadtime = 6,
size = 5,
soundhit = "xplomed2",
soundstart = "cannhvy5",
targetborder = 1,
turret = 1,
weaponvelocity = 610,
damage = {
default = 1100,
},
},
}
|
app:DoAction("App_CustomizeHotkeys", {})
|
local Frame = script.Parent
local NotesButton = Frame:WaitForChild("HomeScreenApps"):WaitForChild("Notes")
local BackButton = Frame.NotesPage:WaitForChild("Back")
local SaveButton = Frame.NotesPage:WaitForChild("Save")
local Notes = Frame.NotesPage:WaitForChild("Notes")
local Notes = Frame.NotesPage:WaitForChild("Notes")
local NotesValue = game.Players.LocalPlayer.Character:FindFirstChild("iExotic 11 Pro Max").NotesValue
local HomeScreenApps = Frame:WaitForChild("HomeScreenApps"):GetChildren()
NotesButton.MouseButton1Click:Connect(function()
local NotesPage = Frame.NotesPage:GetChildren()
for _,v in pairs (NotesPage)do
v.Visible = true
end
Notes.Text = NotesValue.Value
for _,v in pairs (HomeScreenApps)do
v.Visible = false
end
end)
BackButton.MouseButton1Click:Connect(function()
local NotesPage = Frame.NotesPage:GetChildren()
for _,v in pairs (NotesPage)do
v.Visible = false
end
for _,v in pairs (HomeScreenApps)do
v.Visible = true
end
end)
SaveButton.MouseButton1Click:Connect(function()
NotesValue.Value = Notes.Text
end) |
---------------------------------------------------------------------------------------------------
-- Item: Use Case: request is allowed by policies but app is already subscribed for specified parameter
--
-- Requirement summary:
-- [SubscribeVehicleData] As a mobile app wants to send a request to subscribe for specified parameter
--
-- Description:
-- In case:
-- Mobile application sends valid SubscribeVehicleData to SDL and this request
-- is allowed by Policies but app is already subscribed for specified parameter
-- SDL must:
-- SDL responds IGNORED, success:false and info: "Already subscribed on some provided VehicleData."
-- to mobile application and doesn't transfer this request to HMI
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/API/VehicleData/commonVehicleData')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
--[[ Local Variables ]]
local rpc = {
name = "SubscribeVehicleData",
params = {
engineOilLife = true,
fuelRange = true,
tirePressure = true,
electronicParkBrakeStatus = true,
turnSignal = true
}
}
local vehicleDataResults = {
engineOilLife = {
dataType = "VEHICLEDATA_ENGINEOILLIFE",
resultCode = "SUCCESS"
},
fuelRange = {
dataType = "VEHICLEDATA_FUELRANGE",
resultCode = "SUCCESS"
},
tirePressure = {
dataType = "VEHICLEDATA_TIREPRESSURE",
resultCode = "SUCCESS"
},
electronicParkBrakeStatus = {
dataType = "VEHICLEDATA_ELECTRONICPARKBRAKESTATUS",
resultCode = "SUCCESS"
},
turnSignal = {
dataType = "VEHICLEDATA_TURNSIGNAL",
resultCode = "SUCCESS"
}
}
local vehicleDataResults2 = {
engineOilLife = {
dataType = "VEHICLEDATA_ENGINEOILLIFE",
resultCode = "DATA_ALREADY_SUBSCRIBED"
},
fuelRange = {
dataType = "VEHICLEDATA_FUELRANGE",
resultCode = "DATA_ALREADY_SUBSCRIBED"
},
tirePressure = {
dataType = "VEHICLEDATA_TIREPRESSURE",
resultCode = "DATA_ALREADY_SUBSCRIBED"
},
turnSignal = {
dataType = "VEHICLEDATA_TURNSIGNAL",
resultCode = "DATA_ALREADY_SUBSCRIBED"
},
electronicParkBrakeStatus = {
dataType = "VEHICLEDATA_TIREPRESSURE",
resultCode = "DATA_ALREADY_SUBSCRIBED"
}
}
--[[ Local Functions ]]
local function processRPCSuccess(self)
local mobileSession = common.getMobileSession(self, 1)
local cid = mobileSession:SendRPC(rpc.name, rpc.params)
EXPECT_HMICALL("VehicleInfo." .. rpc.name, rpc.params)
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS",
vehicleDataResults)
end)
local responseParams = vehicleDataResults
responseParams.success = true
responseParams.resultCode = "SUCCESS"
mobileSession:ExpectResponse(cid, responseParams)
end
local function processRPCIgnored(self)
local mobileSession = common.getMobileSession(self, 1)
local cid = mobileSession:SendRPC(rpc.name, rpc.params)
EXPECT_HMICALL("VehicleInfo." .. rpc.name, rpc.params):Times(0)
commonTestCases:DelayedExp(common.timeout)
local responseParams = vehicleDataResults2
responseParams.success = false
responseParams.resultCode = "IGNORED"
mobileSession:ExpectResponse(cid, responseParams)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("RAI with PTU", common.registerAppWithPTU)
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
runner.Step("RPC " .. rpc.name .. " 1st time" , processRPCSuccess)
runner.Step("RPC " .. rpc.name .. " 2nd time" , processRPCIgnored)
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
mass_res = {
cast = function(player)
check = player:getObjectsInArea(BL_PC)
if (#check > 0) then
for i = 1, #check do
if (check[i].state == 1) then
check[i].state = 0
check[i].health = check[i].maxHealth
check[i].magic = check[i].maxMagic
check[i]:sendStatus()
check[i]:updateState()
end
end
end
end
}
|
--[[
Copyright 2020 Samarth Ramesh & wsor4035
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 storage = minetest.get_mod_storage()
minetest.deserialize(storage:get_string("banned_names"))
banned_names=minetest.deserialize(storage:get_string("banned_names")) or {"sex","fuck","damn","drug","suicid"}
print("[sriniban] loaded")
minetest.register_on_prejoinplayer(function(name)
for k,v in pairs(banned_names) do
if string.find(string.lower(name),string.lower(v)) then
--logging
print("[sriniban] user: " .. name .. " attempted to join with disallowed word: " .. v)
return "your name contains: " .. v .. " and is not allowed here, please come back with a better name"
end
end
end)
minetest.register_chatcommand("add_name", {
params = "<string>",
privs = {server= true},
description = "adds a name to banlist\nCAUTION adding a single letter can be catastrophic. always be careful when adding names",
func = function(name,param)
if param ~= "" then
table.insert(banned_names,tostring(param))
print(tostring(param))
minetest.chat_send_all("added "..param.." to the list of banned words")
local serial_table = minetest.serialize(banned_names)
storage:set_string("banned_names", serial_table)
else
minetest.chat_send_player(name, "Captain Spock tells us that expexting to add a new banned word without specefying it is senseless")
end
end
})
minetest.register_chatcommand("list_names", {
description = "lists all the banned names",
privs = {server= true},
func= function(name)
for k,v in pairs(banned_names) do
minetest.chat_send_player(name, banned_names[k])
end
end
})
minetest.register_chatcommand("rm_name",{
description = "removes a name from the ban list",
params = "<name>",
privs = {server=true},
func = function(name, param)
if param ~="" then
for k in pairs(banned_names) do
if param == banned_names[k] then
table.remove(banned_names,k)
end
end
storage:set_string("banned_names", minetest.serialize(banned_names))
end
end
})
|
object_tangible_deed_vehicle_deed_havoc_ship_deed = object_tangible_deed_vehicle_deed_shared_havoc_ship_deed:new {
}
ObjectTemplates:addTemplate(object_tangible_deed_vehicle_deed_havoc_ship_deed, "object/tangible/deed/vehicle_deed/havoc_ship_deed.iff")
|
local function getFirework()
local firework = {}
firework.isInitialized = false
firework.x = nil
firework.y = nil
firework.particles = {}
firework.totalParticles = 120
firework.particlesSpeedRange = {min = 100, max = 300}
firework.radius = 100
firework.rangeX = {min = firework.radius, max = window.width - firework.radius}
firework.rangeY = {min = firework.radius, max = 2 * firework.radius}
firework.outOfBoundCount = 0
firework.hasExploded = false
firework.rocket = getParticle(0, window.height, 0, 0)
firework.rocketSpeed = 800
firework.gravity = getVector(0, 0.12)
firework.color = {255, love.math.random(255), love.math.random(255)}
function firework.setRandomPosition()
firework.x = love.math.random(firework.rangeX.min, firework.rangeX.max)
firework.y = love.math.random(firework.rangeY.min, firework.rangeY.max)
end
function firework.initParticles(dt)
for i = 1, firework.totalParticles do
local speed = love.math.random(firework.particlesSpeedRange.min, firework.particlesSpeedRange.max) * dt
local angle = love.math.random() * math.pi * 2
firework.particles[i] = getParticle(firework.x, firework.y, speed, angle)
firework.particles[i].isVisible = true
end
end
function firework.resetParticles(dt)
for i, particle in ipairs(firework.particles) do
local speed = love.math.random(firework.particlesSpeedRange.min, firework.particlesSpeedRange.max) * dt
local angle = love.math.random() * math.pi * 2
particle.position.setX(firework.x)
particle.position.setY(firework.y)
particle.velocity.setLength(speed)
particle.velocity.setAngle(angle)
particle.isVisible = true
end
end
function firework.resetRocket(dt)
firework.setRandomPosition()
firework.rocket.hasExploded = false
firework.rocket.position.setX(firework.x)
firework.rocket.position.setY(window.height)
firework.rocket.velocity.setLength(firework.rocketSpeed * dt)
firework.rocket.velocity.setAngle(-math.pi * 0.5)
end
function firework.update(dt)
if not firework.isInitialized then
firework.setRandomPosition()
firework.resetRocket(dt)
firework.initParticles(dt)
firework.isInitialized = true
end
if firework.rocket.position.getY() <= firework.y then
firework.rocket.hasExploded = true
end
if not firework.rocket.hasExploded then
firework.rocket.update()
return
end
for i, particle in ipairs(firework.particles) do
particle.accelerate(firework.gravity)
particle.update()
end
for i, particle in ipairs(firework.particles) do
local magnitude = math.sqrt(math.pow(particle.position.getX() - firework.x, 2) + math.pow(particle.position.getY() - firework.y, 2))
if(magnitude >= firework.radius) then
firework.outOfBoundCount = firework.outOfBoundCount + 1
particle.isVisible = false
end
end
if firework.outOfBoundCount >= firework.totalParticles then
firework.setRandomPosition()
firework.resetRocket(dt)
firework.resetParticles(dt)
end
firework.outOfBoundCount = 0
end
function firework.draw()
love.graphics.setColor(firework.color)
if not firework.rocket.hasExploded then
--love.graphics.circle("fill", firework.rocket.position.getX(), firework.rocket.position.getY(), 5)
love.graphics.rectangle("fill", firework.rocket.position.getX(), firework.rocket.position.getY(), 5, 10)
return
end
for i, particle in ipairs(firework.particles) do
if particle.isVisible then
--love.graphics.circle("fill", particle.position.getX(), particle.position.getY(), 1)
love.graphics.rectangle("fill", particle.position.getX(), particle.position.getY(), 2, 2)
end
end
end
return firework
end
return getFirework
|
local file = io.open("GLOBAL rev4.lua")
local content = file:read("*a")
io.close(file)
-- note: there is event skip at event 511 in rev4
local replacements =
{
["evt%.CanShowTopic%[(%d+)%]"] = eventNumberReplacements("evt.CanShowTopic[%d]"),
["evt%.global%[(%d+)%]"] = eventNumberReplacements("evt.global[%d]"),
["evt%.Cmp%(\"QBits\", (%d+)%)"] = function(num) return ("evt.Cmp(\"QBits\", %d)"):format(getQuestBit(num)) end,
["evt%.Set%(\"QBits\", (%d+)%)"] = function(num) return ("evt.Set(\"QBits\", %d)"):format(getQuestBit(num)) end,
["evt%.Add%(\"QBits\", (%d+)%)"] = function(num) return ("evt.Add(\"QBits\", %d)"):format(getQuestBit(num)) end,
["evt%.Subtract%(\"QBits\", (%d+)%)"] = function(num) return ("evt.Subtract(\"QBits\", %d)"):format(getQuestBit(num)) end,
["evt%.SetMessage%((%d+)%)"] =
function(message)
message = tonumber(message)
return ("evt.SetMessage(%d)"):format(getMessage(message))
end,
["evt%.SetNPCTopic%{NPC = (%d+), Index = (%d+), Event = (%d+)%}"] =
function(npc, index, event)
npc = tonumber(npc)
index = tonumber(index)
event = tonumber(event)
local indexes = {[0] = "A", "B", "C", "D", "E", "F"}
return ("evt.SetNPCTopic{NPC = %d, Index = %d, Event = %d}"):format(getNPC(npc), index, getEvent(event))
--return ("Game.NPC[%d].Event%s = %d"):format(getNPC(npc), indexes[index], getEvent(event))
end,
["evt%.Subtract%(\"NPCs\", (%d+)%)"] =
function(npc)
npc = tonumber(npc)
return ("evt.Subtract(\"NPCs\", %d)"):format(getNPC(npc))
end,
["evt%.Add%(\"NPCs\", (%d+)%)"] =
function(npc)
npc = tonumber(npc)
return ("evt.Add(\"NPCs\", %d)"):format(getNPC(npc))
end,
["evt%.Set%(\"NPCs\", (%d+)%)"] =
function(npc)
npc = tonumber(npc)
return ("evt.Set(\"NPCs\", %d)"):format(getNPC(npc))
end,
["evt%.Cmp%(\"NPCs\", (%d+)%)"] =
function(npc)
npc = tonumber(npc)
return ("evt.Cmp(\"NPCs\", %d)"):format(getNPC(npc))
end,
["evt%.Add%(\"Awards\", (%d+)%)"] =
function(award)
award = tonumber(award)
local mappingsFromMM7PromotionAwardsToMergeQBits = -- generated with generateMappingsFromMM7PromotionAwardsToMergeQBits
{
[10] = 1560, [11] = 1561, [12] = 1562, [13] = 1563, [16] = 1566, [17] = 1567, [18] = 1568, [19] = 1569, [22] = 1572, [23] = 1573, [24] = 1574, [25] = 1575, [27] = 1577, [28] = 1578, [29] = 1579, [30] = 1580, [31] = 1581, [34] = 1584, [35] = 1585, [36] = 1586, [37] = 1587, [38] = 1588, [39] = 1589, [40] = 1590, [41] = 1591, [42] = 1592, [43] = 1593, [44] = 1594, [45] = 1595, [50] = 1596, [51] = 1597, [52] = 1598, [53] = 1599, [54] = 1600, [55] = 1601, [56] = 1602, [57] = 1603, [58] = 1604, [59] = 1605, [60] = 1606, [62] = 1607, [63] = 1608, [64] = 1609, [65] = 1610, [66] = 1611, [67] = 1612, [68] = 1613, [69] = 1614, [70] = 1615, [71] = 1616, [72] = 1617, [73] = 1618, [74] = 1619, [75] = 1620, [76] = 1621, [77] = 1622, [78] = 1623, [79] = 1624
}
if mappingsFromMM7PromotionAwardsToMergeQBits[award] ~= nil then
-- promotion award, special processing
return ("evt.Add(\"QBits\", %d)"):format(mappingsFromMM7PromotionAwardsToMergeQBits[award])
else
--local awards = LoadBasicTextTable("tab\\AWARDS rev4.txt", 0)
--print("Not promotion award: " .. awards[award + 1][2])
end
local a2 = award
award = getAward(award)
if award == -1 then return ("--" .. " evt.Add(\"Awards\", %d)"):format(a2) end
return ("evt.Add(\"Awards\", %d)"):format(award)
end,
["evt%.Set%(\"Awards\", (%d+)%)"] =
function(award)
award = tonumber(award)
local mappingsFromMM7PromotionAwardsToMergeQBits = -- generated with generateMappingsFromMM7PromotionAwardsToMergeQBits
{
[10] = 1560, [11] = 1561, [12] = 1562, [13] = 1563, [16] = 1566, [17] = 1567, [18] = 1568, [19] = 1569, [22] = 1572, [23] = 1573, [24] = 1574, [25] = 1575, [27] = 1577, [28] = 1578, [29] = 1579, [30] = 1580, [31] = 1581, [34] = 1584, [35] = 1585, [36] = 1586, [37] = 1587, [38] = 1588, [39] = 1589, [40] = 1590, [41] = 1591, [42] = 1592, [43] = 1593, [44] = 1594, [45] = 1595, [50] = 1596, [51] = 1597, [52] = 1598, [53] = 1599, [54] = 1600, [55] = 1601, [56] = 1602, [57] = 1603, [58] = 1604, [59] = 1605, [60] = 1606, [62] = 1607, [63] = 1608, [64] = 1609, [65] = 1610, [66] = 1611, [67] = 1612, [68] = 1613, [69] = 1614, [70] = 1615, [71] = 1616, [72] = 1617, [73] = 1618, [74] = 1619, [75] = 1620, [76] = 1621, [77] = 1622, [78] = 1623, [79] = 1624
}
if mappingsFromMM7PromotionAwardsToMergeQBits[award] ~= nil then
-- promotion award, special processing
return ("evt.Set(\"QBits\", %d)"):format(mappingsFromMM7PromotionAwardsToMergeQBits[award])
else
--local awards = LoadBasicTextTable("tab\\AWARDS rev4.txt", 0)
--print("Not promotion award: " .. awards[award + 1][2])
end
local a2 = award
award = getAward(award)
if award == -1 then return ("--" .. " evt.Set(\"Awards\", %d)"):format(a2) end
return ("evt.Set(\"Awards\", %d)"):format(award)
end,
["evt%.Cmp%(\"Awards\", (%d+)%)"] =
function(award)
award = tonumber(award)
local mappingsFromMM7PromotionAwardsToMergeQBits = -- generated with generateMappingsFromMM7PromotionAwardsToMergeQBits
{
[10] = 1560, [11] = 1561, [12] = 1562, [13] = 1563, [16] = 1566, [17] = 1567, [18] = 1568, [19] = 1569, [22] = 1572, [23] = 1573, [24] = 1574, [25] = 1575, [27] = 1577, [28] = 1578, [29] = 1579, [30] = 1580, [31] = 1581, [34] = 1584, [35] = 1585, [36] = 1586, [37] = 1587, [38] = 1588, [39] = 1589, [40] = 1590, [41] = 1591, [42] = 1592, [43] = 1593, [44] = 1594, [45] = 1595, [50] = 1596, [51] = 1597, [52] = 1598, [53] = 1599, [54] = 1600, [55] = 1601, [56] = 1602, [57] = 1603, [58] = 1604, [59] = 1605, [60] = 1606, [62] = 1607, [63] = 1608, [64] = 1609, [65] = 1610, [66] = 1611, [67] = 1612, [68] = 1613, [69] = 1614, [70] = 1615, [71] = 1616, [72] = 1617, [73] = 1618, [74] = 1619, [75] = 1620, [76] = 1621, [77] = 1622, [78] = 1623, [79] = 1624
}
if mappingsFromMM7PromotionAwardsToMergeQBits[award] ~= nil then
-- promotion award, special processing
return ("evt.Cmp(\"QBits\", %d)"):format(mappingsFromMM7PromotionAwardsToMergeQBits[award])
else
--local awards = LoadBasicTextTable("tab\\AWARDS rev4.txt", 0)
--print("Not promotion award: " .. awards[award + 1][2])
end
local a2 = award
award = getAward(award)
if award == -1 then return ("--" .. " evt.Cmp(\"Awards\", %d)"):format(a2) end
return ("evt.Cmp(\"Awards\", %d)"):format(award)
end,
["evt%.Subtract%(\"Awards\", (%d+)%)"] =
function(award)
award = tonumber(award)
local mappingsFromMM7PromotionAwardsToMergeQBits = -- generated with generateMappingsFromMM7PromotionAwardsToMergeQBits
{
[10] = 1560, [11] = 1561, [12] = 1562, [13] = 1563, [16] = 1566, [17] = 1567, [18] = 1568, [19] = 1569, [22] = 1572, [23] = 1573, [24] = 1574, [25] = 1575, [27] = 1577, [28] = 1578, [29] = 1579, [30] = 1580, [31] = 1581, [34] = 1584, [35] = 1585, [36] = 1586, [37] = 1587, [38] = 1588, [39] = 1589, [40] = 1590, [41] = 1591, [42] = 1592, [43] = 1593, [44] = 1594, [45] = 1595, [50] = 1596, [51] = 1597, [52] = 1598, [53] = 1599, [54] = 1600, [55] = 1601, [56] = 1602, [57] = 1603, [58] = 1604, [59] = 1605, [60] = 1606, [62] = 1607, [63] = 1608, [64] = 1609, [65] = 1610, [66] = 1611, [67] = 1612, [68] = 1613, [69] = 1614, [70] = 1615, [71] = 1616, [72] = 1617, [73] = 1618, [74] = 1619, [75] = 1620, [76] = 1621, [77] = 1622, [78] = 1623, [79] = 1624
}
if mappingsFromMM7PromotionAwardsToMergeQBits[award] ~= nil then
-- promotion award, special processing
return ("evt.Subtract(\"QBits\", %d)"):format(mappingsFromMM7PromotionAwardsToMergeQBits[award])
else
--local awards = LoadBasicTextTable("tab\\AWARDS rev4.txt", 0)
--print("Not promotion award: " .. awards[award + 1][2])
end
local a2 = award
award = getAward(award)
if award == -1 then return ("--" .. " evt.Subtract(\"Awards\", %d)"):format(a2) end
return ("evt.Subtract(\"Awards\", %d)"):format(award)
end,
["evt%.SetNPCGroupNews%{NPCGroup = (%d+), NPCNews = (%d+)%}"] =
function(group, news)
group = tonumber(group)
news = tonumber(news)
return ("evt.SetNPCGroupNews{NPCGroup = %d, NPCNews = %d}"):format(getNpcGroup(group), news + 51)
end,
["evt%.SetNPCGreeting%{NPC = (%d+), Greeting = (%d+)%}"] =
function (npc, greeting)
npc = tonumber(npc)
greeting = tonumber(greeting)
return ("evt.SetNPCGreeting{NPC = %d, Greeting = %d}"):format(getNPC(npc), getGreeting(greeting))
end,
["evt%.Cmp%(\"Inventory\", (%d+)%)"] =
function(item)
item = tonumber(item)
return ("evt.Cmp(\"Inventory\", %d)"):format(getItem(item))
end,
["evt%.Add%(\"Inventory\", (%d+)%)"] =
function(item)
item = tonumber(item)
return ("evt.Add(\"Inventory\", %d)"):format(getItem(item))
end,
["evt%.Subtract%(\"Inventory\", (%d+)%)"] =
function(item)
item = tonumber(item)
return ("evt.Subtract(\"Inventory\", %d)"):format(getItem(item))
end,
["evt%.Set%(\"Inventory\", (%d+)%)"] =
function(item)
item = tonumber(item)
-- apparently evt.Set("Inventory", num) makes character diseased...
return ("evt.Add(\"Inventory\", %d)"):format(getItem(item))
end,
["evt%.MoveNPC%{NPC = (%d+), HouseId = (%d+)%}"] =
function(npc, houseid)
npc = tonumber(npc)
houseid = tonumber(houseid)
return ("evt.MoveNPC{NPC = %d, HouseId = %d}"):format(getNPC(npc), getHouseID(houseid))
end,
["evt%.SetNPCItem%{NPC = (%d+), Item = (%d+), On = (%w+)%}"] =
function(npc, item, on)
npc = tonumber(npc)
item = tonumber(item)
return ("evt.SetNPCItem{NPC = %d, Item = %d, On = %s}"):format(getNPC(npc), getItem(item), on)
end,
--[[["evt%.Add%(\"History(%d+)\", (%d+)%)"] =
function(historyid, dummy)
historyid = tonumber(historyid)
dummy = tonumber(dummy)
return ("--" .. " evt.Add(\"History%d\", %d)"):format(historyid, dummy)
end,]]--
["evt%.SetMonGroupBit%{NPCGroup = (%d+), Bit = ([%w%.]+), On = (%w+)%}"]
= function(npcgroup, bit, on)
npcgroup = tonumber(npcgroup)
return ("evt.SetMonGroupBit{NPCGroup = %d, Bit = %s, On = %s}"):format(getNpcGroup(npcgroup), bit, on)
end,
["evt%.Set%(\"AutonotesBits\", (%d+)%)"] =
function(autonote)
autonote = tonumber(autonote)
return ("evt.Set(\"AutonotesBits\", %d)"):format(getAutonote(autonote))
end,
["evt%.ChangeEvent%((%d+)%)"] =
function(event)
event = tonumber(event)
return ("evt.ChangeEvent(%d)"):format(getEvent(event))
end,
["evt%.StatusText%((%d+)%)"] =
function(message)
message = tonumber(message)
return ("evt.StatusText(%d)"):format(getMessage(message))
end,
["evt%.CheckMonstersKilled%{CheckType = (%d+), Id = (%d+), Count = (%d+)%}"] =
function(checktype, id, count)
checktype = tonumber(checktype)
id = tonumber(id)
count = tonumber(count)
if checktype == 1 then
return ("evt.CheckMonstersKilled{CheckType = %d, Id = %d, Count = %d}"):format(checktype, id + 51, count)
elseif checktype == 2 then
return ("evt.CheckMonstersKilled{CheckType = %d, Id = %d, Count = %d}"):format(checktype, getMonster(id), count)
elseif checktype == 4 then
print("While processing scripts encountered evt.CheckMonstersKilled with CheckType of 4, need to take care of that")
end
return ("evt.CheckMonstersKilled{CheckType = %d, Id = %d, Count = %d}"):format(checktype, id, count)
end
}
--[[ TODO
* SBG's blessed items have red crossed circle icon when equipped - idk how to fix this
* after windiff newly downloaded revamp's directory with my own directory
--]]
--[[ Script files to move to github folder
* Quest_MM7Lich.lua
* Rev4 for Merge.lua
* map and global scripts (incl. MM6/MM8 ones - changed ddmapbuffs)
* Rev4 for Merge change spell damage.lua
* Quest_FortRiverstride.lua
--]]
--[[ TODOs completed
* <del>fix getHouseID (create table of overriding mappings from rev4 to merge in case of for example hostels) - both here and in parseNpcData.lua</del>
* <del>promoted awards checks are changed into qbits in merge</del>
* <del>check if class consts (const.Class.Thief for example) is good for merge</del>
* <del>check if setMonGroupBit works correctly</del>
* <del>check strange avlee teachers greetings ("Help me!")</del>
* <del>BDJ goodbye topic giving wrong message</del>
* <del>sort entries in mapstats</del>
* <del>process npctext</del>
* <del>fix adventurers in temple of the moon not dropping items: iterate through monsters after loading map, find adventurer index and give item to him</del>
* <del>fix skill barrels code</del>
* <del>fix mm7 barrels to give +5</del>
* <del>the gauntlet: lord godwinson, the coding fortress: BDJ the coding wizard, fix him (move to correct location)</del>
* <del>inspect map d16.blv for what's changed (couldn't find anything in the first pass) - vampire cloak</del>
* <del>stone city check chests</del>
* <del>check chests in 7d12.blv</del>
* <del>five rings in chests in stone city</del>
* <del>getItem() fixes (potions etc.)</del>
* <del>d29.blv - angel messenger</del>
* <del>7d28.lua - map editor stuff</del>
* <del>check ancient weapons in items.txt</del>
* <del>check d08.blv for crashes relating to Lord Godwinson placemon id</del>
* <del>BDJ should become hostile on game load/move into 7d12 with lloyd's beacon - use vars table</del>, same thing with 7d08.blv (monsters reappearing)
* <del>castle harmondale locked if not finished scavenger hunt, also messenger about scavenger hunt</del>
* <del>process summon monsters npcgroup</del>
* <del>inspect EI event 575 (where is it located) - answer: nowhere</del>
* <del>castle harmondale respawn -1</del>
* <del>leane shadowrunner in deyja strange message on master stealing</del> - strange in vanilla Merge too
* <del>move npcs in mdt12.blv</del>
* <del>check if after arriving in harmondale death map is set as harmondale</del>
* <del>d16 vampire cloak in prison</del - vampire has it
* <del>check other qbits past 512 * 3, for things that might break with conversion</del>
* <del>phasing cauldron and brazier of succor</del> - idk how to fix this
* <del>judas in colony zod?</del> - nope, though make sure to play fully through rev4
* <del>realign evenmorn island titans</del>
* <del>check d08.blv Lord Godwinson stats - they get affected by bolster monster</del>
* <del>trees in tularean looked strange - possible not changed file name in evt.CheckSeason checks</del>
* <del>the small house entrance text</del>
* <del>resolve docent talking in emerald island - workaround is to walk into BDJ radius again, second time it sets the QBit</del>
* <del>antagarichan gems have changed descriptions in Merge, maybe preserve them?</del>
* <del>consider restoring original behavior of blasters - currently they benefit from bow skill</del>
* <del>check evt.ShowMovie file names</del>
* <del>https://gitlab.com/cthscr/mmmerge/-/wikis/Cluebook/DimensionDoor</del>
* <del>fix other ddmapbuffs in MM6/MM8 maps</del>
* <del>check wtf at line 2595</del>
* <del>check if blayze's quest and saving erathia quest give correct mastery - they probably don't, fix them</del>
* <del>check awards missing mappings</del>
* <del>check Elgar Fellmoon</del>
* <del>Zokarr's tomb fix coordinates on teleport to Barrow VI</del>
* <del>restore qbits on leaving the gauntlet only if they were set originally</del>
* <del>fix the gauntlet scripts to subtract MM8/MM6 scrolls/potions as well and remove SPs from all party members</del>
* <del>restore original pics & descriptions of items taken from MM8/MM6</del>
* <del>mdt, mdk, mdr test</del>
* <del>check evt.SpeakNPC commands if they won't break</del>
* <del>check test of friendship - probably need to disable monster pathfinding there/increase HP of NPCs</del>
* <del>check search for "ERROR: " and check if everything is ok near it</del>
** <del>do this in map scripts too</del>
* <del>integrate changes from revamp.T.lod (incl. scripts)</del>
* <del>integrate latest cthscr's commits</del>
* <del>boost mapstats spawns</del>
* <del>boost spells damage</del>
* <del>find where judas the geek is in rev4 and put him there in merge (maybe he is as spawn)</del>
* <del>tunnels to eofol changed (deleted) spawns at the end?</del> - no, just monster limit is hit easily in this map
--]]
--[[ USEFUL STUFF
shows event id when event is triggered on the map
function events.EvtMap(evtId, seq)
Message(tostring(evtId))
end
for m, id in pairs(Editor.State.Monsters) do if id == 1 then XYZ(m, XYZ(Party)) end end
t1 = nil
for v, k in pairs(Editor.State.Monsters) do
if k == 0 then t1 = v end end
local file = io.open("Monster data.txt", "w")
for k, v in Map.Monsters do if v.NameId ~= 0 then file:write("Monster " .. k .. "\n\n" .. dump(v, 1):gsub("NameId = (%d+)", function(nameid) return ("NameId = %d (%s)"):format(tonumber(nameid), Game.PlaceMonTxt[tonumber(nameid)]) end) .. "\n\n\n") end end
file:close()
--]]
for regex, fun in pairs(replacements) do
content = content:gsub(regex, fun)
end
content = content:replace([[Game.GlobalEvtLines.Count = 0 -- Deactivate all standard events
]], "")
local patches =
{[ [[evt.ForPlayer("All")
if evt.Cmp("QBits", 850) then -- BDJ Final
evt.SetMessage(1024) -- "Adventurer 4, select your new profession."
evt.ForPlayer(3)
elseif evt.Cmp("QBits", 849) then -- BDJ 3
evt.SetMessage(1023) -- "Adventurer 3, select your new profession."
evt.ForPlayer(2)
elseif evt.Cmp("QBits", 848) then -- BDJ 2
evt.SetMessage(1022) -- "Adventurer 2, select your new profession."
evt.ForPlayer(1)
else
evt.SetMessage(1021) -- "Adventurer 1, select your new profession."
evt.ForPlayer(0)
end]] ]
=
[[evt.ForPlayer("All")
if evt.Cmp("QBits", 869) then -- BDJ Final
evt.SetMessage(2822) -- "Adventurer 5, select your new profession."
evt.ForPlayer(4)
elseif evt.Cmp("QBits", 850) then -- BDJ 4
evt.SetMessage(1024) -- "Adventurer 4, select your new profession."
evt.ForPlayer(3)
elseif evt.Cmp("QBits", 849) then -- BDJ 3
evt.SetMessage(1023) -- "Adventurer 3, select your new profession."
evt.ForPlayer(2)
elseif evt.Cmp("QBits", 848) then -- BDJ 2
evt.SetMessage(1022) -- "Adventurer 2, select your new profession."
evt.ForPlayer(1)
else
evt.SetMessage(1021) -- "Adventurer 1, select your new profession."
evt.ForPlayer(0)
end]],
[ [[evt.ForPlayer(3)
if evt.Cmp("FireSkill", 1) then
evt.Set("FireSkill", 49152)
evt.Set("FireSkill", 72)
end
evt.ForPlayer(2)
if evt.Cmp("FireSkill", 1) then
evt.Set("FireSkill", 49152)
evt.Set("FireSkill", 72)
end
evt.ForPlayer(1)
if evt.Cmp("FireSkill", 1) then
evt.Set("FireSkill", 49152)
evt.Set("FireSkill", 72)
end
evt.ForPlayer(0)
if evt.Cmp("FireSkill", 1) then
evt.Set("FireSkill", 49152)
evt.Set("FireSkill", 72)
end]] ] = [[for _, pl in Party do
local s, m = SplitSkill(pl.Skills[const.Skills.Fire])
if s ~= 0 then
pl.Skills[const.Skills.Fire] = JoinSkill(math.max(s, 8), math.max(m, const.Expert))
end
end]],
-- don't need sparkles, as later there's evt.Add("Experience")
[ [[if not evt.Cmp("QBits", 807) then -- Water
if not evt.Cmp("QBits", 808) then -- Fire
if not evt.Cmp("QBits", 809) then -- Air
if not evt.Cmp("QBits", 810) then -- Earth
return
end
end
end
end]] ] = [[if not evt.Cmp("QBits", 807) or not evt.Cmp("QBits", 808) or not evt.Cmp("QBits", 809) or not evt.Cmp("QBits", 810) then
return
end]],
[ [[evt.Set("DarkSkill", 136)]] ] = [[
if evt.Player == 5 then
for _, pl in Party do
local s, m = SplitSkill(pl.Skills[const.Skills.Dark])
pl.Skills[const.Skills.Dark] = JoinSkill(math.max(s, 8), math.max(m, const.Master))
end
else
local pl = Party[evt.Player]
local s, m = SplitSkill(pl.Skills[const.Skills.Dark])
pl.Skills[const.Skills.Dark] = JoinSkill(math.max(s, 8), math.max(m, const.Master))
end]],
-- [ [[evt.Subtract("QBits", 811) -- "Clear out the Strange Temple, retrieve the ancient weapons, and return to Maximus in The Pit"]] ] =
-- [[evt.SetNPCGreeting{NPC = 388, Greeting = 370} -- Halfgild Wynac
-- evt.Subtract("QBits", 811) -- "Clear out the Strange Temple, retrieve the ancient weapons, and return to Maximus in The Pit"]],
--
[ [[evt.MoveNPC{NPC = 60, -- ERROR: Not found
HouseId = 999} -- "Drathen Keldin"]] ] = "",
[ [[evt.Add(-- ERROR: Not found
"Awards", 83886128)]] ] = [[evt.Add(-- ERROR: Not found
"Awards", 21)]],
[ [[evt.global[42397] = function()
evt.SetSnow{EffectId = 18, On = true}
end]] ] = "",
[ [[evt.Set(-- ERROR: Not found
"Awards", 108)
evt.EnterHouse(600) -- Win Good]] ] =
[[evt.Set(-- ERROR: Not found
"Awards", 109)]]
}
for from, to in pairs(patches) do
content = content:replace(from, to)
end
local genericEvtRegex = "evt%.%w-[%(%{].-[%)%}]"
local exclusions =
{
"evt%.Add%(\"Experience\", %d+%)"
}
local i, j = content:find(genericEvtRegex, 1)
repeat
local text = content:sub(i, j)
local matched = false
for regex, fun in pairs(replacements) do
if text:match("(" .. regex .. ")") == text then -- need full capture group, as match returns only first capture group
matched = true
break
end
end
if not matched then
for k, regex in ipairs(exclusions) do
if text:match("(" .. regex .. ")") == text then
matched = true
break
end
end
end
if not matched then
--print("Found unfixed evt command: " .. text)
end
i, j = content:find(genericEvtRegex, i + 1)
until i == nil
-- Harmondale teleportal hub
content = content:replace([[-- "Challenges"
Game.GlobalEvtLines:RemoveEvent(1313)
evt.global[1313] = function()
evt.SetMessage(1671) -- "Scattered around the land are the Challenges. If your ability is great enough, and you best the challenge, you will be award skill points to do with as you wish!"
end]], [[-- "Challenges"
Game.GlobalEvtLines:RemoveEvent(1313)
evt.global[1313] = function()
evt.SetMessage(1671) -- "Scattered around the land are the Challenges. If your ability is great enough, and you best the challenge, you will be award skill points to do with as you wish!"
end
-- HARMONDALE TELEPORTAL HUB --
local indexes = {[0] = "A", "B", "C", "D", "E", "F"}
-- "Go back"
evt.global[1993] = function()
for i = 0, 2 do
Game.NPC[1255]["Event" .. indexes[i] ] = 1995 + i
end
Game.NPC[1255]["Event" .. indexes[3] ] = 1994
end
-- "More destinations"
evt.global[1994] = function()
for i = 0, 1 do
Game.NPC[1255]["Event" .. indexes[i] ] = 1998 + i
end
Game.NPC[1255]["Event" .. indexes[2] ] = 1993
Game.NPC[1255]["Event" .. indexes[3] ] = 0
end
evt.CanShowTopic[1995] = function()
return evt.All.Cmp("Inventory", 1467)
end
-- "Tatalia"
evt.global[1995] = function()
evt.MoveToMap{X = 6604, Y = -8941, Z = 0, Direction = 1024, LookAngle = 0, SpeedZ = 0, HouseId = 0, Icon = 0, Name = "7Out13.odm"}
end
evt.CanShowTopic[1996] = function()
return evt.All.Cmp("Inventory", 1469)
end
-- "Avlee"
evt.global[1996] = function()
evt.MoveToMap{X = 14414, Y = 12615, Z = 0, Direction = 768, LookAngle = 0, SpeedZ = 0, HouseId = 0, Icon = 0, Name = "Out14.odm"}
end
evt.CanShowTopic[1997] = function()
return evt.All.Cmp("Inventory", 1468)
end
-- "Deyja"
evt.global[1997] = function()
evt.MoveToMap{X = 4586, Y = -12681, Z = 0, Direction = 512, LookAngle = 0, SpeedZ = 0, HouseId = 0, Icon = 0, Name = "7Out05.odm"}
end
evt.CanShowTopic[1998] = function()
return evt.All.Cmp("Inventory", 1471)
end
-- "Bracada Desert"
evt.global[1998] = function()
evt.MoveToMap{X = 8832, Y = 18267, Z = 0, Direction = 1536, LookAngle = 0, SpeedZ = 0, HouseId = 0, Icon = 0, Name = "7Out06.odm"}
end
evt.CanShowTopic[1999] = function()
return evt.All.Cmp("Inventory", 1470)
end
-- "Evenmorn Island"
evt.global[1999] = function()
evt.MoveToMap{X = 17161, Y = -10827, Z = 0, Direction = 1024, LookAngle = 0, SpeedZ = 0, HouseId = 0, Icon = 0, Name = "Out09.odm"}
end]])
local file2 = io.open("GLOBAL rev4 processed.lua", "w")
file2:write(content)
io.close(file2) |
GM.Name = "Cataclysm"
GM.Author = "Thendon.exe"
GM.Website = "sneaky.rocks"
DeriveGamemode( "base" )
_G.TEAM_BLACK = 1
_G.TEAM_WHITE = 2
include("sh_loader.lua")
function GM:CreateTeams()
team.SetUp( TEAM_BLACK, "Black", _COLOR.BLACK, true)
team.SetClass( TEAM_BLACK, { "player_earth", "player_fire", "player_air", "player_water" } )
team.SetUp( TEAM_WHITE, "White", _COLOR.WHITE, true)
team.SetClass( TEAM_WHITE, { "player_earth", "player_fire", "player_air", "player_water" } )
end
function GM:GetEnemyTeam( teamID )
teamID = isnumber(teamID) and teamID or teamID:Team()
return teamID == TEAM_BLACK and TEAM_WHITE or TEAM_BLACK
end
local lastThink = 0
local deltaTime = 0
_G.DeltaTime = function()
return deltaTime
end
local function CalcDelta()
local now = CurTime()
deltaTime = now - lastThink
lastThink = now
end
function GM:Think()
CalcDelta()
if SERVER then round_manager.Update() end
if CLIENT then
music_manager.Update()
Popup.Update()
KillLog.Update()
end
end |
--
-- Author: zen.zhao88@gmail.com
-- Date: 2015-12-03 16:54:06
--
local Error = class("Error",b3.Action)
function Error:onTick(tick)
return b3.Com.ERROR
end
return Error |
--[[
Made by toonrun123V2
9.12.2021 (m/d/y).
Custom physics (not newton's law)
understand uself.
SCALE-ONLY
]]
local tweenservice = game:GetService("TweenService")
local mouse:Mouse = game.Players.LocalPlayer:GetMouse()
local info = TweenInfo.new(0.1,Enum.EasingStyle.Linear,Enum.EasingDirection.InOut,0,false,0)
local HostFrame = script.Parent.Parent --[[HostFrame]]
local Frame = script.Parent --[[Box]]
local Camera = workspace.CurrentCamera
local Weight = 1
local SpeedPhysicsLower = 1
local Speed2DLower = 2
local Bouncedivide = 2
local bounceside = {
["Down"] = false,
["Left"] = true,
["Right"] = true
}
--These Settings Change eveytimes=======
local weight = 0
local XD = nil
local future_position = nil
local Rotation = nil
local IsInProcess = nil
local lastx = nil
local lasty = nil
local newx = nil
local newy = nil
local enable = false
local reversespeed = 0
local oldspeedx = 0
local oldspeedy = 0
--====================================
local Floor,abs = math.floor,math.abs
mouse.Button1Down:Connect(function()
enable = true
end)
mouse.Button1Up:Connect(function()
enable = false
end)
local function ScaleToOffset(Scale)
local ViewPortSize = Camera.ViewportSize
return ({ViewPortSize.X * Scale[1],ViewPortSize.Y * Scale[2]})
end
local function OffsetToScale(Offset)
local ViewPortSize = Camera.ViewportSize
return ({Offset[1] / ViewPortSize.X, Offset[2] / ViewPortSize.Y})
end
game:GetService("RunService").RenderStepped:Connect(function()
weight = (Frame.AbsoluteSize.X/2)+(Frame.AbsoluteSize.Y/2)
if enable then
if not lastx then
lastx = mouse.X
end
if not lasty then
lasty = mouse.Y
end
newx = -(lastx - mouse.X)/Weight
newy = -(lasty - mouse.Y)/Weight
oldspeedx = newx
oldspeedy = newy
else
if oldspeedx >= 1 then
oldspeedx -= SpeedPhysicsLower
end
if oldspeedx <= -1 then
oldspeedx += SpeedPhysicsLower
end
if oldspeedx <= 1 and oldspeedx >= 0 then
oldspeedx = 0
end
if oldspeedx >= -1 and oldspeedx <= 0 then
oldspeedx = 0
end
oldspeedy += abs(weight/200*((workspace.Gravity/100)-1*10))
end
XD = OffsetToScale({oldspeedx/Speed2DLower,oldspeedy/Speed2DLower})
future_position = Frame.Position + UDim2.new(XD[1],0,XD[2],0)
Rotation = OffsetToScale({Frame.Rotation,Frame.Rotation})
IsInProcess = false
Frame.Position = future_position
if Frame.Position.Y.Scale < 0 then
oldspeedy = 0
Frame.Position = UDim2.new(future_position.X.Scale,0,0,0)
elseif Frame.Position.Y.Scale > 1-Frame.Size.Y.Scale then
if bounceside["Down"] then
oldspeedy = Floor(-(oldspeedy/Bouncedivide))
else
oldspeedy = 0
end
--[[
XD = OffsetToScale({oldspeedx/Speed2DLower,oldspeedy/Speed2DLower})
future_position = Frame.Position + UDim2.new(XD[1],0,XD[2],0)
Dont enabled it because it will broke speed physics
]]
Frame.Position = UDim2.new(future_position.X.Scale,0,future_position.Y.Scale,0)
if Frame.Position.Y.Scale > 1-Frame.Size.Y.Scale then
Frame.Position = UDim2.new(future_position.X.Scale,0,1-Frame.Size.Y.Scale,0)
end
IsInProcess = true
end
if Frame.Position.X.Scale < 0 then
if bounceside["Left"] then
oldspeedx = Floor(-(oldspeedx/Bouncedivide))
else
oldspeedx = 0
end
XD = OffsetToScale({oldspeedx/Speed2DLower,oldspeedy/Speed2DLower})
future_position = Frame.Position + UDim2.new(XD[1],0,XD[2],0)
Frame.Position = UDim2.new(0,0,future_position.Y.Scale,0)
IsInProcess = true
elseif Frame.Position.X.Scale > 1-Frame.Size.X.Scale then
if bounceside["Right"] then
oldspeedx = Floor(-(oldspeedx/Bouncedivide))
else
oldspeedx = 0
end
XD = OffsetToScale({oldspeedx/Speed2DLower,oldspeedy/Speed2DLower})
future_position = Frame.Position + UDim2.new(XD[1],0,XD[2],0)
Frame.Position = UDim2.new(1-Frame.Size.X.Scale,0,Frame.Position.Y.Scale,0)
IsInProcess = true
end
--[[if oldspeedx >= 1 then
oldspeedx += oldspeedx/10
end
if oldspeedx <= -1 then
oldspeedx -= oldspeedx/10
end]]
--[[if oldspeedx < reversespeed then
warn(oldspeedx,reversespeed)
local Speedclone = script.Parent.Parent:WaitForChild("sPEED"):Clone()
Speedclone.Text = oldspeedx.." "..reversespeed
Speedclone.Parent = HostFrame
Speedclone.Position = Frame.Position
end
reversespeed = oldspeedx
UNUSED
]]
lasty = mouse.Y
lastx = mouse.X
end)
|
local Ansi = setmetatable({ }, {
__call = function(self, ...)
local str = '\027['
for k,v in ipairs({ ...}) do
if k == 1 then
str = str .. v
else
str = str .. ';' .. v
end
end
return str .. 'm'
end
})
Ansi.codes = {
reset = 0,
white = 1,
orange = 2,
magenta = 3,
lightBlue = 4,
yellow = 5,
lime = 6,
pink = 7,
gray = 8,
lightGray = 9,
cyan = 10,
purple = 11,
blue = 12,
brown = 13,
green = 14,
red = 15,
black = 16,
onwhite = 21,
onorange = 22,
onmagenta = 23,
onlightBlue = 24,
onyellow = 25,
onlime = 26,
onpink = 27,
ongray = 28,
onlightGray = 29,
oncyan = 30,
onpurple = 31,
onblue = 32,
onbrown = 33,
ongreen = 34,
onred = 35,
onblack = 36,
}
for k,v in pairs(Ansi.codes) do
Ansi[k] = Ansi(v)
end
return Ansi
|
-- gperftools.cpu
local ffi = require('ffi')
local status, profiler = pcall(ffi.load, 'profiler')
if not status then
error('Failed to load libprofiler. Please install gperftools!')
end
ffi.cdef[[
int ProfilerStart(const char* fname);
void ProfilerStop();
void ProfilerFlush();
]]
local function start(filename)
if filename == nil then
error("Usage: cpu.start(filename)")
end
if profiler.ProfilerStart(filename) ~= 0 then
return true
else
return nil
end
end
local function stop()
profiler.ProfilerStop()
end
local function flush()
profiler.ProfilerFlush()
end
return {
start = start;
stop = stop;
flush = flush;
}
|
GuildGearRulesCache = GuildGearRules:NewModule("GuildGearRulesCache", "AceEvent-3.0")
function GuildGearRulesCache:Initialize(core)
self.Core = core;
self.Queue = {};
self.Queue = GuildGearRulesTable:New{ };
self:RegisterEvent("GET_ITEM_INFO_RECEIVED", "OnItemInfoReceived");
self.Core:Log(tostring(self) .. " initialized.");
return self;
end
function GuildGearRulesCache:Log(text, msgType)
if (self.Core.db.profile.DebugCache) then
self.Core:Log("Cache: " .. text, msgType)
end
end
function GuildGearRulesCache:Update()
-- Iterate backwards so items can be safely removed.
for i = #self.Queue, 1, -1 do
local item = self.Queue[i];
if (item ~= nil) then
if (item.Validate and item.Received) then
if (time() - item.Received >= 1) then
-- Validate item two times.
self.Core.Inspector:ValidateItemAttributes(item.ItemID, item.Meta.ItemLink, item.Meta.SlotID, item.Meta.CharacterInfo);
self:Log("Checking " .. item.Meta.ItemLink .. ".");
item.TimesChecked = item.TimesChecked + 1
if (item.TimesChecked < 2) then
item.Received = time();
else
self.Queue:Remove(i);
end
end
else
self.Queue:Remove(i);
end
end
end
end
function GuildGearRulesCache:New(itemID, validate)
local cacheItem = {
ItemID = itemID,
Validate = validate or false,
Received = nil,
TimesChecked = 0,
Meta = nil,
}
return cacheItem;
end
-- New item equipped, forget about last validation.
-- Without this, items can appear unequipped if they are unequipped and equipped quickly.
function GuildGearRulesCache:Cancel(characterInfo, slotID)
-- Iterate backwards so items can be safely removed.
for i = #self.Queue, 1, -1 do
local item = self.Queue[i];
if (item ~= nil) then
if (item.Meta ~= nil and item.Meta.CharacterInfo ~= nil and item.Meta.SlotID ~= nil) then
if (item.Meta.CharacterInfo == characterInfo and item.Meta.SlotID == slotID) then
self.Queue:Remove(i);
end
end
end
end
end
function GuildGearRulesCache:Load(itemID, cacheItem)
-- Will be nil if not cached and start a GET_ITEM_INFO_RECEIVED request.
local itemName = GetItemInfo(itemID);
local isCached = itemName ~= nil;
-- Add item to queue if is not cached or if we want to validate it.
if (cacheItem ~= nil and (not isCached or cacheItem.Validate)) then
if (cacheItem.Validate) then cacheItem.Received = time(); end
self.Queue:Add(cacheItem);
local index, cacheItem = self.Queue:Find("ItemID", itemID);
if (self.Core.db.profile.DebugCache) then
local ending = "was already cached.";
if (not isCached) then
local ending = "was not cached.";
end
self:Log("Adding " .. itemID .. " to queue, " .. ending);
end
end
end
function GuildGearRulesCache:OnItemInfoReceived(event, itemID, success)
if (not success) then return; end
local itemName = GetItemInfo(itemID);
local indexes, cacheItems = self.Queue:FindAll("ItemID", itemID);
for i = 1, #indexes do
if (cacheItems[i].Validate) then
cacheItems[i].Received = time();
else
-- If we don't want to validate it, remove directly.
self.Queue:Remove(indexes[i]);
end
end
if (#indexes > 0) then
self:Log("Resolved " .. itemID .. ".");
else
if (itemName ~= nil) then
self:Log("Received information on " .. itemName .. " (" .. itemID .. ").");
else
self:Log("Received information on " .. itemID .. ", could not get name.");
end
end
end |
-- SPDX-License-Identifier: BSD-3-Clause
--
-- Copyright 2016 Raritan Inc. All rights reserved.
-- Print some information from the PDU data model.
-- load the "Pdu" library and all dependencies
require "Pdu"
-- Acquire the single instance of the Pdu interface
local pdu = pdumodel.Pdu:getDefault()
-- Get and print some information from the PDU nameplate.
--
-- According to Pdu.idl, getNameplate() returns a structure. In Lua, this is
-- represented as a table whose keys are the field names of the structure.
local nameplate = pdu:getNameplate()
print("PDU Manufacturer: " .. nameplate.manufacturer)
print("PDU Model: " .. nameplate.model)
print()
-- Get and print the PDU metadata structure.
--
-- To display a complete table, use the built-in function 'printTable'.
print("PDU metadata:")
printTable(pdu:getMetaData())
print()
-- Iterate through all outlets and print their power state
local outlets = pdu:getOutlets()
for _, outlet in ipairs(outlets) do
-- Get the outlet label (from the metadata) and power state
local label = outlet:getMetaData().label
local state = outlet:getState()
if state.powerState == pdumodel.Outlet.PowerState.PS_ON then
print("Outlet " .. label .. ": ON")
else
print("Outlet " .. label .. ": OFF")
end
end
|
local PluginRoot = script:FindFirstAncestor("PicularPlugin")
local Components = PluginRoot.Components
local Roact: Roact = require(PluginRoot.Packages.Roact)
local Controls = require(Components.Controls)
local e = Roact.createElement
local Component = Roact.PureComponent:extend("PicularSearchBar")
function Component:render()
return e(Controls.TextInput, {
placeholder = "Search for anything...",
iconId = "Search",
size = UDim2.new(1, 0, 0, 36),
})
end
return Component
|
addEvent("onPlayerAcceptTrade",true)
addEventHandler("onPlayerAcceptTrade",root,function(koszt)
local character = getElementData(source,"character")
if (not character or not character.id) then
outputDebugString("Zadanie onPlayerAcceptTrade dla niezalogowanego gracza.")
return false
end
if (not getPlayerMoney(source) or getPlayerMoney(source)<koszt) then return false end
takePlayerMoney(source,koszt)
setPedArmor(source,100)
outputChatBox("* Zakupiłeś kamizelkę kuloodporną, za 235$.",source)
return true
end)
arm_pick = createPickup(309.38,-134.70,1000.3,3,1242,1,1)
setElementDimension(arm_pick,12)
setElementInterior(arm_pick,7)
|
local lua = require "lapis.lua"
local lapis = require "lapis.init"
local lapis_application = require "lapis.application"
local respond_to = lapis_application.respond_to
local yield_error = lapis_application.yield_error
local capture_errors = lapis_application.capture_errors
local lapis_validate = require "lapis.validate"
local assert_valid = lapis_validate.assert_valid
local fmt = string.format
local model = require "model"
local app = {
path = "/greet",
name = "greeter.",
}
app[{greet = "/:login"}] = respond_to {
GET = capture_errors(function(self)
assert_valid(self.params, {
{"login", min_length = 2, max_length = 128},
})
local user = model.get_user_by_login(self.params.login)
if user then
self.name = user.fullname
else
yield_error("unexpected guest")
end
return {
render = true,
layout = "greeter.layout",
}
end),
}
-- BELOW: This does not work:
-- app.layout = require "views.greeter.layout"
return lua.class(app, lapis.Application)
|
-- Language Server Protocol configuration.
local utils = require 'utils'
utils.debug('S LSP configuration sequence started')
require('lsp.bash')
require('lsp.lua')
require('lsp.python')
require('lsp.rust')
require('lsp.common').lsputils()
utils.debug('S LSP configuration sequence finished')
|
local PANEL
--[[---------------------------------------------------------------------------
Hitman menu
---------------------------------------------------------------------------]]
PANEL = {}
AccessorFunc(PANEL, "hitman", "Hitman")
AccessorFunc(PANEL, "target", "Target")
AccessorFunc(PANEL, "selected", "Selected")
function PANEL:Init()
self.BaseClass.Init(self)
self.btnClose = vgui.Create("DButton", self)
self.btnClose:SetText("")
self.btnClose.DoClick = function() self:Remove() end
self.btnClose.Paint = function(panel, w, h) derma.SkinHook("Paint", "WindowCloseButton", panel, w, h) end
self.icon = vgui.Create("SpawnIcon", self)
self.icon:SetDisabled(true)
self.icon.PaintOver = function(icon) icon:SetTooltip() end
self.icon:SetTooltip()
self.title = vgui.Create("DLabel", self)
self.title:SetText(DarkRP.getPhrase("hitman"))
self.name = vgui.Create("DLabel", self)
self.price = vgui.Create("DLabel", self)
self.playerList = vgui.Create("DScrollPanel", self)
self.btnRequest = vgui.Create("HitmanMenuButton", self)
self.btnRequest:SetText(DarkRP.getPhrase("hitmenu_request"))
self.btnRequest.DoClick = function()
if IsValid(self:GetTarget()) then
RunConsoleCommand("darkrp", "requesthit", self:GetTarget():SteamID(), self:GetHitman():UserID())
self:Remove()
end
end
self.btnCancel = vgui.Create("HitmanMenuButton", self)
self.btnCancel:SetText(DarkRP.getPhrase("cancel"))
self.btnCancel.DoClick = function() self:Remove() end
self:SetSkin(GAMEMODE.Config.DarkRPSkin)
self:InvalidateLayout()
end
function PANEL:Think()
if not IsValid(self:GetHitman()) or self:GetHitman():GetPos():Distance(LocalPlayer():GetPos()) > GAMEMODE.Config.minHitDistance then
self:Remove()
return
end
-- update the price (so the hitman can't scam)
self.price:SetText(DarkRP.getPhrase("priceTag", DarkRP.formatMoney(self:GetHitman():getHitPrice()), ""))
self.price:SizeToContents()
end
function PANEL:PerformLayout()
local w, h = self:GetSize()
self:SetSize(500, 700)
self:Center()
self.btnClose:SetSize(24, 24)
self.btnClose:SetPos(w - 24 - 5, 5)
self.icon:SetSize(128, 128)
self.icon:SetModel(self:GetHitman():GetModel())
self.icon:SetPos(20, 20)
self.title:SetFont("ScoreboardHeader")
self.title:SetPos(20 + 128 + 20, 20)
self.title:SizeToContents(true)
self.name:SizeToContents(true)
self.name:SetText(DarkRP.getPhrase("name", self:GetHitman():Nick()))
self.name:SetPos(20 + 128 + 20, 20 + self.title:GetTall())
self.price:SetFont("HUDNumber5")
self.price:SetColor(Color(255, 0, 0, 255))
self.price:SetText(DarkRP.getPhrase("priceTag", DarkRP.formatMoney(self:GetHitman():getHitPrice()), ""))
self.price:SetPos(20 + 128 + 20, 20 + self.title:GetTall() + 20)
self.price:SizeToContents(true)
self.playerList:SetPos(20, 20 + self.icon:GetTall() + 20)
self.playerList:SetWide(self:GetWide() - 40)
self.btnRequest:SetPos(20, h - self.btnRequest:GetTall() - 20)
self.btnRequest:SetButtonColor(Color(0, 120, 30, 255))
self.btnCancel:SetPos(w - self.btnCancel:GetWide() - 20, h - self.btnCancel:GetTall() - 20)
self.btnCancel:SetButtonColor(Color(140, 0, 0, 255))
self.playerList:StretchBottomTo(self.btnRequest, 20)
self.BaseClass.PerformLayout(self)
end
function PANEL:Paint()
local w, h = self:GetSize()
surface.SetDrawColor(Color(0, 0, 0, 200))
surface.DrawRect(0, 0, w, h)
end
function PANEL:AddPlayerRows()
local players = table.Copy(player.GetAll())
table.sort(players, function(a, b)
local aTeam, bTeam, aNick, bNick = team.GetName(a:Team()), team.GetName(b:Team()), string.lower(a:Nick()), string.lower(b:Nick())
return aTeam == bTeam and aNick < bNick or aTeam < bTeam
end)
for k, v in pairs(players) do
local canRequest = hook.Call("canRequestHit", DarkRP.hooks, self:GetHitman(), LocalPlayer(), v, self:GetHitman():getHitPrice())
if not canRequest then continue end
local line = vgui.Create("HitmanMenuPlayerRow")
line:SetPlayer(v)
self.playerList:AddItem(line)
line:SetWide(self.playerList:GetWide() - 100)
line:Dock(TOP)
line.DoClick = function()
self:SetTarget(line:GetPlayer())
if IsValid(self:GetSelected()) then
self:GetSelected():SetSelected(false)
end
line:SetSelected(true)
self:SetSelected(line)
end
end
end
vgui.Register("HitmanMenu", PANEL, "DPanel")
--[[---------------------------------------------------------------------------
Hitmenu button
---------------------------------------------------------------------------]]
PANEL = {}
AccessorFunc(PANEL, "btnColor", "ButtonColor")
function PANEL:PerformLayout()
self:SetSize(self:GetParent():GetWide() / 2 - 30, 100)
self:SetFont("HUDNumber5")
self:SetTextColor(Color(255, 255, 255, 255))
self.BaseClass.PerformLayout(self)
end
function PANEL:Paint()
local w, h = self:GetSize()
local col = self:GetButtonColor() or Color(0, 120, 30, 255)
surface.SetDrawColor(col.r, col.g, col.b, col.a)
surface.DrawRect(0, 0, w, h)
end
vgui.Register("HitmanMenuButton", PANEL, "DButton")
--[[---------------------------------------------------------------------------
Player row
---------------------------------------------------------------------------]]
PANEL = {}
AccessorFunc(PANEL, "player", "Player")
AccessorFunc(PANEL, "selected", "Selected", FORCE_BOOL)
function PANEL:Init()
self.lblName = vgui.Create("DLabel", self)
self.lblName:SetMouseInputEnabled(false)
self.lblName:SetColor(Color(255,255,255,200))
self.lblTeam = vgui.Create("DLabel", self)
self.lblTeam:SetMouseInputEnabled(false)
self.lblTeam:SetColor(Color(255,255,255,200))
self:SetText("")
self:SetCursor("hand")
end
function PANEL:PerformLayout()
local ply = self:GetPlayer()
if not IsValid(ply) then self:Remove() return end
self.lblName:SetFont("UiBold")
self.lblName:SetText(DarkRP.deLocalise(ply:Nick()))
self.lblName:SizeToContents()
self.lblName:SetPos(10, 1)
self.lblTeam:SetFont("UiBold")
self.lblTeam:SetText((ply.DarkRPVars and DarkRP.deLocalise(ply:getDarkRPVar("job") or "")) or team.GetName(ply:Team()))
self.lblTeam:SizeToContents()
self.lblTeam:SetPos(self:GetWide() / 2, 1)
end
function PANEL:Paint()
if not IsValid(self:GetPlayer()) then self:Remove() return end
local color = team.GetColor(self:GetPlayer():Team())
color.a = self:GetSelected() and 70 or 255
surface.SetDrawColor(color)
surface.DrawRect(0, 0, self:GetWide(), 20)
end
vgui.Register("HitmanMenuPlayerRow", PANEL, "Button")
--[[---------------------------------------------------------------------------
Open the hit menu
---------------------------------------------------------------------------]]
function DarkRP.openHitMenu(hitman)
local frame = vgui.Create("HitmanMenu")
frame:SetHitman(hitman)
frame:AddPlayerRows()
frame:SetVisible(true)
frame:MakePopup()
end
|
--[[
--------------------------------------------------
Update Checker for Rainmeter
v6.1.0
By raiguard
Implements 'semver.lua' by kikito (https://github.com/kikito/semver.lua)
Implements 'JSON.lua' by rxi (https://github.com/rxi/json.lua)
--------------------------------------------------
Release Notes:
v6.1.0 - 2018-7-4
- Added 'RawChangelog' option
v6.0.0 - 2018-7-2
- Switched to use GitHub REST v3 API, rather than a customized INI file
v5.1.0 - 2018-6-21
- Switched to using the WebParser measure output rather than a downloaded file
for the ReadINI function
v5.0.0 - 2017-12-20
- Removed hard-coded actions and replaced with arguments in the script measure
- Switched to using INI format for the remote version data
- Added 'GetIniValue' function for retrieving other information from remote
v4.0.0 - 2016-11-18
- Implemented "semver.lua" for more robust comparisons
v3.0.0 - 2016-11-14
- Added support for update checking on development versions
v2.1.0 - 2016-11-14
- Fixed oversight where if the user is on a development version for an
outdated release, it would not return UpdateAvailable()
- Added 'ParsingError' return
v2.0.0 - 2016-8-4
- Removed dependancy on an output meter in favor of hard-coded actions, added
more documentation
v1.0.1 - 2016-7-1
- Optimized gmatch function, more debug functionality
v1.0.0 - 2016-1-25
- Initial release
--------------------------------------------------
This script compares two semver-formatted version strings and compares them,
returning whether the current version is outdated, up-to-date, or a development
version. By default, it uses the GitHub REST API to download release information,
automatically extracting the most recent release from the specified repository.
However, you do not need to use this if you have another method for retrieving
the most recently released version.
Please keep in mind that version strings must be formatted using the Semantic
Versioning 2.0.0 format. See http://semver.org/ for additional information.
--------------------------------------------------
INSTRUCTIONS FOR USE:
[MeasureUpdateCheckerScript]
Measure=Script
Script=#@#Scripts\UpdateChecker.lua
CheckForPrereleases=#checkForPrereleases#
UpToDateAction=[!ShowMeter "UpToDateString"]
DevAction=[!ShowMeter "DevString"]
UpdateAvailableAction=[!ShowMeter "UpdateAvailableString"]
ParsingErrorAction=[!ShowMeter "ParsingErrorString"]
This is an example of the script measure you will use to invoke this script.
The 'CheckForPrereleases' defines whether the update checker will compare
with the most recent full release, or the most recent release whatsoever.
Each action option is a series of bangs to execute when that outcome is
reached by the comparison function.
[MeasureUpdateCheck]
Measure=WebParser
URL=#webParserUrl#
RegExp=(?siU)^(.*)$
StringIndex=1
UpdateRate=#updateCheckRate#
OnConnectErrorAction=[!Log "Couldn't connect to update server" "Error"]
FinishAction=[!CommandMeasure MeasureUpdateCheckerScript "CheckForUpdate('#version#', 'MeasureUpdateCheck')"]
DynamicVariables=1
This is an example of the webparser measure used to download the information.
The important thing to note here is the last argument on the 'FinishAction'
line. This must be the name of the WebParser measure, whatever that may
be. This allows the script to actually retrieve the string that was downloaded,
which lets the update check actually take place.
The script retrieves the raw JSON data from the GitHub API, then uses a JSON
parser function to convert it into a LUA table. From there, the script extracts
data for the most recent full release, and the most recent release regardless
of whether or not it is a prerelease. Which release is compared to and provides
the release information is determined by the 'CheckForPrereleases' option in the
script measure.
There are four values for each release that you can retrieve for displaying in
your skin. Each value is retrieved using
[&MeasureUpdateCheckerScript:GetReleaseInfo('key')]. Replace key with one of the
following options:
'name' - returns the tag version of the release
'date' - returns the published date of the release
'changelog' - returns the release's changelog, with the release version and
published date added to the beginning
'downloadUrl' - returns the URL that can be used to download the .RMSKIN
attached to the release
Please note that any meter that extracts information from the script in this way
will need 'DynamicVariables=1' set in order to function properly.
By default, the changelog will include the release's tag version and published
date attached to the beginning of the string. If you wish to disable this, add
'RawChangelog=1' to the script measure.
--------------------------------------------------
]]--
debug = false
function Initialize()
upToDateAction = SELF:GetOption('UpToDateAction')
updateAvailableAction = SELF:GetOption('UpdateAvailableAction')
parsingErrorAction = SELF:GetOption('ParsingErrorAction')
devAction = SELF:GetOption('DevAction')
rawChangelog = tonumber(SELF:GetOption('RawChangelog', '0'))
checkForPrereleases = tonumber(SELF:GetOption('CheckForPrereleases', '1'))
if devAction == '' or devAction == nil then devAction = upToDateAction end
printIndent = ' '
releases = {}
end
function Update() end
function CheckForUpdate(cVersion, measureName)
showPrereleases = tonumber(SELF:GetOption('ShowPrereleases', 1))
apiJson = json.decode(SKIN:GetMeasure(measureName or 'MeasureUpdateCheck'):GetStringValue())
releases = AssembleReleaseInfo(apiJson)
Compare(cVersion, releases[checkForPrereleases + 1]['name'])
end
-- compares two semver-formatted version strings
function Compare(cVersion, rVersion)
cVersion = v(cVersion)
rVersion = v(rVersion)
if cVersion == rVersion then
LogHelper('Up-to-date', 'Debug')
SKIN:Bang(upToDateAction)
elseif cVersion > rVersion then
LogHelper('Development version', 'Debug')
SKIN:Bang(devAction)
elseif cVersion < rVersion then
LogHelper('Update available', 'Debug')
SKIN:Bang(updateAvailableAction)
else
LogHelper('Parsing error', 'Debug')
SKIN:Bang(parsingErrorAction)
end
end
function GetReleaseInfo(key)
return releases[checkForPrereleases + 1] and releases[checkForPrereleases + 1][key] or '---'
end
function AssembleReleaseInfo(jsonTable)
local releases = {}
local i = 0
local k = 0
while i == 0 do
k = k + 1
if jsonTable[k]['prerelease'] == false then
i = 1
releases[1] = {}
releases[1]['name'] = jsonTable[k]['tag_name']:gsub('v', '')
releases[1]['date'] = jsonTable[k]['published_at']:gsub('(.*)T(.*)', '%1')
releases[1]['changelog'] = (rawChangelog == 0 and 'v' .. releases[1]['name'] .. ' - ' .. releases[1]['date'] .. '\n' or '') .. jsonTable[k]['body']:gsub('\r\n', '\n')
releases[1]['downloadUrl'] = jsonTable[k]['assets'][1]['browser_download_url']
end
end
releases[2] = {}
releases[2]['name'] = jsonTable[1]['tag_name']:gsub('v', '')
releases[2]['date'] = jsonTable[1]['published_at']:gsub('(.*)T(.*)', '%1')
releases[2]['changelog'] = (rawChangelog == 0 and 'v' .. releases[2]['name'] .. ' - ' .. releases[2]['date'] .. '\n' or '') .. jsonTable[1]['body']:gsub('\r\n', '\n')
releases[2]['downloadUrl'] = jsonTable[1]['assets'][1]['browser_download_url']
return releases
end
-- function to make logging messages less cluttered
function LogHelper(message, type)
if type == nil then type = 'Debug' end
if debug == true then
SKIN:Bang("!Log", message, type)
elseif type ~= 'Debug' then
SKIN:Bang("!Log", message, type)
end
end
--[[
--------------------------------------------------
SEMVER.LUA
By kitito
MIT LICENSE
Copyright (c) 2015 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of tother 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 tother 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 function checkPositiveInteger(number, name)
assert(number >= 0, name .. ' must be a valid positive number')
assert(math.floor(number) == number, name .. ' must be an integer')
end
local function present(value)
return value and value ~= ''
end
-- splitByDot("a.bbc.d") == {"a", "bbc", "d"}
local function splitByDot(str)
str = str or ""
local t, count = {}, 0
str:gsub("([^%.]+)", function(c)
count = count + 1
t[count] = c
end)
return t
end
local function parsePrereleaseAndBuildWithSign(str)
local prereleaseWithSign, buildWithSign = str:match("^(-[^+]+)(+.+)$")
if not (prereleaseWithSign and buildWithSign) then
prereleaseWithSign = str:match("^(-.+)$")
buildWithSign = str:match("^(+.+)$")
end
assert(prereleaseWithSign or buildWithSign, ("The parameter %q must begin with + or - to denote a prerelease or a build"):format(str))
return prereleaseWithSign, buildWithSign
end
local function parsePrerelease(prereleaseWithSign)
if prereleaseWithSign then
local prerelease = prereleaseWithSign:match("^-(%w[%.%w-]*)$")
assert(prerelease, ("The prerelease %q is not a slash followed by alphanumerics, dots and slashes"):format(prereleaseWithSign))
return prerelease
end
end
local function parseBuild(buildWithSign)
if buildWithSign then
local build = buildWithSign:match("^%+(%w[%.%w-]*)$")
assert(build, ("The build %q is not a + sign followed by alphanumerics, dots and slashes"):format(buildWithSign))
return build
end
end
local function parsePrereleaseAndBuild(str)
if not present(str) then return nil, nil end
local prereleaseWithSign, buildWithSign = parsePrereleaseAndBuildWithSign(str)
local prerelease = parsePrerelease(prereleaseWithSign)
local build = parseBuild(buildWithSign)
return prerelease, build
end
local function parseVersion(str)
local sMajor, sMinor, sPatch, sPrereleaseAndBuild = str:match("^(%d+)%.?(%d*)%.?(%d*)(.-)$")
assert(type(sMajor) == 'string', ("Could not extract version number(s) from %q"):format(str))
local major, minor, patch = tonumber(sMajor), tonumber(sMinor), tonumber(sPatch)
local prerelease, build = parsePrereleaseAndBuild(sPrereleaseAndBuild)
return major, minor, patch, prerelease, build
end
-- return 0 if a == b, -1 if a < b, and 1 if a > b
local function compare(a,b)
return a == b and 0 or a < b and -1 or 1
end
local function compareIds(myId, otherId)
if myId == otherId then return 0
elseif not myId then return -1
elseif not otherId then return 1
end
local selfNumber, otherNumber = tonumber(myId), tonumber(otherId)
if selfNumber and otherNumber then -- numerical comparison
return compare(selfNumber, otherNumber)
-- numericals are always smaller than alphanums
elseif selfNumber then
return -1
elseif otherNumber then
return 1
else
return compare(myId, otherId) -- alphanumerical comparison
end
end
local function smallerIdList(myIds, otherIds)
local myLength = #myIds
local comparison
for i=1, myLength do
comparison = compareIds(myIds[i], otherIds[i])
if comparison ~= 0 then
return comparison == -1
end
-- if comparison == 0, continue loop
end
return myLength < #otherIds
end
local function smallerPrerelease(mine, other)
if mine == other or not mine then return false
elseif not other then return true
end
return smallerIdList(splitByDot(mine), splitByDot(other))
end
local methods = {}
function methods:nextMajor()
return semver(self.major + 1, 0, 0)
end
function methods:nextMinor()
return semver(self.major, self.minor + 1, 0)
end
function methods:nextPatch()
return semver(self.major, self.minor, self.patch + 1)
end
local mt = { __index = methods }
function mt:__eq(other)
return self.major == other.major and
self.minor == other.minor and
self.patch == other.patch and
self.prerelease == other.prerelease
-- notice that build is ignored for precedence in semver 2.0.0
end
function mt:__lt(other)
if self.major ~= other.major then return self.major < other.major end
if self.minor ~= other.minor then return self.minor < other.minor end
if self.patch ~= other.patch then return self.patch < other.patch end
return smallerPrerelease(self.prerelease, other.prerelease)
-- notice that build is ignored for precedence in semver 2.0.0
end
-- This works like the "pessimisstic operator" in Rubygems.
-- if a and b are versions, a ^ b means "b is backwards-compatible with a"
-- in other words, "it's safe to upgrade from a to b"
function mt:__pow(other)
if self.major == 0 then
return self == other
end
return self.major == other.major and
self.minor <= other.minor
end
function mt:__tostring()
local buffer = { ("%d.%d.%d"):format(self.major, self.minor, self.patch) }
if self.prerelease then table.insert(buffer, "-" .. self.prerelease) end
if self.build then table.insert(buffer, "+" .. self.build) end
return table.concat(buffer)
end
function v(major, minor, patch, prerelease, build)
assert(major, "At least one parameter is needed")
if type(major) == 'string' then
major,minor,patch,prerelease,build = parseVersion(major)
end
patch = patch or 0
minor = minor or 0
checkPositiveInteger(major, "major")
checkPositiveInteger(minor, "minor")
checkPositiveInteger(patch, "patch")
local result = {major=major, minor=minor, patch=patch, prerelease=prerelease, build=build}
return setmetatable(result, mt)
end
--
-- json.lua
--
-- Copyright (c) 2018 rxi
--
-- 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.
--
json = { _version = "0.1.1" }
-------------------------------------------------------------------------------
-- Encode
-------------------------------------------------------------------------------
local encode
local escape_char_map = {
[ "\\" ] = "\\\\",
[ "\"" ] = "\\\"",
[ "\b" ] = "\\b",
[ "\f" ] = "\\f",
[ "\n" ] = "\\n",
[ "\r" ] = "\\r",
[ "\t" ] = "\\t",
}
local escape_char_map_inv = { [ "\\/" ] = "/" }
for k, v in pairs(escape_char_map) do
escape_char_map_inv[v] = k
end
local function escape_char(c)
return escape_char_map[c] or string.format("\\u%04x", c:byte())
end
local function encode_nil(val)
return "null"
end
local function encode_table(val, stack)
local res = {}
stack = stack or {}
-- Circular reference?
if stack[val] then error("circular reference") end
stack[val] = true
if val[1] ~= nil or next(val) == nil then
-- Treat as array -- check keys are valid and it is not sparse
local n = 0
for k in pairs(val) do
if type(k) ~= "number" then
error("invalid table: mixed or invalid key types")
end
n = n + 1
end
if n ~= #val then
error("invalid table: sparse array")
end
-- Encode
for i, v in ipairs(val) do
table.insert(res, encode(v, stack))
end
stack[val] = nil
return "[" .. table.concat(res, ",") .. "]"
else
-- Treat as an object
for k, v in pairs(val) do
if type(k) ~= "string" then
error("invalid table: mixed or invalid key types")
end
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
end
stack[val] = nil
return "{" .. table.concat(res, ",") .. "}"
end
end
local function encode_string(val)
return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
end
local function encode_number(val)
-- Check for NaN, -inf and inf
if val ~= val or val <= -math.huge or val >= math.huge then
error("unexpected number value '" .. tostring(val) .. "'")
end
return string.format("%.14g", val)
end
local type_func_map = {
[ "nil" ] = encode_nil,
[ "table" ] = encode_table,
[ "string" ] = encode_string,
[ "number" ] = encode_number,
[ "boolean" ] = tostring,
}
encode = function(val, stack)
local t = type(val)
local f = type_func_map[t]
if f then
return f(val, stack)
end
error("unexpected type '" .. t .. "'")
end
function json.encode(val)
return ( encode(val) )
end
-------------------------------------------------------------------------------
-- Decode
-------------------------------------------------------------------------------
local parse
local function create_set(...)
local res = {}
for i = 1, select("#", ...) do
res[ select(i, ...) ] = true
end
return res
end
local space_chars = create_set(" ", "\t", "\r", "\n")
local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
local literals = create_set("true", "false", "null")
local literal_map = {
[ "true" ] = true,
[ "false" ] = false,
[ "null" ] = nil,
}
local function next_char(str, idx, set, negate)
for i = idx, #str do
if set[str:sub(i, i)] ~= negate then
return i
end
end
return #str + 1
end
local function decode_error(str, idx, msg)
local line_count = 1
local col_count = 1
for i = 1, idx - 1 do
col_count = col_count + 1
if str:sub(i, i) == "\n" then
line_count = line_count + 1
col_count = 1
end
end
error( string.format("%s at line %d col %d", msg, line_count, col_count) )
end
local function codepoint_to_utf8(n)
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
local f = math.floor
if n <= 0x7f then
return string.char(n)
elseif n <= 0x7ff then
return string.char(f(n / 64) + 192, n % 64 + 128)
elseif n <= 0xffff then
return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
elseif n <= 0x10ffff then
return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
f(n % 4096 / 64) + 128, n % 64 + 128)
end
error( string.format("invalid unicode codepoint '%x'", n) )
end
local function parse_unicode_escape(s)
local n1 = tonumber( s:sub(3, 6), 16 )
local n2 = tonumber( s:sub(9, 12), 16 )
-- Surrogate pair?
if n2 then
return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
else
return codepoint_to_utf8(n1)
end
end
local function parse_string(str, i)
local has_unicode_escape = false
local has_surrogate_escape = false
local has_escape = false
local last
for j = i + 1, #str do
local x = str:byte(j)
if x < 32 then
decode_error(str, j, "control character in string")
end
if last == 92 then -- "\\" (escape char)
if x == 117 then -- "u" (unicode escape sequence)
local hex = str:sub(j + 1, j + 5)
if not hex:find("%x%x%x%x") then
decode_error(str, j, "invalid unicode escape in string")
end
if hex:find("^[dD][89aAbB]") then
has_surrogate_escape = true
else
has_unicode_escape = true
end
else
local c = string.char(x)
if not escape_chars[c] then
decode_error(str, j, "invalid escape char '" .. c .. "' in string")
end
has_escape = true
end
last = nil
elseif x == 34 then -- '"' (end of string)
local s = str:sub(i + 1, j - 1)
if has_surrogate_escape then
s = s:gsub("\\u[dD][89aAbB]..\\u....", parse_unicode_escape)
end
if has_unicode_escape then
s = s:gsub("\\u....", parse_unicode_escape)
end
if has_escape then
s = s:gsub("\\.", escape_char_map_inv)
end
return s, j + 1
else
last = x
end
end
decode_error(str, i, "expected closing quote for string")
end
local function parse_number(str, i)
local x = next_char(str, i, delim_chars)
local s = str:sub(i, x - 1)
local n = tonumber(s)
if not n then
decode_error(str, i, "invalid number '" .. s .. "'")
end
return n, x
end
local function parse_literal(str, i)
local x = next_char(str, i, delim_chars)
local word = str:sub(i, x - 1)
if not literals[word] then
decode_error(str, i, "invalid literal '" .. word .. "'")
end
return literal_map[word], x
end
local function parse_array(str, i)
local res = {}
local n = 1
i = i + 1
while 1 do
local x
i = next_char(str, i, space_chars, true)
-- Empty / end of array?
if str:sub(i, i) == "]" then
i = i + 1
break
end
-- Read token
x, i = parse(str, i)
res[n] = x
n = n + 1
-- Next token
i = next_char(str, i, space_chars, true)
local chr = str:sub(i, i)
i = i + 1
if chr == "]" then break end
if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
end
return res, i
end
local function parse_object(str, i)
local res = {}
i = i + 1
while 1 do
local key, val
i = next_char(str, i, space_chars, true)
-- Empty / end of object?
if str:sub(i, i) == "}" then
i = i + 1
break
end
-- Read key
if str:sub(i, i) ~= '"' then
decode_error(str, i, "expected string for key")
end
key, i = parse(str, i)
-- Read ':' delimiter
i = next_char(str, i, space_chars, true)
if str:sub(i, i) ~= ":" then
decode_error(str, i, "expected ':' after key")
end
i = next_char(str, i + 1, space_chars, true)
-- Read value
val, i = parse(str, i)
-- Set
res[key] = val
-- Next token
i = next_char(str, i, space_chars, true)
local chr = str:sub(i, i)
i = i + 1
if chr == "}" then break end
if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
end
return res, i
end
local char_func_map = {
[ '"' ] = parse_string,
[ "0" ] = parse_number,
[ "1" ] = parse_number,
[ "2" ] = parse_number,
[ "3" ] = parse_number,
[ "4" ] = parse_number,
[ "5" ] = parse_number,
[ "6" ] = parse_number,
[ "7" ] = parse_number,
[ "8" ] = parse_number,
[ "9" ] = parse_number,
[ "-" ] = parse_number,
[ "t" ] = parse_literal,
[ "f" ] = parse_literal,
[ "n" ] = parse_literal,
[ "[" ] = parse_array,
[ "{" ] = parse_object,
}
parse = function(str, idx)
local chr = str:sub(idx, idx)
local f = char_func_map[chr]
if f then
return f(str, idx)
end
decode_error(str, idx, "unexpected character '" .. chr .. "'")
end
function json.decode(str)
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
local res, idx = parse(str, next_char(str, 1, space_chars, true))
idx = next_char(str, idx, space_chars, true)
if idx <= #str then
decode_error(str, idx, "trailing garbage")
end
return res
end
return json |
local theme = {}
theme.font = "Terminus 9"
--theme.bg_normal = "#222222"
theme.bg_normal = "#CCCCCC"
theme.bg_focus = theme.bg_normal
theme.bg_urgent = "#ff0000"
theme.bg_minimize = "#444444"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#000000"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.battery_high = "#66d93c"
theme.battery_medium = "#edf940"
theme.battery_low = "#db2a20"
theme.battery_bg = theme.bg_normal
theme.battery_border = "#000000"
theme.snap_old = "#cccccc"
theme.snap_new = "#66d93c"
theme.snap_border = "#000000"
theme.useless_gap = 2
theme.border_width = 1
theme.border_normal = "#000000"
theme.border_focus = "#535d6c"
theme.border_marked = "#91231c"
theme.clip_icon = "~/.config/awesome/themes/bold_white/clip_icon.png"
-- Define the image to load
theme.titlebar_close_button_normal = "/usr/local/share/awesome/themes/default/titlebar/close_normal.png"
theme.titlebar_close_button_focus = "/usr/local/share/awesome/themes/default/titlebar/close_focus.png"
theme.titlebar_minimize_button_normal = "/usr/local/share/awesome/themes/default/titlebar/minimize_normal.png"
theme.titlebar_minimize_button_focus = "/usr/local/share/awesome/themes/default/titlebar/minimize_focus.png"
theme.titlebar_ontop_button_normal_inactive = "/usr/local/share/awesome/themes/default/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = "/usr/local/share/awesome/themes/default/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = "/usr/local/share/awesome/themes/default/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = "/usr/local/share/awesome/themes/default/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive = "/usr/local/share/awesome/themes/default/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = "/usr/local/share/awesome/themes/default/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = "/usr/local/share/awesome/themes/default/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = "/usr/local/share/awesome/themes/default/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive = "/usr/local/share/awesome/themes/default/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = "/usr/local/share/awesome/themes/default/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = "/usr/local/share/awesome/themes/default/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = "/usr/local/share/awesome/themes/default/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = "/usr/local/share/awesome/themes/default/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = "/usr/local/share/awesome/themes/default/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = "/usr/local/share/awesome/themes/default/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = "/usr/local/share/awesome/themes/default/titlebar/maximized_focus_active.png"
theme.wallpaper = "~/.background.png"
-- You can use your own layout icons like this:
theme.layout_fairh = "/usr/local/share/awesome/themes/default/layouts/fairh.png"
theme.layout_fairv = "/usr/local/share/awesome/themes/default/layouts/fairv.png"
theme.layout_floating = "/usr/local/share/awesome/themes/default/layouts/floating.png"
theme.layout_magnifier = "/usr/local/share/awesome/themes/default/layouts/magnifier.png"
theme.layout_max = "/usr/local/share/awesome/themes/default/layouts/max.png"
theme.layout_fullscreen = "/usr/local/share/awesome/themes/default/layouts/fullscreen.png"
theme.layout_tilebottom = "/usr/local/share/awesome/themes/default/layouts/tilebottom.png"
theme.layout_tileleft = "/usr/local/share/awesome/themes/default/layouts/tileleft.png"
theme.layout_tile = "/usr/local/share/awesome/themes/default/layouts/tile.png"
theme.layout_tiletop = "/usr/local/share/awesome/themes/default/layouts/tiletop.png"
theme.layout_spiral = "/usr/local/share/awesome/themes/default/layouts/spiral.png"
theme.layout_dwindle = "/usr/local/share/awesome/themes/default/layouts/dwindle.png"
theme.layout_cornernw = "/usr/local/share/awesome/themes/default/layouts/cornernw.png"
theme.layout_cornerne = "/usr/local/share/awesome/themes/default/layouts/cornerne.png"
theme.layout_cornersw = "/usr/local/share/awesome/themes/default/layouts/cornersw.png"
theme.layout_cornerse = "/usr/local/share/awesome/themes/default/layouts/cornerse.png"
theme.awesome_icon = "/usr/local/share/awesome/icons/awesome16.png"
-- Define the icon theme for application icons. If not set then the icons
-- from /usr/share/icons and /usr/share/icons/hicolor will be used.
theme.icon_theme = nil
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
|
local skinSwapTrigger = {}
skinSwapTrigger.name = "SkinModHelper/SkinSwapTrigger"
skinSwapTrigger.placements = {
{
name = "normal",
data = {
width = 16,
height = 16,
skinId = "Default";
revertOnLeave = false;
}
}
}
return skinSwapTrigger |
object_tangible_furniture_decorative_event_lifeday07_banner_kit = object_tangible_furniture_decorative_shared_event_lifeday07_banner_kit:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_decorative_event_lifeday07_banner_kit, "object/tangible/furniture/decorative/event_lifeday07_banner_kit.iff")
|
-- Minimal controller draw ent. Inherit and override "guideline" function to control pointer line display
namespace "standard"
local Hand = classNamed("Hand", Ent)
local desktop = lovr.headset.getDriver() == "desktop"
local platform = require "skategirl.engine.platform"
-- If first value is false, no guideline. If true, guideline.
-- First and second values may optionally be a color (cpml style table) and a termination point (a vec3)
function Hand:guideline(i, controllerName)
return false
end
function Hand:onDraw()
for i,controllerName in ipairs(lovr.headset.getHands()) do
-- Attempt to load a model
if not self.controllerModel then self.controllerModel = {} end
if self.controllerModel[i] == nil then
if platform.oculusmobile then -- See issue#417
self.controllerModel[i] = false print "Skipping controller model on Oculus Mobile"
else
self.controllerModel[i] = lovr.headset.newModel(controllerName)
if not self.controllerModel[i] then self.controllerModel[i] = false print "NO CONTROLLER MODEL!" end -- If model load fails, don't try again
end
end
if self.controllerModel[i] then
local x, y, z, angle, ax, ay, az = lovr.headset.getPose(controllerName)
--x = x * 4 y = y * 4 z = z * 4 -- Good for background debug mode
self.controllerModel[i]:draw(x,y,z,1,angle,ax, ay, az)
elseif not desktop then -- On OculusVR, no-model is expected, due to lack of avatar sdk support
local x, y, z, angle, ax, ay, az = lovr.headset.getPose(controllerName) -- Placeholder: Draw a little box at an
local q = quat.from_angle_axis(angle, ax, ay, az)
local v = vec3(x, y, z) + q * vec3(0, -.025, .05)
lovr.graphics.setColor(1,1,1,1)
lovr.graphics.box('fill', v.x, v.y, v.z, .1, .05, .1, angle, ax, ay, az)
end
local guideline, guidelineTo = self:guideline(i, controllerName)
if guideline then
if type(guideline) == "table" then
lovr.graphics.setColor(unpack(guideline))
end
local at, q = unpackPose(controllerName)
local a2 = guidelineTo or forwardLine(at, q)
lovr.graphics.line(at.x,at.y,at.z, a2.x,a2.y,a2.z)
end
end
end
return Hand
|
local cmd = vim.cmd
local global_theme = "themes/" .. vim.g.nvchad_theme
local colors = require(global_theme)
local white = colors.white
local darker_black = colors.darker_black
local black = colors.black
local black2 = colors.black2
local one_bg = colors.one_bg
local one_bg2 = colors.one_bg2
local grey = colors.grey
local grey_fg = colors.grey_fg
local red = colors.red
local line = colors.line
local green = colors.green
local nord_blue = colors.nord_blue
local blue = colors.blue
local yellow = colors.yellow
local purple = colors.purple
local pmenu_bg = colors.pmenu_bg
local folder_bg = colors.folder_bg
-- for guifg , bg
local function fg(group, color)
cmd("hi " .. group .. " guifg=" .. color)
end
local function bg(group, color)
cmd("hi " .. group .. " guibg=" .. color)
end
local function fg_bg(group, fgcol, bgcol)
cmd("hi " .. group .. " guifg=" .. fgcol .. " guibg=" .. bgcol)
end
-- blankline
fg("IndentBlanklineChar", line)
-- misc --
fg("LineNr", grey)
-- Comments
local ui = require("utils").load_config().ui
if ui.italic_comments then
cmd("hi Comment gui=italic guifg=" .. grey_fg)
else
fg("Comment", grey_fg)
end
fg("NvimInternalError", red)
fg("VertSplit", line)
fg("EndOfBuffer", black)
-- fg_bg("Visual",light_grey, colors.lightbg)
-- Pmenu
bg("Pmenu", one_bg)
bg("PmenuSbar", one_bg2)
bg("PmenuSel", pmenu_bg)
bg("PmenuThumb", nord_blue)
-- inactive statuslines as thin splitlines
cmd("hi! StatusLineNC gui=underline guifg=" .. line)
-- line n.o
cmd("hi clear CursorLine")
fg("cursorlinenr", white)
-- git signs ---
fg_bg("DiffAdd", nord_blue, "none")
fg_bg("DiffChange", grey_fg, "none")
fg_bg("DiffModified", nord_blue, "none")
-- NvimTree
fg("NvimTreeFolderIcon", folder_bg)
fg("NvimTreeFolderName", folder_bg)
fg("NvimTreeGitDirty", red)
fg("NvimTreeOpenedFolderName", blue)
fg("NvimTreeEmptyFolderName", blue)
fg("NvimTreeIndentMarker", one_bg2)
fg("NvimTreeVertSplit", darker_black)
bg("NvimTreeVertSplit", darker_black)
fg("NvimTreeEndOfBuffer", darker_black)
cmd("hi NvimTreeRootFolder gui=underline guifg=" .. red)
bg("NvimTreeNormal", darker_black)
fg_bg("NvimTreeStatuslineNc", darker_black, darker_black)
fg_bg("NvimTreeWindowPicker", red, black2)
-- telescope
fg("TelescopeBorder", line)
fg("TelescopePromptBorder", line)
fg("TelescopeResultsBorder", line)
fg("TelescopePreviewBorder", grey)
-- LspDiagnostics ---
-- error / warnings
fg("DiagnosticSignError", red)
fg("DiagnosticVirtualTextError", red)
fg("DiagnosticSignWarn", yellow)
fg("DiagnosticVirtualTextWarn", yellow)
-- info
fg("DiagnosticSignInfo", green)
fg("DiagnosticsVirtualTextInfo", green)
-- hint
fg("DiagnosticSignHint", purple)
fg("DiagnosticVirtualTextHint", purple)
-- signature
fg("LspSignatureActiveParameter", purple)
-- document highlight
cmd("hi default link LspReferenceText CursorColumn")
cmd("hi default link LspReferenceRead LspReferenceText")
cmd("hi default link LspReferenceWrite LspReferenceText")
-- dashboard
fg("DashboardHeader", grey_fg)
fg("DashboardCenter", grey_fg)
fg("DashboardShortcut", grey_fg)
fg("DashboardFooter", grey_fg)
if require("utils").load_config().ui.transparency then
bg("Normal", "NONE")
bg("Folded", "NONE")
fg("Folded", "NONE")
bg("NvimTreeNormal", "NONE")
bg("NvimTreeVertSplit", "NONE")
fg("NvimTreeVertSplit", grey)
bg("NvimTreeStatusLineNC", "NONE")
fg("Comment", grey)
end
-- For floating windows
bg("NormalFloat", one_bg)
fg("FloatBorder", blue)
--
|
local pl
local create_retry
local trex, pol, apikeys
local arb
local dump_orderbook = function (o, name, depth)
local min = math.min
io.write (string.format ("[%s - %s]\n", name, tostring(o)))
io.write (string.format ("%12s %12s %14s %13s\n",
"sell price", "sell amount",
"buy price", "buy amount"))
depth = depth or 200
depth = min (depth, min (#o.sell.price, #o.buy.price))
for i = 1, depth do
local out = string.format ("%12.8f %12.4f || %12.8f %12.4f",
o.sell.price[i], o.sell.amount[i],
o.buy.price[i], o.buy.amount[i])
print (out)
end
end
local arb_module = {}
arb_module.startup = function ()
pl = require 'pl.import_into' ()
apikeys = require 'apikeys'
make_retry = require 'tools.retry'
trex = require 'exchange.bittrex' (apikeys.bittrex)
pol = require 'exchange.poloniex' (apikeys.poloniex)
trex = make_retry (trex, 4, "timeout", "closed")
pol = make_retry (pol, 4, "timeout", "closed")
arb = require 'arbitrate'.arbitrate
log = require 'tools.logger' "Arb"
end
arb_module.main = function ()
local dump = require 'pl.pretty'.dump
local timer = require 'pl.test'.timer
local trex_orders, pol_orders
local arb_str = "%s buy %.8f => %s sell %.8f, Qty: %.8f"
while true do
local noerr, errmsg = pcall (function ()
timer ("pol orderbook", 1, function ()
pol_orders = pol:orderbook ("BTC", "XMR")
end)
timer ("trex orderbook", 1, function ()
trex_orders = trex:orderbook ("BTC", "XMR")
end)
local res = arb (trex_orders, pol_orders)
if res then
res.buy = res.buy == trex_orders and "bittrex" or "poloniex"
res.sell = res.sell == pol_orders and "poloniex" or "bittrex"
for _, v in ipairs (res) do
local prof_spread = v.amount * (v.sellprice - v.buyprice)
log (arb_str:format (res.buy, v.buyprice,
res.sell, v.sellprice,
v.amount, prof_spread))
log ( ("Risking: %.8f -> Profit: %.8f btc, ratio: %.6f"):format (v.buyprice * v.amount,
prof_spread,
100*prof_spread / (v.buyprice * v.amount) ))
end
-- local o1, o2
-- timer ("trex buy", 1, function () o1 = trex:buy ("BTC", "CINNI", 0.000011, 10.001) end)
-- timer ("pol buy", 1, function () o2 = pol:buy ("BTC", "CINNI", 0.000011, 10.001) end)
-- dump (o1); dump (o2)
-- timer ("trex cancel", 1, function ()
-- if o1.orderNumber then
-- o1 = trex:cancelorder ("BTC", "CINNI", o1.orderNumber)
-- else
-- local o1 = assert (trex:openorders ("BTC", "CINNI"))
-- for each, order in ipairs (o1) do
-- assert (trex:cancelorder ("BTC", "CINNI", order.order_id))
-- end
-- end
-- end)
-- timer ("pol cancel", 1, function ()
-- o2 = pol:cancelorder ("BTC", "CINNI", o2.orderNumber)
-- end)
-- dump (o1); dump (o2)
-- assert (o1 and o1.response == "success")
-- assert (o2 and o2.success == 1)
dump_orderbook (trex_orders, "bittrex", 4)
dump_orderbook (pol_orders, "poloniex", 4)
end
end)
log._if (not noerr, errmsg)
if not noerr and errmsg:match "wantread" then break end
coroutine.yield ()
end
end
arb_module.interval = 4 -- secs
return arb_module
|
-- Copy of the bot_nevermore.lua. It is used in the recording mode and
-- Dota 2 client requires the files to have this structure.
require(GetScriptDirectory() .. '/util/json')
local Observation = require(GetScriptDirectory() .. '/agent_utils/observation')
local Reward = require(GetScriptDirectory() .. '/agent_utils/reward')
local Action = require(GetScriptDirectory() .. '/agent_utils/action')
local action_to_do_next
local current_action = 0
-- Bot communication automaton.
local IDLE = 0
local ACTION_RECEIVED = 1
local SEND_OBSERVATION = 2
local fsm_state = SEND_OBSERVATION
local wrong_action = 0
local messages = {}
--- Executes received action.
-- @param action_info bot action
--
function execute_action(action)
wrong_action = Action.execute_action(action)
end
--- Create JSON message from table 'message' of type 'type'.
-- @param message table containing message
-- @param type type of message e.g. 'what_next' or 'observation'
-- @return JSON encoded {'type': type, 'content': message}
--
function create_message(message, type)
local msg = {
['type'] = type,
['content'] = message
}
local encode_msg = Json.Encode(msg)
return encode_msg
end
--- Send JSON message to bot server.
-- @param json_message message to send
-- @param route route ('/what_next' or '/observation')
-- @param callback called after response is received
--
function send_message(json_message, route, callback)
local req = CreateHTTPRequest(':5000' .. route)
req:SetHTTPRequestRawPostBody('application/json', json_message)
req:Send(function(result)
for k, v in pairs(result) do
if k == 'Body' then
if v ~= '' then
local response = Json.Decode(v)
if callback ~= nil then
callback(response)
end
action_to_do_next = response['action']
fsm_state = response['fsm_state']
else
fsm_state = WHAT_NEXT
end
end
end
end)
end
--- Ask what to do next.
--
function send_what_next_message()
local message = create_message('', 'what_next')
send_message(message, '/what_next', nil)
end
--- Send JSON with the message.
--
function send_observation_message(msg)
send_message(create_message(msg, 'observation'), '/observation', nil)
end
function Think()
-- current state info
Observation.update_info_about_environment()
local message = {
['observation'] = Observation.get_observation(),
['reward'] = Reward.get_reward(wrong_action),
['done'] = Observation.is_done(),
['action_info'] = Observation.get_action_info()
}
table.insert(messages, {current_action, message})
if fsm_state == SEND_OBSERVATION then
fsm_state = IDLE
send_observation_message(messages)
print('FRAMES SENT', #messages)
messages = {}
elseif fsm_state == ACTION_RECEIVED then
fsm_state = SEND_OBSERVATION
current_action = action_to_do_next
elseif fsm_state == IDLE then
-- Do nothing
end
execute_action(current_action)
end
|
local function make(p)
if p > 10 then
local n = p + 1
return {
incr = function(i) n = n + i end,
mult = function(i) n = n * i end,
get = function() return n end,
}
else
local n = 2*p
return {
incr = function(i) n = n + i end,
mult = function(i) n = n * i end,
get = function() return n end,
}
end
end
local obj = make(7)
obj.mult(3)
obj.incr(1)
obj.mult(2)
obj.incr(5)
print(obj.get())
|
--[[
animationUI.lua
Copyright (C) 2016 Kano Computing Ltd.
License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2
]]--
local CircleWipeIn = require 'game.ui.animation.circleWipeIn'
local CircleWipeOut = require 'game.ui.animation.circleWipeOut'
local RectangleWipeIn = require 'game.ui.animation.rectangleWipeIn'
local RectangleWipeOut = require 'game.ui.animation.rectangleWipeOut'
local RectangleSwipeIn = require 'game.ui.animation.rectangleSwipeIn'
local RectangleSwipeOut = require 'game.ui.animation.rectangleSwipeOut'
local RectangleVerticalWipeIn = require 'game.ui.animation.rectangleVerticalWipeIn'
local RectangleVerticalWipeOut = require 'game.ui.animation.rectangleVerticalWipeOut'
local AnimationUI = {}
AnimationUI.__index = AnimationUI
function AnimationUI.create(gameStates, uiManager)
-- print("CREATING AnimationUI") -- DEBUG_TAG
local self = setmetatable({}, AnimationUI)
-- parameters
self.gameStates = gameStates
self.uiManager = uiManager
-- animation types available
self.CIRCLE_WIPE_IN = 'circleWipeIn'
self.CIRCLE_WIPE_OUT = 'circleWipeOut'
self.RECTANGLE_WIPE_IN = 'rectangleWipeIn'
self.RECTANGLE_WIPE_OUT = 'rectangleWipeOut'
self.RECTANGLE_SWIPE_IN = 'rectangleSwipeIn'
self.RECTANGLE_SWIPE_OUT = 'rectangleSwipeOut'
self.RECTANGLE_VERTICAL_WIPE_IN = 'rectangleVerticalWipeIn'
self.RECTANGLE_VERTICAL_WIPE_OUT = 'rectangleVerticalWipeOut'
-- variables
self.animations = {
[self.CIRCLE_WIPE_IN] = CircleWipeIn.create(),
[self.CIRCLE_WIPE_OUT] = CircleWipeOut.create(),
[self.RECTANGLE_WIPE_IN] = RectangleWipeIn.create(),
[self.RECTANGLE_WIPE_OUT] = RectangleWipeOut.create(),
[self.RECTANGLE_SWIPE_IN] = RectangleSwipeIn.create(),
[self.RECTANGLE_SWIPE_OUT] = RectangleSwipeOut.create(),
[self.RECTANGLE_VERTICAL_WIPE_IN] = RectangleVerticalWipeIn.create(),
[self.RECTANGLE_VERTICAL_WIPE_OUT] = RectangleVerticalWipeOut.create(),
}
self.currentAnimation = nil
self.postAnimationCallback = nil
self.callbackArgs = nil
return self
end
function AnimationUI:load()
-- print("LOADING AnimationUI") -- DEBUG_TAG
for _, animation in pairs(self.animations) do
animation:load()
end
end
function AnimationUI:update(dt)
if not self.currentAnimation:isFinished() then
self.currentAnimation:update(dt)
else
self:deactivate()
end
end
function AnimationUI:draw()
self.currentAnimation:draw()
end
function AnimationUI:activate(type, postAnimationCallback, ...)
self.currentAnimation = self.animations[type]
self.postAnimationCallback = postAnimationCallback
self.callbackArgs = {...}
self.currentAnimation:start()
self.gameStates:changeState(self.gameStates.STATE_ANIMATION)
self.uiManager:changeState(self.uiManager.STATE_ANIMATION)
end
function AnimationUI:deactivate()
self.gameStates:changeState(self.gameStates.STATE_INGAME)
self.uiManager:changeState(self.uiManager.STATE_GAMEUI)
local postAnimationCallback = self.postAnimationCallback
local callbackArgs = self.callbackArgs
self.currentAnimation = nil
self.postAnimationCallback = nil
self.callbackArgs = nil
if postAnimationCallback then
postAnimationCallback(unpack(callbackArgs))
end
end
-- Input --------------------------------------------------------------------------------
function AnimationUI:controls()
return
end
return AnimationUI
|
game.ReplicatedStorage.Click.OnServerEvent:connect(function(Player,Target)
if Target:IsDescendantOf(script.Parent) then
game.ReplicatedStorage.Boom:FireClient(Player,script.Parent)
game.ServerStorage.AwardItem:Invoke(Player,501,1)
end
end) |
if (system.getPreference('locale', 'identifier') == 'pt_BR') then
return {
applicationName = 'JUMRUN',
developedByTitle = 'Desenvolvido por:',
developerName = 'AFG',
developerGithubLink = 'github.com/arturfgirao',
developerEmail = 'arturfgirao@gmail.com',
designedByTitle = 'Design por:',
firstDesignerName = 'Luis GG',
firstDesignerGithub = 'David Clifte',
secondDesignerName = 'Artur Girao',
secondDesignerGithub = 'github.com/arturfgirao',
songsTitle = 'Sons:',
songsLink = 'freemusicarchive.org/music/boxcat_games',
imagesTitle = 'Imagens:',
imagesLink = 'wallpaper.zone/night-background-images',
score = 'Pontuação',
enableSound = 'Habilitar som',
enableVibration = 'Habilitar vibração',
enableLargeSprites = 'Habilitar imagens grandes',
playTitle = 'Jogar',
preferencesTitle = 'Configurações',
aboutTitle = 'Sobre',
menuTitle = 'Menu',
yes = 'Sim',
no = 'Não',
isEnUS = false
}
else
return {
applicationName = 'JUMRUN',
developedByTitle = 'Developed by:',
developerName = 'AFG',
developerGithubLink = 'github.com/arturfgirao',
developerEmail = 'arturfgirao@gmail',
designedByTitle = 'Designed by:',
firstDesignerName = 'Luiz GG',
firstDesignerGithub = 'David Clifte',
secondDesignerName = 'Artur Girao',
secondDesignerGithub = 'github.com/arturfgirao',
songsTitle = 'Songs:',
songsLink = 'freemusicarchive.org/music/boxcat_games',
imagesTitle = 'Images:',
imagesLink = 'wallpaper.zone/night-background-images',
score = 'Score',
enableSound = 'Enable sound',
enableVibration = 'Enable vibration',
enableLargeSprites = 'Enable large sprites',
playTitle = 'Play',
preferencesTitle = 'Preferences',
aboutTitle = 'About',
menuTitle = 'Menu',
yes = 'Yes',
no = 'No',
isEnUS = true
}
end
|
-----------------------------------
-- Area: Phomiuna_Aqueducts
-- NM: Tres Duendes
-----------------------------------
function onMobDeath(mob, player, isKiller)
end
function onMobDespawn(mob)
mob:setRespawnTime(math.random(75600, 86400)) -- 21 to 24 hours
end
|
local completeLifecycleOrderTests = require(script:FindFirstAncestor("lifecycle").completeLifecycleOrderTests)
return function()
describe("never run", function()
it("SHOULD FAIL", function()
fail("This should have never ran. Check testNamePattern")
end)
end)
describe("super specific describe block", completeLifecycleOrderTests)
end
|
local switch = {
[1] = function()
LoadStory(4060101,function() end)
end
}
if module.TeamModule.GetTeamInfo().id > 0 then
local stage = module.CemeteryModule.GetTeam_stage(106)
stage = stage + 1
--ERROR_LOG("STAGE:",stage)
local f = switch[stage]
print("------------",stage)
if(f) then
f()
else
end
end |
-- Aaahhh (screams of terror, not a yawn)
function color (r, g, b)
return {r, g, b}
end
function fromFile (filename)
-- file extensions of different length
filetype3 = string.sub(filename, -4)
filetype4 = string.sub(filename, -5)
filetype5 = string.sub(filename, -6)
filetype7 = string.sub(filename, -8)
-- "loading" a model
if filetype3 == ".j3o" or
filetype3 == ".obj" or
filetype5 == ".blend" or
filetype8 == ".mesh.xml" then
return {
meshFile = filename,
material = {}
}
end
-- "loading" a material
if filetype3 == ".j3m" then
return {
materialFile = filename
}
end
-- "loading" a texture
if filetype3 == ".png" or
filetype3 == ".jpg" or
filetype3 == ".bmp" or
filetype3 == ".tga" or
filetype4 == ".jpeg" or
filetype3 == ".gif" then
return {
textureFile = filename,
flipY = false
}
end
-- lua file
if filetype3 == ".lua" then
return dofile(ADDON_ROOT .. filename)
end
end
|
local luaunit = require("luaunit")
require("eos_exception_u4")
TestEosExceptionU4 = {}
function TestEosExceptionU4:test_eos_exception_u4()
luaunit.assertError(EosExceptionU4.from_file, "src/term_strz.bin")
end
|
--
-- Author: Alexey Melnichuk <mimir@newmail.ru>
--
-- Copyright (C) 2013-2014 Alexey Melnichuk <mimir@newmail.ru>
--
-- Licensed according to the included 'LICENCE' document
--
-- This file is part of lua-lzqm library.
--
return require "lzmq.impl.threads"("lzmq") |
function MineSection.OnInit()
end
function MineSection.OnEnable()
end
function MineSection.Update(dt)
local moveSpeed = this.manager.moveSpeed + this.manager.boostSpeed;
GameObject.TranslateZ(-dt * moveSpeed);
if GameObject.GetTransformZ() < -9.0 then
this.GameObject:Delete();
end
end
function MineSection.OnDisable()
end
function MineSection.OnDestroy()
end
|
function DarknessMinion_Corruption(pUnit, Event)
if pUnit:GetHealthPct() < 70 then
pUnit:FullCastSpell(25419)
pUnit:RegisterEvent("DarknessMinion_Shadowbolt", 1000, 0)
end
end
function DarknessMinion_Shadowbolt(pUnit, Event)
if pUnit:GetHealthPct() < 30 then
pUnit:FullCastSpell(29640)
end
end
function DarknessMinion_start(pUnit, Event)
pUnit:RegisterEvent("DarknessMinion_Corruption", 1000, 0)
end
RegisterUnitEvent(1337134, 1, "DarknessMinion_start") |
require 'Util'
require 'Constants'
require 'Menu'
require 'Music'
require 'Skill'
require 'Triggers'
Battle = class('Battle')
GridSpace = class('GridSpace')
PULSE = 0.4
function GridSpace:initialize(sp)
self.occupied = nil
if sp then
self.occupied = sp
end
self.assists = {}
self.n_assists = 0
end
function Battle:initialize(battle_id, player, chapter)
self.id = battle_id
self.chapter = chapter
-- Tracking state
self.turn = 0
self.seen = {}
-- Data file
local data_file = 'Abelon/data/battles/' .. self.id .. '.txt'
local data = readLines(data_file)
-- Get base tile of the top left of the grid
local tile_origin = readArray(data[3], tonumber)
self.origin_x = tile_origin[1]
self.origin_y = tile_origin[2]
-- Battle grid
local grid_index = 14
local grid_dim = readArray(data[grid_index], tonumber)
self.grid_w = grid_dim[1]
self.grid_h = grid_dim[2]
self.grid = {}
for i = 1, self.grid_h do
local row_str = data[grid_index + i]
self.grid[i] = {}
for j = 1, self.grid_w do
self.grid[i][j] = ite(row_str:sub(j, j) == 'T', GridSpace:new(), F)
end
end
-- Participants and statuses
self.player = player
self.status = {}
self.enemy_order = readArray(data[6])
self.participants = concat(
self:readEntities(data, 4),
self:readEntities(data, 5)
)
self.enemy_action = nil
-- Win conditions and loss conditions
self.win = readArray(data[7], function(s) return wincons[s] end)
self.lose = readArray(data[8], function(s) return losscons[s] end)
self.turnlimits = readArray(data[9], tonumber)
if next(self.turnlimits) then table.insert(self.lose, {}) end
self:adjustDifficultyFrom(MASTER)
-- Battle cam starting location
self.battle_cam_x = self.chapter.camera_x
self.battle_cam_y = self.chapter.camera_y
self.battle_cam_speed = 170
-- Render timers
self.pulse_timer = 0
self.pulse = false
self.shading = 0.2
self.shade_dir = 1
self.action_in_progress = nil
self.skill_in_use = nil
self.render_bexp = false
self.levelup_queue = {}
-- Music
self.chapter:stopMusic()
self.chapter.current_music = readField(data[10])
-- Action stack
self.suspend_stack = {}
self.stack = {}
-- Participants to battle behavior
for i = 1, #self.participants do
self.participants[i]:changeBehavior('battle')
end
self.player:changeMode('battle')
end
-- Put participants on grid
function Battle:readEntities(data, idx)
local t = {}
for k,v in pairs(readDict(data[idx], ARR, nil, tonumber)) do
-- Put sprite on grid and into participants
local sp = self.chapter:getSprite(k)
table.insert(t, sp)
self.grid[v[2]][v[1]] = GridSpace:new(sp)
-- Initialize sprite status
self.status[sp:getId()] = {
['sp'] = sp,
['team'] = ite(idx == 4, ALLY, ENEMY),
['location'] = { v[1], v[2] },
['effects'] = {},
['alive'] = true,
['acted'] = false,
['attack'] = nil,
['assist'] = nil,
['prepare'] = nil
}
local x_tile = self.origin_x + v[1]
local y_tile = self.origin_y + v[2]
local x, y = self.chapter:getMap():tileToPixels(x_tile, y_tile)
sp:resetPosition(x, y)
-- If an enemy, prepare their first skill
if self.status[sp:getId()]['team'] == ENEMY then
self:prepareSkill(sp)
end
end
return t
end
function Battle:adjustDifficultyFrom(old)
-- Adjust enemy stats
local new = self.chapter.difficulty
local factor = 3 * (old - new)
for i = 1, #self.participants do
local sp = self.participants[i]
if not self:isAlly(sp) then
local attrs = sp.attributes
local adjust = {
'endurance', 'focus', 'force', 'affinity', 'reaction'
}
for j = 1, #adjust do
attrs[adjust[j]] = math.max(0, attrs[adjust[j]] - factor)
end
sp.health = math.min(sp.health, attrs['endurance'])
sp.ignea = math.min(sp.ignea, attrs['focus'])
end
end
-- Adjust turn limit, if there is one
if next(self.turnlimits) then
self.turnlimit = self.turnlimits[new]
self.lose[#self.lose] = { self.turnlimit .. ' turns pass',
function(b) return ite(b.turn > b.turnlimit, 'turnlimit', false) end
}
-- Stupid hack to refresh objectives box
if self.stack then
self:closeMenu()
self:openBattleStartMenu()
local m = self:getMenu()
m:hover(DOWN)
m:hover(DOWN)
m:forward()
m:hover(UP)
m:forward()
for i = 1, new - 1 do m:hover(DOWN) end
end
end
end
function Battle:getId()
return self.id
end
function Battle:getCamera()
self:updateBattleCam()
return self.battle_cam_x, self.battle_cam_y, self.battle_cam_speed
end
function Battle:push(e)
for i = 1, #self.stack do
if self.stack[i]['cursor'] then
self.stack[i]['cursor'][3] = false
end
end
self.stack[#self.stack + 1] = e
end
function Battle:pop()
local st = self.stack
table.remove(st, #st)
while next(st) and st[#st]['stage'] == STAGE_BUBBLE do
table.remove(st, #st)
end
end
function Battle:stackBase()
return {
['stage'] = STAGE_FREE,
['cursor'] = { 1, 1, false, { HIGHLIGHT } },
['views'] = {
{ BEFORE, TEMP, function(b) b:renderMovementHover() end }
}
}
end
function Battle:stackBubble(c, moves)
local x = 1
local y = 1
if c then
x = c[1]
y = c[2]
end
bubble = {
['stage'] = STAGE_BUBBLE,
['cursor'] = { x, y, false, { 0, 0, 0, 0 } },
['views'] = {}
}
if moves then bubble['moves'] = moves end
return bubble
end
function Battle:getCursor(n)
c = nil
found = 0
n = ite(n, n, 1)
for i = 1, #self.stack do
if self.stack[#self.stack - i + 1]['cursor'] then
c = self.stack[#self.stack - i + 1]['cursor']
found = found + 1
if found == n then
return c
end
end
end
return nil
end
function Battle:getMenu()
if next(self.stack) ~= nil then
local st = self.stack[#self.stack]
return st['menu']
end
return nil
end
function Battle:getSprite()
top = nil
for i = 1, #self.stack do
if self.stack[i]['sp'] then
top = self.stack[i]['sp']
end
end
return top
end
function Battle:getMoves()
for i = 1, #self.stack do
if self.stack[#self.stack - i + 1]['moves'] then
return self.stack[#self.stack - i + 1]['moves']
end
end
end
function Battle:findSprite(sp_id)
local loc = self.status[sp_id]['location']
return loc[2], loc[1]
end
function Battle:getSkill()
for i = 1, #self.stack do
if self.stack[#self.stack - i + 1]['sk'] then
return self.stack[#self.stack - i + 1]['sk']
end
end
end
function Battle:moveCursor(x, y)
local c = self:getCursor()
if self.grid[y] and self.grid[y][x] and (x ~= c[1] or y ~= c[2]) then
sfx['hover']:play()
c[1] = x
c[2] = y
end
end
function Battle:moveSprite(sp, x, y)
local old_y, old_x = self:findSprite(sp:getId())
self.status[sp:getId()]['location'] = { x, y }
self.grid[old_y][old_x].occupied = nil
self.grid[y][x].occupied = sp
end
function Battle:isAlly(sp)
return self.status[sp:getId()]['team'] == ALLY
end
function Battle:getTmpAttributes(sp)
local y, x = self:findSprite(sp:getId())
return mkTmpAttrs(
sp.attributes,
self.status[sp:getId()]['effects'],
ite(self:isAlly(sp), self.grid[y][x].assists, {})
)
end
function Battle:getStage()
if next(self.stack) ~= nil then
return self.stack[#self.stack]['stage']
end
return nil
end
function Battle:setStage(s)
self.stack[#self.stack]['stage'] = s
end
function Battle:openMenu(m, views)
self:push({
['stage'] = STAGE_MENU,
['menu'] = m,
['views'] = views
})
end
function Battle:closeMenu()
if self.stack[#self.stack]['stage'] == STAGE_MENU then
self:pop()
end
end
function Battle:checkTriggers(phase, doneAction)
local triggers = battle_triggers[self.id][phase]
for k, v in pairs(triggers) do
if not self.seen[k] then
local scene_id = v(self)
if scene_id then
self.seen[k] = true
self:suspend(self.id .. '-' .. scene_id, doneAction)
return true
end
end
end
return false
end
function Battle:endTurn()
-- Check triggers first
local doneAction = function() self:endTurn() end
if self:checkTriggers(ENEMY, doneAction) then return end
-- Allies have their actions refreshed
for i = 1, #self.participants do
local sp = self.participants[i]
if self:isAlly(sp) then
self.status[sp:getId()]['acted'] = false
end
end
-- Prepare the first enemy's action and place it in self.enemy_action
self:planNextEnemyAction()
-- Let the first enemy go if exists, and prepare the subsequent enemy
if self.enemy_action then
self.stack = self.enemy_action
self:playAction()
else
-- If there are no enemies, it's immediately the ally phase
self:beginTurn()
end
end
function Battle:beginTurn()
-- Increment turn count
self.turn = self.turn + 1
-- Check win and loss
local battle_over = self:checkWinLose()
if battle_over then return end
-- Start menu open
self:openBeginTurnMenu()
end
function Battle:turnRefresh()
-- Decrement/clear statuses
for _, v in pairs(self.status) do
local es = v['effects']
local i = 1
while i <= #es do
if es[i].duration > 1 then
es[i].duration = es[i].duration - 1
i = i + 1
else
table.remove(es, i)
end
end
end
-- Clear all assists from the field
for i = 1, #self.grid do
for j = 1, #self.grid[i] do
if self.grid[i][j] then
self.grid[i][j].assists = {}
self.grid[i][j].n_assists = 0
end
end
end
-- Nobody has acted
for i = 1, #self.participants do
self.status[self.participants[i]:getId()]['acted'] = false
end
end
function Battle:suspend(scene_id, effects)
self.suspend_stack = self.stack
self.stack = {}
local doneAction = function()
self:restore()
if effects then effects() end
end
self.chapter:launchScene(scene_id, doneAction)
end
function Battle:restore()
self.stack = self.suspend_stack
self.suspend_stack = {}
end
function Battle:checkWinLose()
for i = 1, #self.lose do
local defeat_scene = self.lose[i][2](self)
if defeat_scene then
-- TODO: Change to defeat music
local scene_id = self.id .. '-' .. defeat_scene .. '-defeat'
self:suspend(scene_id, function()
self.stack = {}
self.battle_cam_x = self.chapter.camera_x
self.battle_cam_y = self.chapter.camera_y
self:openDefeatMenu()
end)
return true
end
end
for i = 1, #self.win do
if self.win[i][2](self) then
self.chapter:stopMusic()
sfx['victory']:play()
self.stack = {}
self:openVictoryMenu()
return true
end
end
return false
end
function Battle:awardBonusExp()
local bexp = 0
if self.turnlimit then
bexp = bexp + (self.turnlimit - self.turn) * 15
self.render_bexp = bexp
end
for i = 1, #self.participants do
local sp = self.participants[i]
if self:isAlly(sp) then
local lvlups = sp:gainExp(bexp)
if lvlups > 0 then self.levelup_queue[sp:getId()] = lvlups end
end
end
return bexp
end
function Battle:openBattleStartMenu()
local save = function(c)
self:closeMenu()
c:saveAndQuit()
end
local next = function(c)
self:closeMenu()
self:beginTurn()
end
local begin = MenuItem:new('Begin battle', {}, "Begin the battle", nil, next)
local wincon = MenuItem:new('Objectives', {},
'View victory and defeat conditions', self:buildObjectivesBox()
)
local settings = self.player:mkSettingsMenu()
local party = self.player:mkPartyMenu()
local restart = MenuItem:new('Restart chapter', {}, 'Start the chapter over',
nil, function(c) c:reloadChapter() end,
"Are you SURE you want to restart the chapter? You will lose ALL \z
progress made during the chapter."
)
local quit = MenuItem:new('Save and quit', {}, 'Quit the game', nil, save,
"Save current progress and close the game?"
)
local m = { wincon, party, settings, restart, quit, begin }
self:openMenu(Menu:new(nil, m, BOX_MARGIN, BOX_MARGIN, true), {})
end
function Battle:openVictoryMenu()
self:awardBonusExp()
local desc = 'Finish the battle'
local m = { MenuItem:new('Continue', {}, desc, nil,
function(c)
self.render_bexp = false
if next(self.levelup_queue) then
self:push({
['stage'] = STAGE_LEVELUP,
['views'] = {}
})
else
self.chapter:launchScene(self.id .. '-victory')
self.chapter:startMapMusic()
self.chapter.battle = nil
end
end
)}
local v = { " V I C T O R Y " }
self:openMenu(Menu:new(nil, m, CONFIRM_X, CONFIRM_Y(v), true, v, GREEN), {})
end
function Battle:openDefeatMenu()
local m = { MenuItem:new('Restart battle', {}, 'Start the battle over', nil,
function(c) c:reloadBattle() end
)}
local d = { " D E F E A T " }
self:openMenu(Menu:new(nil, m, CONFIRM_X, CONFIRM_Y(d), true, d, RED), {
{ AFTER, TEMP, function(b) b:renderLens({ 0.5, 0, 0 }) end }
})
end
function Battle:openEndTurnMenu()
self.stack = {}
local m = { MenuItem:new('End turn', {}, 'Begin enemy phase', nil,
function(c)
self:closeMenu()
self:endTurn()
end
)}
local e = { " E N E M Y P H A S E " }
self:openMenu(Menu:new(nil, m, CONFIRM_X, CONFIRM_Y(e), true, e, RED), {})
end
function Battle:openBeginTurnMenu()
self.stack = {}
local m = { MenuItem:new('Begin turn', {}, 'Begin ally phase', nil,
function(c)
self:closeMenu()
self:turnRefresh()
self.stack = { self:stackBase() }
local y, x = self:findSprite(self.player:getId())
local c = self:getCursor()
c[1] = x
c[2] = y
self:checkTriggers(ALLY)
end
)}
local e = { " A L L Y P H A S E " }
self:openMenu(Menu:new(nil, m, CONFIRM_X, CONFIRM_Y(e), true, e, HIGHLIGHT), {})
end
function Battle:openAttackMenu(sp)
local attributes = MenuItem:new('Attributes', {},
'View ' .. sp.name .. "'s attributes", {
['elements'] = sp:buildAttributeBox(self:getTmpAttributes(sp)),
['w'] = HBOX_WIDTH
})
local wait = MenuItem:new('Skip', {},
'Skip ' .. sp.name .. "'s attack", nil, function(c)
self:push(self:stackBubble())
self:selectTarget()
end
)
local skills_menu = sp:mkSkillsMenu(true, false)
local weapon = skills_menu.children[1]
local spell = skills_menu.children[2]
for i = 1, #weapon.children do self:mkUsable(sp, weapon.children[i]) end
for i = 1, #spell.children do self:mkUsable(sp, spell.children[i]) end
local opts = { attributes, weapon, spell, wait }
local moves = self:getMoves()
self:openMenu(Menu:new(nil, opts, BOX_MARGIN, BOX_MARGIN, false), {
{ BEFORE, TEMP, function(b) b:renderMovement(moves, 1) end }
})
end
function Battle:openAssistMenu(sp)
local attributes = MenuItem:new('Attributes', {},
'View ' .. sp.name .. "'s attributes", {
['elements'] = sp:buildAttributeBox(self:getTmpAttributes(sp)),
['w'] = HBOX_WIDTH
})
local wait = MenuItem:new('Skip', {},
'Skip ' .. sp.name .. "'s assist", nil, function(c)
self:endAction(false)
end
)
local skills_menu = sp:mkSkillsMenu(true, false)
local assist = skills_menu.children[3]
for i = 1, #assist.children do self:mkUsable(sp, assist.children[i]) end
local opts = { attributes, assist, wait }
local c = self:getCursor(3)
local moves = self:getMoves()
self:openMenu(Menu:new(nil, opts, BOX_MARGIN, BOX_MARGIN, false), {
{ BEFORE, TEMP, function(b) b:renderMovement(moves, 1) end }
})
end
function Battle:openAllyMenu(sp)
local attrs = MenuItem:new('Attributes', {},
'View ' .. sp.name .. "'s attributes", {
['elements'] = sp:buildAttributeBox(self:getTmpAttributes(sp)),
['w'] = HBOX_WIDTH
})
local sks = sp:mkSkillsMenu(true, false)
self:openMenu(Menu:new(nil, { attrs, sks }, BOX_MARGIN, BOX_MARGIN, false), {})
end
function Battle:openEnemyMenu(sp)
local attributes = MenuItem:new('Attributes', {},
'View ' .. sp.name .. "'s attributes", {
['elements'] = sp:buildAttributeBox(self:getTmpAttributes(sp)),
['w'] = 390
})
local readying = MenuItem:new('Next Attack', {},
'Prepared skill and target', {
['elements'] = self:buildReadyingBox(sp),
['w'] = HBOX_WIDTH
})
local skills = sp:mkSkillsMenu(false, true)
local opts = { attributes, readying, skills }
self:openMenu(Menu:new(nil, opts, BOX_MARGIN, BOX_MARGIN, false), {
{ BEFORE, TEMP, function(b) b:renderMovementHover() end }
})
end
function Battle:openOptionsMenu()
local save = function(c)
self:closeMenu()
c:quicksave()
end
local endfxn = function(c)
self:closeMenu()
self:openEndTurnMenu()
end
local wincon = MenuItem:new('Objectives', {},
'View victory and defeat conditions', self:buildObjectivesBox()
)
local end_turn = MenuItem:new('End turn', {}, 'End your turn', nil, endfxn)
local settings = self.player:mkSettingsMenu()
table.remove(settings.children)
local restart = MenuItem:new('Restart battle', {},
'Start the battle over', nil, function(c) c:reloadBattle() end,
"Start the battle over from the beginning?"
)
local quit = MenuItem:new('Suspend game', {},
'Suspend battle state and quit', nil, save,
"Create a temporary save and close the game?"
)
local m = { wincon, settings, restart, quit, end_turn }
self:openMenu(Menu:new(nil, m, BOX_MARGIN, BOX_MARGIN, false), {})
end
function Battle:openLevelupMenu(sp, n)
local m = { MenuItem:new('Level up', {}, nil, nil,
function(c)
self.stack[#self.stack]['menu'] = LevelupMenu(sp, n)
end
)}
local l = { " L E V E L U P " }
local menu = Menu:new(nil, m, CONFIRM_X, CONFIRM_Y(l), true, l, GREEN)
self.stack[#self.stack]['menu'] = menu
end
function Battle:endAction(used_assist)
local sp = self:getSprite()
local end_menu = MenuItem:new('Confirm end', {},
"Confirm " .. sp.name .. "'s actions this turn", nil,
function(c) self:playAction() end
)
local views = {}
if used_assist then
views = {{ BEFORE, TEMP, function(b)
b:renderSkillRange({ 0, 1, 0 })
end }}
end
self:openMenu(Menu:new(nil, { end_menu }, BOX_MARGIN, BOX_MARGIN, false), views)
end
function Battle:buildReadyingBox(sp)
-- Start with basic skill box
local stat = self.status[sp:getId()]
local prep = stat['prepare']
local hbox = prep['sk']:mkSkillBox(icon_texture, icons, false, false)
-- Update priority for this sprite (would happen later anyway)
if hasSpecial(stat['effects'], {}, 'enrage') then
prep['prio'] = { FORCED, 'kath' }
end
-- Make prio elements
local send = { prep['prio'][1] }
if send[1] == FORCED then
send[2] = self.status[prep['prio'][2]]['sp']:getName()
end
hbox = concat(hbox, prep['sk']:mkPrioElements(send))
-- Add enemy order
local o = 0
for i = 1, #self.enemy_order do
if self.enemy_order[i] == sp:getId() then o = i end
end
local s = ite(o == 1, 'st', ite(o == 2, 'nd', ite(o == 3, 'rd', 'th')))
table.insert(hbox, mkEle('text', { 'Order: ' .. o .. s }, 415, 13))
return hbox
end
function Battle:buildObjectivesBox()
local joinOr = function(d)
local res = ''
for i = 1, #d do
local s = d[i][1]
res = res .. s
if i < #d then
res = res .. ' or '
else
res = res .. '.'
end
end
return res:sub(1,1):upper() .. res:sub(2)
end
local idt = 30
local wstr, _ = splitByCharLimit(joinOr(self.win), HBOX_CHARS_PER_LINE)
local lstr, _ = splitByCharLimit(joinOr(self.lose), HBOX_CHARS_PER_LINE)
local longest = max(mapf(string.len, concat(wstr, lstr)))
local w = BOX_MARGIN + idt + longest * CHAR_WIDTH + BOX_MARGIN
return {
['elements'] = {
mkEle('text', {'Victory'},
BOX_MARGIN, BOX_MARGIN, GREEN),
mkEle('text', wstr,
idt + BOX_MARGIN, BOX_MARGIN + LINE_HEIGHT),
mkEle('text', {'Defeat'},
BOX_MARGIN, BOX_MARGIN + LINE_HEIGHT * 3, RED),
mkEle('text', lstr,
idt + BOX_MARGIN, BOX_MARGIN + LINE_HEIGHT * 4)
},
['w'] = w
}
end
function Battle:mkUsable(sp, sk_menu)
local sk = skills[sk_menu.id]
sk_menu.hover_desc = 'Use ' .. sk_menu.name
local ignea_spent = sk.cost
local sk2 = self:getSkill()
if sk2 then ignea_spent = ignea_spent + sk2.cost end
local obsrv = hasSpecial(self.status[sp:getId()]['effects'], {}, 'observe')
if sp.ignea < ignea_spent or (sk.id == 'observe' and obsrv) then
sk_menu.setPen = function(c) love.graphics.setColor(unpack(DISABLE)) end
else
sk_menu.setPen = function(c) love.graphics.setColor(unpack(WHITE)) end
sk_menu.action = function(c)
local c = self:getCursor()
local cx = c[1]
local cy = c[2]
if sk.aim['type'] ~= SELF_CAST then
if self.grid[cy][cx + 1] then
cx = cx + 1
elseif self.grid[cy][cx - 1] then
cx = cx - 1
elseif self.grid[cy + 1][cx] then
cy = cy + 1
else
cy = cy - 1
end
end
local cclr = ite(sk.type == ASSIST, { 0.4, 1, 0.4, 1 },
{ 1, 0.4, 0.4, 1 })
local new_c = { cx, cy, c[3], cclr }
local zclr = ite(sk.type == ASSIST, { 0, 1, 0 }, { 1, 0, 0 })
self:push({
['stage'] = STAGE_TARGET,
['cursor'] = new_c,
['sp'] = sp,
['sk'] = sk,
['views'] = {
{ BEFORE, TEMP, function(b)
b:renderSkillRange(zclr)
end }
}
})
end
end
end
function Battle:selectAlly(sp)
local c = self:getCursor()
local new_c = { c[1], c[2], c[3], { 0.4, 0.4, 1, 1 } }
local moves = self:validMoves(sp, c[2], c[1])
self:push({
['stage'] = STAGE_MOVE,
['sp'] = sp,
['cursor'] = new_c,
['moves'] = moves,
['views'] = {
{ BEFORE, TEMP, function(b) b:renderMovement(moves, 1) end },
{ AFTER, PERSIST, function(b)
local y, x = b:findSprite(sp:getId())
b:renderSpriteImage(new_c[1], new_c[2], x, y, sp)
end }
}
})
self:checkTriggers(SELECT)
end
function Battle:getSpent(i, j)
local moves = self:getMoves()
if moves then
for k = 1, #moves do
if moves[k]['to'][1] == i
and moves[k]['to'][2] == j
then
return moves[k]['spend']
end
end
end
return 0
end
function Battle:getMovement(sp, i, j)
local attrs = self:getTmpAttributes(sp)
local spent = self:getSpent(i, j)
return math.floor(attrs['agility'] / 5) - spent
end
function Battle:validMoves(sp, i, j)
-- Get sprite's base movement points
local move = self:getMovement(sp, i, j)
-- Run djikstra's algorithm on grid
local dist, _ = sp:djikstra(self.grid, { i, j }, nil, move)
-- Reachable nodes have distance < move
local moves = {}
for y = math.max(i - move, 1), math.min(i + move, #self.grid) do
for x = math.max(j - move, 1), math.min(j + move, #self.grid[y]) do
if dist[y][x] <= move then
table.insert(moves,
{ ['to'] = { y, x }, ['spend'] = dist[y][x] }
)
end
end
end
return moves
end
function Battle:selectTarget()
local sp = self:getSprite()
local c = self:getCursor(2)
local moves = self:validMoves(sp, c[2], c[1])
if #moves <= 1 then
self:push(self:stackBubble(c, moves))
self:openAssistMenu(sp)
else
local nc = { c[1], c[2], c[3], { 0.6, 0.4, 0.8, 1 } }
self:push({
['stage'] = STAGE_MOVE,
['sp'] = sp,
['cursor'] = nc,
['moves'] = moves,
['views'] = {
{ BEFORE, TEMP, function(b)
b:renderMovement(moves, 1)
end },
{ AFTER, PERSIST, function(b)
b:renderSpriteImage(nc[1], nc[2], c[1], c[2], sp)
end }
}
})
end
end
function Battle:useAttack(sp, attack, attack_dir, c_attack, dryrun)
local i, j = self:findSprite(sp:getId())
local sp_a = ite(self:isAlly(sp), self.grid[i][j].assists, {})
local t = self:skillRange(attack, attack_dir, c_attack)
local ts = {}
local ts_a = {}
for k = 1, #t do
local space = self.grid[t[k][1]][t[k][2]]
local target = space.occupied
if target then
table.insert(ts, target)
table.insert(ts_a, ite(self:isAlly(target), space.assists, {}))
end
end
return attack:use(sp, sp_a, ts, ts_a, self.status, self.grid, dryrun)
end
function Battle:kill(sp)
local i, j = self:findSprite(sp:getId())
self.grid[i][j].occupied = nil
self.status[sp:getId()]['alive'] = false
end
function Battle:pathToWalk(sp, path, next_sk)
local move_seq = {}
if #path == 0 then
table.insert(move_seq, function(d)
self.skill_in_use = next_sk
d()
end)
end
for i = 1, #path do
table.insert(move_seq, function(d)
self.skill_in_use = next_sk
return sp:walkToBehaviorGeneric(function()
self:moveSprite(sp, path[i][2], path[i][1])
d()
end, self.origin_x + path[i][2], self.origin_y + path[i][1], true)
end)
end
return move_seq
end
function Battle:playAction()
-- Skills used
local sp = self:getSprite()
local attack = self.stack[4]['sk']
local assist = self.stack[7]['sk']
-- Cursor locations
local c_sp = self.stack[1]['cursor']
local c_move1 = self.stack[2]['cursor']
local c_attack = self.stack[4]['cursor']
local c_move2 = self.stack[5]['cursor']
local c_assist = self.stack[7]['cursor']
-- Derive directions from cursor locations
local computeDir = function(c1, c2)
if c1[1] - c2[1] == 1 then return RIGHT
elseif c1[1] - c2[1] == -1 then return LEFT
elseif c1[2] - c2[2] == 1 then return DOWN
else return UP
end
end
local attack_dir = UP
if attack and attack.aim['type'] == DIRECTIONAL then
attack_dir = computeDir(c_attack, c_move1)
end
local assist_dir = UP
if assist and assist.aim['type'] == DIRECTIONAL then
assist_dir = computeDir(c_assist, c_move2)
end
-- Shorthand
local ox = self.origin_x
local oy = self.origin_y
local sp_y, sp_x = self:findSprite(sp:getId())
-- Make behavior sequence
-- Move 1
local move1_path = sp:djikstra(self.grid,
{ sp_y, sp_x },
{ c_move1[2], c_move1[1] }
)
local seq = self:pathToWalk(sp, move1_path, attack)
-- Attack
table.insert(seq, function(d)
if not attack then
return sp:waitBehaviorGeneric(d, 'combat', 0.2)
end
return sp:skillBehaviorGeneric(function()
local hurt, dead, lvlups = self:useAttack(sp,
attack, attack_dir, c_attack
)
sp.ignea = sp.ignea - attack.cost
for k, v in pairs(lvlups) do
if lvlups[k] > 0 then self.levelup_queue[k] = v end
end
for i = 1, #hurt do
if hurt[i] ~= sp then
hurt[i]:behaviorSequence({ function(d)
hurt[i]:fireAnimation('hurt', function()
hurt[i]:changeBehavior('battle')
end)
return pass
end }, pass)
end
end
for i = 1, #dead do
dead[i]:behaviorSequence({ function(d)
dead[i]:fireAnimation('death', function()
local did = dead[i]:getId()
local stat = self.status[did]
if stat['team'] == ENEMY then
self.chapter:getMap():dropSprite(did)
end
end)
return pass
end }, pass)
self:kill(dead[i])
end
d()
end, attack, attack_dir, c_attack[1] + ox, c_attack[2] + oy)
end)
-- Move 2
local move2_path = sp:djikstra(self.grid,
{ c_move1[2], c_move1[1] },
{ c_move2[2], c_move2[1] }
)
seq = concat(seq, self:pathToWalk(sp, move2_path, assist))
-- Assist
table.insert(seq, function(d)
if not assist then
return sp:waitBehaviorGeneric(d, 'combat', 0.2)
end
return sp:skillBehaviorGeneric(function()
sp.ignea = sp.ignea - assist.cost
local t = self:skillRange(assist, assist_dir, c_assist)
for i = 1, #t do
-- Get the buffs this assist will confer, based on
-- the sprite's attributes
local buffs = assist:use(self:getTmpAttributes(sp))
-- Put the buffs on the grid
local g = self.grid[t[i][1]][t[i][2]]
for j = 1, #buffs do
table.insert(g.assists, buffs[j])
end
g.n_assists = g.n_assists + 1
end
d()
end, assist, assist_dir, c_assist[1] + ox, c_assist[2] + oy)
end)
-- Register behavior sequence with sprite
sp:behaviorSequence(seq, function()
self.action_in_progress = nil
self.skill_in_use = nil
sp:changeBehavior('battle')
end
)
-- Process other battle results of actions
c_sp[1] = c_move2[1]
c_sp[2] = c_move2[2]
if attack then self.status[sp:getId()]['attack'] = attack end
if assist then self.status[sp:getId()]['assist'] = assist end
-- Force player to watch the action
self.action_in_progress = sp
self:push({
['stage'] = STAGE_WATCH,
['sp'] = sp,
['views'] = {}
})
end
function Battle:rangeToTiles(sk, dir, c)
local scale = #sk.range
local toGrid = function(x, k, flip)
local g = c[k] - (scale + 1) / 2 + x
if flip then
g = c[k] + (scale + 1) / 2 - x
end
return g
end
local tiles = {}
for i = 1, scale do
for j = 1, scale do
if sk.range[i][j] then
local gi = toGrid(i, 2, false)
local gj = toGrid(j, 1, false)
if dir == DOWN then
gi = toGrid(i, 2, true)
gj = toGrid(j, 1, true)
elseif dir == LEFT then
gi = toGrid(j, 2, true)
gj = toGrid(i, 1, false)
elseif dir == RIGHT then
gi = toGrid(j, 2, false)
gj = toGrid(i, 1, true)
end
table.insert(tiles, { gi, gj })
end
end
end
return tiles
end
function Battle:skillRange(sk, dir, c)
return filter(
function(t) return self.grid[t[1]] and self.grid[t[1]][t[2]] end,
self:rangeToTiles(sk, dir, c)
)
end
function Battle:newCursorMove(up, down, left, right)
local c = self:getCursor()
local i = c[2]
local j = c[1]
local x_move = 0
local y_move = 0
if left and not right and j - 1 >= 1 and self.grid[i][j - 1] then
x_move = -1
end
if right and not left and j + 1 <= self.grid_w and self.grid[i][j + 1] then
x_move = 1
end
if up and not down and i - 1 >= 1 and self.grid[i - 1][j] then
y_move = -1
end
if down and not up and i + 1 <= self.grid_h and self.grid[i + 1][j] then
y_move = 1
end
return x_move, y_move
end
function Battle:newCursorPosition(up, down, left, right)
local x_move, y_move = self:newCursorMove(up, down, left, right)
local c = self:getCursor()
local i = c[2]
local j = c[1]
return j + x_move, i + y_move
end
function Battle:update(keys, dt)
-- Advance render timers
local c = self:getCursor()
self.pulse_timer = self.pulse_timer + dt
while self.pulse_timer > PULSE do
self.pulse_timer = self.pulse_timer - PULSE
self.pulse = not self.pulse
if c then c[3] = self.pulse end
end
self.shading = self.shading + self.shade_dir * dt / 3
if self.shading > 0.4 then
self.shading = 0.4
self.shade_dir = -1
elseif self.shading < 0.2 then
self.shading = 0.2
self.shade_dir = 1
end
-- Control determined by stage
local s = self:getStage()
local m = self:getMenu()
local d = keys['d']
local f = keys['f']
local up = keys['up']
local down = keys['down']
local left = keys['left']
local right = keys['right']
if m then
-- Menu navigation
local m = self:getMenu()
local done = false
if d then
done = m:back()
elseif f then
m:forward(self.chapter)
elseif up ~= down then
m:hover(ite(up, UP, DOWN))
end
if done then self:closeMenu() end
end
if s == STAGE_FREE then
-- Free map navagation
local x, y = self:newCursorPosition(up, down, left, right)
self:moveCursor(x, y)
if f then
local space = self.grid[y][x]
local o = space.occupied
if not o then
self:openOptionsMenu()
elseif self:isAlly(o) then
if not self.status[o:getId()]['acted'] then
self:selectAlly(o)
else
self:openAllyMenu(o)
end
else
self:openEnemyMenu(o)
end
end
elseif s == STAGE_MOVE then
local sp = self:getSprite()
local c = self:getCursor(3)
if d then
self:pop()
else
-- Move a sprite to a new location
local x, y = self:newCursorPosition(up, down, left, right)
self:moveCursor(x, y)
local space = self.grid[y][x].occupied
if f and not (space and space ~= sp) then
local moves = self:getMoves()
for i = 1, #moves do
if moves[i]['to'][1] == y and moves[i]['to'][2] == x then
if not c then
self:openAttackMenu(sp)
else
self:openAssistMenu(sp)
end
break
end
end
end
end
elseif s == STAGE_TARGET then
local sp = self:getSprite()
local sk = self:getSkill()
if d then
self:pop()
else
local c = self:getCursor(2)
local x_move, y_move = self:newCursorMove(up, down, left, right)
if sk.aim['type'] == DIRECTIONAL then
if x_move == 1 then
self:moveCursor(c[1] + 1, c[2])
elseif x_move == -1 then
self:moveCursor(c[1] - 1, c[2])
elseif y_move == 1 then
self:moveCursor(c[1], c[2] + 1)
elseif y_move == -1 then
self:moveCursor(c[1], c[2] - 1)
end
elseif sk.aim['type'] == FREE then
local scale = sk.aim['scale']
local c_cur = self:getCursor()
if abs(c_cur[1] + x_move - c[1]) +
abs(c_cur[2] + y_move - c[2]) <= scale then
self:moveCursor(c_cur[1] + x_move, c_cur[2] + y_move)
end
end
if f then
if sk.type ~= ASSIST then
local c_cur = self:getCursor()
local t = self.grid[c_cur[2]][c_cur[1]].occupied
local can_obsv = t and self:isAlly(t) and t.id ~= 'elaine'
if not (sk.id == 'observe' and not can_obsv) then
self:selectTarget()
end
else
self:endAction(true)
end
end
end
elseif s == STAGE_WATCH then
-- Clean up after actions are performed
if not self.action_in_progress then
if next(self.levelup_queue) then
self:push({
['stage'] = STAGE_LEVELUP,
['views'] = {}
})
return
end
-- Check triggers
if self:checkTriggers(END_ACTION) then
return
end
-- Say this sprite acted and reset stack
local sp = self:getSprite()
self.status[sp:getId()]['acted'] = true
self.stack = { self.stack[1] }
-- Check win and loss
if self:checkWinLose() then return end
-- If there are enemies that need to go next, have them go.
if self.enemy_action then
self:planNextEnemyAction()
if self.enemy_action then
self.stack = self.enemy_action
self:playAction()
end
end
-- If all allies have acted, switch to enemy phase
local ally_phase_over = true
for i = 1, #self.participants do
local sp = self.participants[i]
if self:isAlly(sp) and not self.status[sp:getId()]['acted'] then
ally_phase_over = false
end
end
if ally_phase_over and self.chapter.turn_autoend then
self:openEndTurnMenu()
else
-- If all enemies have acted, it's time for the next turn
local all_enemies_acted = true
local enemies_alive = false
for i = 1, #self.participants do
local sp = self.participants[i]
local sp_stat = self.status[sp:getId()]
if not self:isAlly(sp) and sp_stat['alive'] then
enemies_alive = true
if not sp_stat['acted'] then
all_enemies_acted = false
end
end
end
if all_enemies_acted and enemies_alive then
self:beginTurn()
end
end
end
elseif s == STAGE_LEVELUP then
-- Check levelups
if not m then
local k, v = next(self.levelup_queue)
if k then
self:openLevelupMenu(self.status[k]['sp'], v)
self.levelup_queue[k] = self.levelup_queue[k] - 1
if self.levelup_queue[k] == 0 then
self.levelup_queue[k] = nil
end
else
self:pop()
end
end
end
end
function Battle:updateBattleCam()
local focus = self.action_in_progress
local c = self:getCursor()
if focus then
local x, y = focus:getPosition()
local w, h = focus:getDimensions()
self.battle_cam_x = x + math.ceil(w / 2) - VIRTUAL_WIDTH / 2
self.battle_cam_y = y + math.ceil(h / 2) - VIRTUAL_HEIGHT / 2
elseif c then
self.battle_cam_x = (c[1] + self.origin_x)
* TILE_WIDTH - VIRTUAL_WIDTH / 2 - TILE_WIDTH / 2
self.battle_cam_y = (c[2] + self.origin_y)
* TILE_HEIGHT - VIRTUAL_HEIGHT / 2 - TILE_HEIGHT / 2
end
end
-- Prepare this sprite's next skill
function Battle:prepareSkill(e, used)
-- TODO: skill selection strategy
local sk = e.skills[1]
self.status[e:getId()]['prepare'] = { ['sk'] = sk, ['prio'] = { sk.prio } }
end
function Battle:planTarget(e, plan)
-- Get targeting priority
local stat = self.status[e:getId()]
local prio = stat['prepare']['prio'][1]
-- If the target is forced, it doesn't matter where they are. Target them.
if prio == FORCED then
local sp = self.status[stat['prepare']['prio'][2]]['sp']
for i = 1, #plan['options'] do
if sp == plan['options'][i]['sp'] then
return plan['options'][i], nil
end
end
return nil, nil
end
-- The set of choices is all ally sprites, unless some sprites are within
-- striking distance, in which case only reachable sprites are considered
local tgts = filter(function(o) return o['reachable'] end, plan['options'])
if not next(tgts) then tgts = plan['options'] end
-- Pick a target from the set of choices based on the sprite's priorities
local tgt = nil -- Who to target
local mv = nil -- Which move to take (optional)
if prio == CLOSEST then
-- Target whichever sprite requires the least movement to attack
local min_dist = math.huge
for i = 1, #tgts do
for j = 1, #tgts[i]['moves'] do
local d = tgts[i]['moves'][j]['attack']['dist']
if d <= min_dist then
min_dist = d
tgt, mv = tgts[i], tgts[i]['moves'][j]
end
end
end
elseif prio == KILL then
-- Target whichever sprite will suffer the highest percent of their
-- current health in damage (with 100% meaning they'd die)
local max_percent = 0
for i = 1, #tgts do
for j = 1, #tgts[i]['moves'] do
local a = tgts[i]['moves'][j]['attack']
local d = self:useAttack(e, plan['sk'], a['dir'], a['c'], true)
for k = 1, #d do
if d[k]['percent'] >= max_percent then
max_percent = d[k]['percent']
tgt, mv = tgts[i], tgts[i]['moves'][j]
end
end
end
end
elseif prio == DAMAGE then
-- Target whichever sprite and move will achieve the maximum damage
-- across all affected sprites
local max_dmg = 0
for i = 1, #tgts do
for j = 1, #tgts[i]['moves'] do
local a = tgts[i]['moves'][j]['attack']
local d = self:useAttack(e, plan['sk'], a['dir'], a['c'], true)
local sum = 0
for k = 1, #d do sum = sum + d[k]['flat'] end
if sum >= max_dmg then
max_dmg = sum
tgt, mv = tgts[i], tgts[i]['moves'][j]
end
end
end
elseif prio == STRONGEST then
-- Target whichever sprite poses the biggest threat
local max_attrs = 0
for i = 1, #tgts do
local attrs = self:getTmpAttributes(tgts[i]['sp'])
local sum = 0
for _,v in pairs(attrs) do sum = sum + v end
if sum >= max_attrs then
max_attrs = sum
tgt, mv = tgts[i], nil
end
end
end
return tgt, mv
end
function Battle:planAction(e, plan, other_plans)
-- Select a target and move based on skill prio and enemies in range
local target, move = self:planTarget(e, plan)
-- Get skill being used and suggested move
local move = nil
if not move then
-- If no suggested move, compute the nearest one
-- TODO: pick a non-interfering tile based on other_plans
local min_dist = math.huge
for i = 1, #target['moves'] do
local d = target['moves'][i]['attack']['dist']
if d < min_dist then
min_dist = d
move = target['moves'][i]
end
end
end
-- Return move data, and attack data if target is reachable
if target['reachable'] then
return move['move_c'], move['attack']['c'], target['sp']
end
return move['move_c'], nil, nil
end
function Battle:getAttackAngles(e, sp, sk)
-- Initializing stuff
local y, x = self:findSprite(sp:getId())
local ey, ex = self:findSprite(e:getId())
local g = self.grid
local attacks = {}
-- Tile transpose function
local addTransposedAttack = function(c, dir)
local ts = self:rangeToTiles(sk, ite(dir, dir, UP), c)
for i = 1, #ts do
local y_dst = ey + (y - ts[i][1])
local x_dst = ex + (x - ts[i][2])
local ac = { c[1] + (x - ts[i][2]), c[2] + (y - ts[i][1]) }
if g[y_dst] and g[y_dst][x_dst] and (not g[y_dst][x_dst].occupied
or g[y_dst][x_dst].occupied == e) and g[ac[2]] and g[ac[2]][ac[1]]
then
table.insert(attacks, {
['c'] = ac,
['from'] = { y_dst, x_dst },
['dir'] = ite(dir, dir, UP)
})
end
end
end
-- Add transposed attacks
if sk.aim['type'] == DIRECTIONAL then
addTransposedAttack({ ex, ey - 1 }, UP)
addTransposedAttack({ ex, ey + 1 }, DOWN)
addTransposedAttack({ ex - 1, ey }, LEFT)
addTransposedAttack({ ex + 1, ey }, RIGHT)
else
addTransposedAttack({ ex, ey })
end
return attacks
end
function Battle:mkInitialPlan(e, sps)
-- Get skill
local sk = self.status[e:getId()]['prepare']['sk']
-- Preemptively get shortest paths for the grid, and enemy movement
local y, x = self:findSprite(e:getId())
local paths_dist, paths_prev = e:djikstra(self.grid, { y, x })
local movement = math.floor(self:getTmpAttributes(e)['agility'] / 5)
-- Compute ALL movement options!
local opts = {}
for i = 1, #sps do
-- Init opts for this sprite
opts[i] = {}
opts[i]['sp'] = sps[i]
opts[i]['moves'] = {}
opts[i]['reachable'] = false
-- Get all attacks that can be made against this sprite using the skill
local attacks = self:getAttackAngles(e, sps[i], sk)
for j = 1, #attacks do
-- Get distance and path to attack location
local attack_from = attacks[j]['from']
local dist = paths_dist[attack_from[1]][attack_from[2]]
if dist ~= math.huge then
-- Sprite should move to path node with dist == movement
local move_c = { attack_from[2], attack_from[1] }
local n = attack_from
for k = 1, dist - movement do
n = paths_prev[n[1]][n[2]]
move_c[1] = n[2]
move_c[2] = n[1]
end
-- Candidate move
local c = {
['move_c'] = move_c,
['attack'] = {
['dist'] = dist,
['c'] = attacks[j]['c'],
['from'] = attacks[j]['from'],
['dir'] = attacks[j]['dir']
}
}
local c_reachable = move_c[1] == attack_from[2]
and move_c[2] == attack_from[1]
-- If candidate move is reachable, we will only accept reachable
-- moves now. Clean out moves (all unreachable) and mark flag.
if c_reachable and not opts[i]['reachable'] then
opts[i]['moves'] = {}
opts[i]['reachable'] = true
end
-- If candidate is reachable, or if we don't care whether or not
-- it's reachable, add it to moves
if c_reachable or not opts[i]['reachable'] then
table.insert(opts[i]['moves'], c)
end
end
end
end
return { ['sk'] = sk, ['options'] = opts }
end
-- Plan the next enemy's action
function Battle:planNextEnemyAction()
-- Clear previous action and stack
self.enemy_action = nil
-- Get enemies who haven't gone yet, in order of action
local enemies = {}
for i = 1, #self.enemy_order do
local stat = self.status[self.enemy_order[i]]
local prev = self:getSprite()
if stat['alive'] and not stat['acted']
and not (prev and prev == stat['sp'])
then
table.insert(enemies, stat['sp'])
end
end
-- If there are no more enemies who can act, do nothing
if not next(enemies) then return end
local e = enemies[1]
-- If the current enemy is stunned, it misses it's action
local stat = self.status[e:getId()]
if hasSpecial(stat['effects'], {}, 'stun') then
local y, x = self:findSprite(e:getId())
local move = { ['cursor'] = { x, y }, ['sp'] = e }
self.enemy_action = { self:stackBase(), move, {}, {}, move, {}, {} }
return
end
-- If the current enemy is enraged, force it to target Kath
if hasSpecial(stat['effects'], {}, 'enrage') then
stat['prepare']['prio'] = { FORCED, 'kath' }
end
-- For every enemy who hasn't acted, make a tentative plan for their action
local sps = filter(function(p) return self:isAlly(p) end, self.participants)
local plans = {}
for i = 1, #enemies do
-- Precompute options for targeting all ally sprites
plans[i] = self:mkInitialPlan(enemies[i], sps)
-- Compute this enemy's preferred action in a vacuum and add it to plan
local pref_move, _, pref_target = self:planAction(enemies[i], plans[i])
plans[i]['pref'] = {
['target'] = pref_target,
['move'] = pref_move
}
end
-- Prepare the first enemy's action, taking into account what the
-- following enemies are planning and would prefer
local m_c, a_c, _ = self:planAction(e, plans[1], plans)
self:prepareSkill(enemies[1], ite(a_c, true, false))
-- Declare next enemy action to be played as an action stack
local move = { ['cursor'] = m_c, ['sp'] = e }
local attack = ite(a_c, { ['cursor'] = a_c, ['sk'] = plans[1]['sk'] }, {})
self.enemy_action = { self:stackBase(), move, {}, attack, move, {}, {} }
end
function Battle:renderCursors()
for i = 1, #self.stack do
local c = self.stack[i]['cursor']
if c then
local x_tile = self.origin_x + c[1]
local y_tile = self.origin_y + c[2]
local x, y = self.chapter:getMap():tileToPixels(x_tile, y_tile)
local shift = ite(c[3], 2, 3)
local fx = x + TILE_WIDTH - shift
local fy = y + TILE_HEIGHT - shift
x = x + shift
y = y + shift
local len = 10 - shift
love.graphics.setColor(unpack(c[4]))
love.graphics.line(x, y, x + len, y)
love.graphics.line(x, y, x, y + len)
love.graphics.line(fx, y, fx - len, y)
love.graphics.line(fx, y, fx, y + len)
love.graphics.line(x, fy, x, fy - len)
love.graphics.line(x, fy, x + len, fy)
love.graphics.line(fx, fy, fx - len, fy)
love.graphics.line(fx, fy, fx, fy - len)
end
end
end
function Battle:renderLens(clr)
love.graphics.setColor(clr[1], clr[2], clr[3], 0.1)
local map = self.chapter.current_map
love.graphics.rectangle('fill', 0, 0,
map.width * TILE_WIDTH, map.height * TILE_HEIGHT
)
end
function Battle:renderSkillInUse(cam_x, cam_y)
local sk = self.skill_in_use
if not sk then return end
local str_w = #sk.name * CHAR_WIDTH
local w = str_w + 55 + BOX_MARGIN
local h = LINE_HEIGHT + BOX_MARGIN
local x = cam_x + VIRTUAL_WIDTH - w - BOX_MARGIN
local y = cam_y + BOX_MARGIN
love.graphics.setColor(0, 0, 0, RECT_ALPHA)
love.graphics.rectangle('fill', x, y, w, h)
love.graphics.setColor(1, 1, 1, 1)
love.graphics.draw(
icon_texture,
icons[sk:treeToIcon()],
x + HALF_MARGIN + str_w + 8, y + HALF_MARGIN,
0, 1, 1, 0, 0
)
love.graphics.draw(
icon_texture,
icons[sk.type],
x + HALF_MARGIN + str_w + 33, y + HALF_MARGIN,
0, 1, 1, 0, 0
)
renderString(sk.name, x + HALF_MARGIN, y + HALF_MARGIN + 3)
end
function Battle:renderSpriteImage(cx, cy, x, y, sp)
if cx ~= x or cy ~= y then
love.graphics.setColor(1, 1, 1, 0.5)
love.graphics.draw(
sp:getSheet(),
sp:getCurrentQuad(),
TILE_WIDTH * (cx + self.origin_x - 1) + sp.w / 2,
TILE_HEIGHT * (cy + self.origin_y - 1) + sp.h / 2,
0,
sp.dir,
1,
sp.w / 2,
sp.h / 2
)
end
end
function Battle:shadeSquare(i, j, clr, alpha)
if self.grid[i] and self.grid[i][j] then
local x = (self.origin_x + j - 1) * TILE_WIDTH
local y = (self.origin_y + i - 1) * TILE_HEIGHT
love.graphics.setColor(clr[1], clr[2], clr[3], self.shading * alpha)
love.graphics.rectangle('fill',
x + 2, y + 2,
TILE_WIDTH - 4, TILE_HEIGHT - 4
)
end
end
function Battle:renderAssistSpaces()
for i = 1, self.grid_h do
for j = 1, self.grid_w do
if self.grid[i][j] then
local n = self.grid[i][j].n_assists
if n > 0 then
local clr = { 0, 1, 0 }
if n == 1 then
clr = { 0.7, 1, 0.7 }
elseif n == 2 then
clr = { 0.4, 1, 0.4 }
elseif n == 3 then
clr = { 0.2, 1, 0.2}
end
self:shadeSquare(i, j, clr, 0.75)
end
end
end
end
end
function Battle:getTargetDirection()
-- Get skill and cursor info
local c = self:getCursor()
local sk = self:getSkill()
-- Get direction to point the skill
local dir = UP
if sk.aim['type'] == DIRECTIONAL then
local o = self:getCursor(2)
dir = ite(c[1] > o[1], RIGHT,
ite(c[1] < o[1], LEFT,
ite(c[2] > o[2], DOWN, UP)))
end
return dir
end
function Battle:outlineTile(tx, ty, edges, clr)
local x1 = (self.origin_x + tx - 1) * TILE_WIDTH
local y1 = (self.origin_y + ty - 1) * TILE_HEIGHT
local x2 = x1 + TILE_WIDTH
local y2 = y1 + TILE_HEIGHT
local sh = 0.3
local newclr = { clr[1] - sh, clr[2] - sh, clr[3] - sh, 1 }
if self.grid[ty] and self.grid[ty][tx] then
love.graphics.setColor(unpack(newclr))
if not next(edges) then
if not self.grid[ty + 1] or not self.grid[ty + 1][tx] then
love.graphics.line(x1, y2, x2, y2)
end
if not self.grid[ty - 1] or not self.grid[ty - 1][tx] then
love.graphics.line(x1, y1, x2, y1)
end
if not self.grid[ty][tx + 1] then
love.graphics.line(x2, y1, x2, y2)
end
if not self.grid[ty][tx - 1] then
love.graphics.line(x1, y1, x1, y2)
end
else
for i = 1, #edges do
local e = edges[i]
if e == UP then love.graphics.line(x1, y1, x2, y1)
elseif e == DOWN then love.graphics.line(x1, y2, x2, y2)
elseif e == LEFT then love.graphics.line(x1, y1, x1, y2)
else love.graphics.line(x2, y1, x2, y2)
end
end
end
end
end
function Battle:renderSkillRange(clr)
-- What skill?
local c = self:getCursor()
local sk = self:getSkill()
-- Get direction to point the skill
local dir = self:getTargetDirection()
-- Render red squares given by the skill range
local tiles = self:skillRange(sk, dir, c)
for i = 1, #tiles do
self:shadeSquare(tiles[i][1], tiles[i][2], clr, 1)
end
-- For bounded free aim skills, render the boundary
if sk.aim['type'] == FREE and sk.aim['scale'] < 100 then
local t = self:getCursor(2)
for x = 0, sk.aim['scale'] do
for y = 0, sk.aim['scale'] - x do
local l = t[1] - x
local r = t[1] + x
local d = t[2] + y
local u = t[2] - y
if x + y == sk.aim['scale'] then
self:outlineTile(r, d, { DOWN, RIGHT }, clr)
self:outlineTile(l, d, { DOWN, LEFT }, clr)
self:outlineTile(r, u, { UP, RIGHT }, clr)
self:outlineTile(l, u, { UP, LEFT }, clr)
end
self:outlineTile(r, d, {}, clr)
self:outlineTile(l, d, {}, clr)
self:outlineTile(r, u, {}, clr)
self:outlineTile(l, u, {}, clr)
end
end
end
end
function Battle:renderMovement(moves, full)
for i = 1, #moves do
self:shadeSquare(moves[i]['to'][1], moves[i]['to'][2], {0, 0, 1}, full)
end
end
function Battle:renderMovementHover()
local c = self:getCursor()
local sp = self.grid[c[2]][c[1]].occupied
if sp and not self.status[sp:getId()]['acted'] then
local i, j = self:findSprite(sp:getId())
self:renderMovement(self:validMoves(sp, i, j), 0.5)
end
end
function Battle:renderViews(depth)
for i = 1, #self.stack do
local views = self.stack[i]['views']
for j = 1, #views do
if views[j][1] == depth
and (views[j][2] == PERSIST or i == #self.stack) then
views[j][3](self)
end
end
end
end
function Battle:renderHealthbar(sp)
local x, y = sp:getPosition()
local ratio = sp.health / sp.attributes['endurance']
y = y + sp.h + ite(self.pulse, 0, -1) - 1
love.graphics.setColor(0, 0, 0, 1)
love.graphics.rectangle('fill', x + 3, y, sp.w - 6, 3)
love.graphics.setColor(0.4, 0, 0.2, 1)
love.graphics.rectangle('fill', x + 3, y, (sp.w - 6) * ratio, 3)
love.graphics.setColor(0.3, 0.3, 0.3, 1)
love.graphics.rectangle('line', x + 3, y, sp.w - 6, 3)
end
function Battle:renderStatus(sp)
-- Get statuses
local x, y = sp:getPosition()
local statuses = self.status[sp:getId()]['effects']
-- Collect what icons need to be rendered
local buffed = false
local debuffed = false
local augmented = false
local impaired = false
for i = 1, #statuses do
local b = statuses[i].buff
if b.attr == 'special' then
if b.type == BUFF then augmented = true end
if b.type == DEBUFF then impaired = true end
else
if b.type == BUFF then buffed = true end
if b.type == DEBUFF then debuffed = true end
end
end
-- Render icons
local y_off = ite(self.pulse, 0, 1)
if buffed then
love.graphics.draw(icon_texture, status_icons[1],
x + TILE_WIDTH - 8, y + y_off, 0, 1, 1, 0, 0
)
end
if debuffed then
love.graphics.draw(icon_texture, status_icons[2],
x + TILE_WIDTH - 16, y + y_off, 0, 1, 1, 0, 0
)
end
if augmented then
love.graphics.draw(icon_texture, status_icons[4],
x + 8, y + y_off, 0, 1, 1, 0, 0
)
end
if impaired then
love.graphics.draw(icon_texture, status_icons[3],
x, y + y_off, 0, 1, 1, 0, 0
)
end
end
function Battle:mkOuterHoverBox(w)
-- Check for an ally sprite or empty space
local c = self:getCursor()
local g = self.grid[c[2]][c[1]]
local sp = g.occupied
if ((not sp) or self:isAlly(sp)) and g.n_assists > 0 then
-- Make an element for each assist
local eles = { mkEle('text', 'Assists', HALF_MARGIN, HALF_MARGIN) }
for i = 1, #g.assists do
local str = g.assists[i]:toStr()
table.insert(eles, mkEle('text', str,
w - #str * CHAR_WIDTH - HALF_MARGIN,
HALF_MARGIN + LINE_HEIGHT * i
))
end
return eles, LINE_HEIGHT * (#eles) + BOX_MARGIN
end
return {}, 0
end
function Battle:mkTileHoverBox(tx, ty)
local sp = self.grid[ty][tx].occupied
if not sp then return nil, nil, nil, nil end
local w = BOX_MARGIN + CHAR_WIDTH * MAX_WORD
-- Box contains sprite's name and status
local name_str = sp.name
local hp_str = sp.health .. "/" .. sp.attributes['endurance']
local ign_str = sp.ignea .. "/" .. sp.attributes['focus']
-- Compute box width from longest status
local statuses = self.status[sp:getId()]['effects']
local longest_status = 0
for i = 1, #statuses do
-- Space (in characters) between two strings in hover box
local buf = 3
-- Length of duration string
local d = statuses[i].duration
local dlen = ite(d == math.huge, 0, ite(d < 2, 6, ite(d < 10, 7, 8)))
-- Length of buff string
local b = statuses[i].buff
local blen = #b:toStr()
-- Combine them all to get character size
longest_status = math.max(longest_status, dlen + blen + buf)
end
w = math.max(w, longest_status * CHAR_WIDTH + BOX_MARGIN)
-- Add sprite basic info
local sp_eles = {
mkEle('text', sp.name, HALF_MARGIN, HALF_MARGIN),
mkEle('text', hp_str, w - HALF_MARGIN - #hp_str * CHAR_WIDTH,
HALF_MARGIN + LINE_HEIGHT + 3),
mkEle('text', ign_str, w - HALF_MARGIN - #ign_str * CHAR_WIDTH,
HALF_MARGIN + LINE_HEIGHT * 2 + 9),
mkEle('image', icons[str_to_icon['endurance']],
HALF_MARGIN, HALF_MARGIN + LINE_HEIGHT, icon_texture),
mkEle('image', icons[str_to_icon['focus']],
HALF_MARGIN, HALF_MARGIN + LINE_HEIGHT * 2 + 6, icon_texture)
}
-- Add sprite statuses
local stat_eles = {}
local y = HALF_MARGIN + LINE_HEIGHT * 3 + BOX_MARGIN
for i = 1, #statuses do
local cy = y + LINE_HEIGHT * (i - 1)
local b = statuses[i].buff
local d = statuses[i].duration
local dur = ''
if d ~= math.huge then
dur = d .. ite(d > 1, ' turns', ' turn')
end
table.insert(stat_eles, mkEle('text', dur,
w - #dur * CHAR_WIDTH - HALF_MARGIN, cy
))
local str = b:toStr()
table.insert(stat_eles, mkEle('text', str, HALF_MARGIN, cy))
end
-- Concat info with statuses
local h = BOX_MARGIN + HALF_MARGIN + LINE_HEIGHT
* (#sp_eles - 2 + #stat_eles / 2)
if next(statuses) ~= nil then
h = h + HALF_MARGIN
end
local clr = ite(self:isAlly(sp), { 0, 0.1, 0.1 }, { 0.1, 0, 0 })
return concat(sp_eles, stat_eles), w, h, clr
end
function Battle:mkInnerHoverBox()
local c = self:getCursor()
local hbox, bw, bh, bclr = self:mkTileHoverBox(c[1], c[2])
if not hbox then
local w = BOX_MARGIN + CHAR_WIDTH * MAX_WORD
local h = BOX_MARGIN + LINE_HEIGHT
local clr = { 0, 0, 0 }
return { mkEle('text', 'Empty', HALF_MARGIN, HALF_MARGIN) }, w, h, clr
end
return hbox, bw, bh, bclr
end
function Battle:renderTargetHoverBoxes(cam_x, cam_y)
-- Get skill range
local dir = self:getTargetDirection()
local sk = self:getSkill()
local c = self:getCursor()
local sp = self:getSprite()
local tiles = self:skillRange(sk, dir, c)
-- Iterate over tiles to see which ones need to render boxes
local max_y = cam_y + VIRTUAL_HEIGHT
- BOX_MARGIN * 2 - FONT_SIZE - LINE_HEIGHT
local cur_y = cam_y + BOX_MARGIN
for i = 1, #tiles do
-- Switch tile of current sprite with prospective tile it's moving to
local t = self.grid[tiles[i][1]][tiles[i][2]].occupied
local move_c = self:getCursor(2)
if t == sp then
tiles[i][1] = move_c[2]
tiles[i][2] = move_c[1]
elseif tiles[i][1] == move_c[2] and tiles[i][2] == move_c[1] then
local y, x = self:findSprite(sp:getId())
tiles[i][1] = y
tiles[i][2] = x
end
t = self.grid[tiles[i][1]][tiles[i][2]].occupied
-- If there's a sprite on the tile and the skill affects that sprite,
-- render the sprite's hover box
if t and sk:hits(sp, t, self.status) then
local box, w, h, clr = self:mkTileHoverBox(tiles[i][2], tiles[i][1])
-- Only render if there's room for the whole box on screen
if cur_y + h <= max_y then
local cur_x = cam_x + VIRTUAL_WIDTH - BOX_MARGIN - w
table.insert(clr, RECT_ALPHA)
love.graphics.setColor(unpack(clr))
love.graphics.rectangle('fill', cur_x, cur_y, w, h)
self:renderBoxElements(box, cur_x, cur_y)
cur_y = cur_y + h + BOX_MARGIN
else
local cur_x = cam_x + VIRTUAL_WIDTH
- BOX_MARGIN - CHAR_WIDTH * 3
renderString("...", cur_x, cur_y)
break
end
end
end
end
function Battle:renderBoxElements(box, base_x, base_y)
for i = 1, #box do
local e = box[i]
if e['type'] == 'text' then
local clr = ite(e['color'], e['color'], WHITE)
love.graphics.setColor(unpack(clr))
renderString(e['data'],
base_x + e['x'], base_y + e['y'], true, e['auto_color']
)
else
love.graphics.setColor(unpack(WHITE))
love.graphics.draw(
e['texture'],
e['data'],
base_x + e['x'],
base_y + e['y'],
0, 1, 1, 0, 0
)
end
end
end
function Battle:renderHoverBoxes(x, y, ibox, w, ih, obox, oh, clr)
-- Base coordinates for both boxes
local outer_x = x + VIRTUAL_WIDTH - BOX_MARGIN - w
local inner_x = outer_x
local inner_y = y + BOX_MARGIN
local outer_y = inner_y + ih
-- If there are assists
if next(obox) ~= nil then
-- Draw outer box
love.graphics.setColor(0.05, 0.15, 0.05, RECT_ALPHA)
love.graphics.rectangle('fill', outer_x, outer_y, w, oh)
-- Draw outer box elements
self:renderBoxElements(obox, outer_x, outer_y)
end
-- Draw inner box
table.insert(clr, RECT_ALPHA)
love.graphics.setColor(unpack(clr))
love.graphics.rectangle('fill', inner_x, inner_y, w, ih)
-- Draw inner box elements
self:renderBoxElements(ibox, inner_x, inner_y)
end
function Battle:renderBattleText(cam_x, cam_y)
-- Variables needed off stack
local s = self:getStage()
local c = self:getCursor()
local sp = self.grid[c[2]][c[1]].occupied
-- Compute hover string
local hover_str = 'View battle options'
if s == STAGE_MOVE then
hover_str = 'Select a space to move to'
elseif s == STAGE_TARGET then
hover_str = 'Select a target for ' .. self:getSkill().name
elseif sp then
if self:isAlly(sp) and not self.status[sp:getId()]['acted'] then
hover_str = "Move " .. sp.name
else
hover_str = "Examine " .. sp.name
end
end
-- Render hover string in the lower right
local x = cam_x + VIRTUAL_WIDTH - BOX_MARGIN - #hover_str * CHAR_WIDTH
local y = cam_y + VIRTUAL_HEIGHT - BOX_MARGIN - FONT_SIZE
renderString(hover_str, x, y)
end
function Battle:renderBexp(x, y)
local bexp = self.render_bexp
local saved = self.turnlimit - self.turn
local msg1 = saved .. " turns saved * 15 exp"
local msg2 = bexp .. " bonus exp"
local computeX = function(s)
return x + VIRTUAL_WIDTH - BOX_MARGIN - #s * CHAR_WIDTH
end
local base_y = y + BOX_MARGIN
love.graphics.setColor(unpack(DISABLE))
renderString(msg1, computeX(msg1), base_y, true)
love.graphics.setColor(unpack(HIGHLIGHT))
renderString(msg2, computeX(msg2), base_y + LINE_HEIGHT, true)
end
function Battle:renderGrid()
-- Draw grid at fixed position
love.graphics.setColor(0.5, 0.5, 0.5, 1)
for i = 1, self.grid_h do
for j = 1, self.grid_w do
if self.grid[i][j] then
love.graphics.rectangle('line',
(self.origin_x + j - 1) * TILE_WIDTH,
(self.origin_y + i - 1) * TILE_HEIGHT,
TILE_WIDTH,
TILE_HEIGHT
)
end
end
end
self:renderAssistSpaces()
-- Render views over grid if we aren't watching a scene
local s = self:getStage()
if s ~= STAGE_WATCH and s ~= STAGE_LEVELUP then
-- Render active views below the cursor, in stack order
self:renderViews(BEFORE)
-- Draw cursors always
self:renderCursors()
-- Render active views above the cursor, in stack order
self:renderViews(AFTER)
end
end
function Battle:renderOverlay(cam_x, cam_y)
-- Render healthbars below each sprite, and status markers above
for i = 1, #self.participants do
if self.chapter:getMap():getSprite(self.participants[i]:getId()) then
self:renderHealthbar(self.participants[i])
self:renderStatus(self.participants[i])
end
end
-- No overlay if stack has no cursors
local s = self:getStage()
if self:getCursor() then
-- Dont render any other overlays while watching an action
if s ~= STAGE_WATCH and s ~= STAGE_LEVELUP then
-- Make and render hover boxes
if s == STAGE_TARGET then
self:renderTargetHoverBoxes(cam_x, cam_y)
else
local ibox, w, ih, clr = self:mkInnerHoverBox()
local obox, oh = self:mkOuterHoverBox(w)
self:renderHoverBoxes(cam_x, cam_y, ibox, w, ih, obox, oh, clr)
end
-- Render battle text if not in a menu
if s ~= STAGE_MENU then
self:renderBattleText(cam_x, cam_y)
end
elseif s == STAGE_WATCH then
self:renderSkillInUse(cam_x, cam_y)
end
end
-- Render menu if there is one
local m = self:getMenu()
if m then
m:render(cam_x, cam_y, self.chapter)
if self.render_bexp then self:renderBexp(cam_x, cam_y) end
end
-- Render what turn it is in the lower right
if s and s ~= STAGE_WATCH and s ~= STAGE_LEVELUP then
local turn_str = 'Turn ' .. self.turn
renderString(turn_str,
cam_x + VIRTUAL_WIDTH - BOX_MARGIN - #turn_str * CHAR_WIDTH,
cam_y + VIRTUAL_HEIGHT - BOX_MARGIN - FONT_SIZE - LINE_HEIGHT
)
end
end
wincons = {
['rout'] = { "defeat all enemies",
function(b)
for _,v in pairs(b.status) do
if v['team'] == ENEMY and v['alive'] then
return false
end
end
return true
end
},
['escape'] = { "escape the battlefield",
function(b)
return false
end
}
}
losscons = {
['death'] = { "any ally dies",
function(b)
for k,v in pairs(b.status) do
if v['team'] == ALLY and not v['alive'] then
return k
end
end
return false
end
},
['defend'] = { "any enemy breaches the defended area",
function(b)
return false
end
}
}
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local core = require("apisix.core")
local plugin_name = "request-validation"
local ngx = ngx
local io = io
local req_read_body = ngx.req.read_body
local schema = {
type = "object",
anyOf = {
{
title = "Body schema",
properties = {
body_schema = {type = "object"}
},
required = {"body_schema"}
},
{
title = "Header schema",
properties = {
header_schema = {type = "object"}
},
required = {"header_schema"}
}
}
}
local _M = {
version = 0.1,
priority = 2800,
type = 'validation',
name = plugin_name,
schema = schema,
}
function _M.check_schema(conf)
local ok, err = core.schema.check(schema, conf)
if not ok then
return false, err
end
if conf.body_schema then
ok, err = core.schema.valid(conf.body_schema)
if not ok then
return false, err
end
end
if conf.header_schema then
ok, err = core.schema.valid(conf.header_schema)
if not ok then
return false, err
end
end
return true, nil
end
function _M.rewrite(conf)
local headers = ngx.req.get_headers()
if conf.header_schema then
local ok, err = core.schema.check(conf.header_schema, headers)
if not ok then
core.log.error("req schema validation failed", err)
return 400, err
end
end
if conf.body_schema then
req_read_body()
local req_body, error
local body = ngx.req.get_body_data()
if not body then
local filename = ngx.req.get_body_file()
if not filename then
return 500
end
local fd = io.open(filename, 'rb')
if not fd then
return 500
end
body = fd:read('*a')
end
if headers["content-type"] == "application/x-www-form-urlencoded" then
req_body, error = ngx.decode_args(body)
else -- JSON as default
req_body, error = core.json.decode(body)
end
if not req_body then
core.log.error('failed to decode the req body', error)
return 400, error
end
local ok, err = core.schema.check(conf.body_schema, req_body)
if not ok then
core.log.error("req schema validation failed", err)
return 400, err
end
end
end
return _M
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.