content
stringlengths 5
1.05M
|
|---|
slot0 = class("WSMapItem", import("...BaseEntity"))
slot0.Fields = {
cell = "table",
transform = "userdata",
rtArtifacts = "userdata",
theme = "table"
}
slot0.GetName = function (slot0, slot1)
return "item_" .. slot0 .. "_" .. slot1
end
slot0.Setup = function (slot0, slot1, slot2)
slot0.cell = slot1
slot0.theme = slot2
end
slot0.Dispose = function (slot0)
slot0:Unload()
slot0:Clear()
end
slot0.Load = function (slot0)
PoolMgr.GetInstance():GetPrefab("world/object/world_cell_item", "world_cell_item", false, function (slot0)
slot0.transform = slot0.transform
slot0:Init()
end)
end
slot0.Unload = function (slot0)
if slot0.transform then
PoolMgr.GetInstance():ReturnPrefab("world/object/world_cell_item", "world_cell_item", slot0.transform.gameObject)
end
slot0.transform = nil
end
slot0.Init = function (slot0)
slot0.transform.name = slot0.GetName(slot0.cell.row, slot0.cell.column)
slot0.transform.anchoredPosition = slot0.theme:GetLinePosition(slot0.cell.row, slot0.cell.column)
slot0.transform.sizeDelta = slot0.theme.cellSize
slot0.rtArtifacts = slot0.transform.Find(slot2, "artifacts")
slot0.rtArtifacts.localEulerAngles = Vector3(-slot0.theme.angle, 0, 0)
end
return slot0
|
local tbTable = GameMain:GetMod("MagicHelper")
local tbMagic = tbTable:GetMagic("TTMG_11_3")
function tbMagic:EnableCheck(npc)
return true
end
function tbMagic:TargetCheck(key, t)
if t.ThingType == CS.XiaWorld.g_emThingType.Npc then
return true
else
return false
end
end
function tbMagic:MagicEnter(IDs, IsThing)
self.targetId = IDs[0]
end
function tbMagic:MagicStep(dt, duration)
self:SetProgress(duration / self.magic.Param1)
if duration >= self.magic.Param1 then
return 1
end
return 0
end
function tbMagic:MagicLeave(success)
if success then
local target = ThingMgr:FindThingByID(self.targetId)
local v1 = target:GetProperty("NpcFight_SpellPowerAddP")
local v2 = self.bind:GetProperty("NpcFight_SpellPowerAddP")
if target then
if v2 <= 100000000 then
self.bind.PropertyMgr:ModifierProperty("NpcFight_SpellPowerAddP", v1 * 0.5)
target.PropertyMgr:ModifierProperty("NpcFight_SpellPowerAddP", -v1)
else
self.bind:AddMsg("[NAME] has reached the limit, cannot absorb.")
end
end
end
end
|
client, service = nil, nil
return function()
local function findMean(tab: {number}): number
local total = 0
for _, val in pairs(tab) do
total += val
end
return total / #tab
end
local function checkConsistency(tab: {number}, uncertainty: number?): boolean
local consistent = 0
for _, val in pairs(tab) do
if math.abs(math.abs(val) - math.abs(findMean(tab))) < (uncertainty or 1) then
consistent += 1
if consistent >= #tab / 2 then
return true
end
end
end
return false
end
local Mouse: Mouse = service.Players.LocalPlayer:GetMouse()
local clickHistory = {}
local isActive = true
local function activateClickCheck()
if not isActive then return end
table.insert(clickHistory, os.clock())
task.delay(2, function()
clickHistory = {}
end)
if #clickHistory > 4 then
if checkConsistency(clickHistory, 0.1) then
isActive = false
client.Anti.Detected("kick", "Autoclicking detected")
end
end
end
Mouse.Button1Down:Connect(activateClickCheck)
Mouse.Button2Down:Connect(activateClickCheck)
end
|
local Piece = require 'tetris.components.piece'
local Ruleset = require 'tetris.rulesets.arika_ace2'
local ARS = Ruleset:extend()
ARS.name = "ACE-ARS"
ARS.hash = "ArikaACE"
ARS.colourscheme = {
I = "C",
L = "O",
J = "B",
S = "G",
Z = "R",
O = "Y",
T = "M",
}
ARS.softdrop_lock = false
ARS.harddrop_lock = true
return ARS
|
local lang = {
repair = "Riparazione {1}.",
reward = "Ricompensa: {1} $.",
bankdriver = "Dato soldi {1}.",
reward = "Ricompensa: {1} $.",
delivery = {
title = "Compra gli oggetti dai mercati (vedi mappa) e poi portameli!",
item = "- {2} {1}"
},
drugseller = {
title = "Trova l'Informatore illegale, raccogli i semi dalla posizione che dà, portali al Drug Lab (vedi mappa) e poi portameli!",
item = "- {2} {1}"
},
hacker = {
title = "Hack carte di credito dai terminali nascosti quindi vendono carte di credito per me!",
item = "- {2} {1}"
},
fisherman = {
title = "Vai a pescare (vedi mappa) e poi portami quei pesci!",
item = "- {2} {1}"
},
weapons_smuggler = {
title = "Prendi le armi da dietro a Paleto Ammunation e poi nascondi le armi!",
item = "- {2} {1}"
},
medical = {
title = "Prendi l'erba medica (vedi la mappa) e consegna l'erba medica a me!",
item = "- {2} {1}"
},
-- santa = {
-- title = "Consegna i regali di Natale",
-- item = "- {2} {1}"
-- },
pilot = {
title = "Raccogli il carico (vedi mappa) e poi consegnami il carico!",
item = "- {2} {1}"
},
police = {
title = "Ottieni rapporti di polizia (vedi mappa) e consegnali ai responsabili bancari per mostrare la presenza della polizia.",
item = "- {2} {1}"
},
ems = {
title = "Ottieni rapporti medici (vedi mappa) e consegnali all'ospedale.",
item = "- {2} {1}"
},
trash = {
title = "Raccogli la spazzatura (vedi mappa) e portameli.",
item = "- {2} {1}"
},
forger = {
title = "Ottieni le carte di credito dagli hacker, convertili in ID falso (vedi mappa) e portameli!",
item = "- {2} {1}"
}
}
return lang
|
--
-- Copyright (c) 2016-present, 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.
--
local ffi = require 'ffi'
local pl = require 'pl.import_into'()
local utils = require 'utils.utils'
local common = require 'common.common'
-- local image = require 'image'
-- local symbols, s = utils.ffi_include(paths.concat(common.lib_path, "board/board.h"))
local script_path = common.script_path()
local symbols, s = utils.ffi_include(paths.concat(script_path, "board.h"))
-- print(s)
local board = {}
board.pass = tonumber(symbols.M_PASS)
board.resign = tonumber(symbols.M_RESIGN)
board.chinese_rule = tonumber(symbols.RULE_CHINESE)
board.japanese_rule = tonumber(symbols.RULE_JAPANESE)
local C = ffi.load(paths.concat(script_path, "../libs/libboard.so"))
board.C = C
board.s = s
board.symbols = symbols
board.script_path = script_path
local ids = ffi.new("GroupId4")
local debugging = false
local function dprintf(...)
if debugging then
print(string.format(...))
end
end
function board.print_info()
-- Print relevant information
print("----Go board for LUA version 1.0----")
local b = board.new()
print(string.format("sizeof(Board) = %d", ffi.sizeof(b)))
print(string.format("sizeof(Group) = %d", ffi.sizeof("Group")))
print(string.format("sizeof(Info) = %d", ffi.sizeof("Info")))
print(string.format("sizeof(GroupId4) = %d", ffi.sizeof("GroupId4")))
print(string.format("sizeof(Board._infos) = %d", ffi.sizeof(b._infos)))
print(string.format("sizeof(Board._groups) = %d", ffi.sizeof(b._groups)))
print("-----------------------------------")
end
function board.get_board_size()
return common.board_size
end
function board.new(n)
dprintf("Start board.new()")
if n == nil then
return ffi.new("Board")
elseif type(n) == 'number' then
return ffi.new("Board[?]", n)
end
end
function board.copyfrom(b)
local bb = ffi.new("Board")
ffi.copy(bb, b, ffi.sizeof("Board"))
return bb
end
function board.copyfrom2(bb, b)
ffi.copy(bb, b, ffi.sizeof("Board"))
end
function board.clear(b)
dprintf("Start board.clear()")
C.ClearBoard(b)
end
function board.show(b, choice)
dprintf("Start board.show()")
if choice == "last_move" then
C.ShowBoard(b, tonumber(symbols.SHOW_LAST_MOVE))
elseif choice == "all" then
C.ShowBoard(b, tonumber(symbols.SHOW_ALL))
else
C.ShowBoard(b, tonumber(symbols.SHOW_NONE))
end
print " "
end
function board.show_fancy(b, choice)
dprintf("Start board.show()")
if choice == "last_move" then
C.ShowBoardFancy(b, tonumber(symbols.SHOW_LAST_MOVE))
elseif choice == "all" then
C.ShowBoardFancy(b, tonumber(symbols.SHOW_ALL))
elseif choice == 'all_rows_cols' then
C.ShowBoardFancy(b, tonumber(symbols.SHOW_ALL_ROWS_COLS))
else
C.ShowBoardFancy(b, tonumber(symbols.SHOW_NONE))
end
print " "
end
function board.dump(b)
dprintf("Start board.dump()")
C.DumpBoard(b)
C.VerifyBoard(b)
end
-- This one returns Coords.
function board.get_all_stones(b)
local black_moves = ffi.new("AllMoves")
local white_moves = ffi.new("AllMoves")
C.GetAllStones(b, black_moves, white_moves)
local res = { }
for i = 0, black_moves.num_moves - 1 do
table.insert(res, { black_moves.moves[i], common.black })
end
for i = 0, white_moves.num_moves - 1 do
table.insert(res, { white_moves.moves[i], common.white })
end
return res
end
function board.get_black_white_stones(b)
local black_moves = ffi.new("AllMoves")
local white_moves = ffi.new("AllMoves")
C.GetAllStones(b, black_moves, white_moves)
local blacks = { }
for i = 0, black_moves.num_moves - 1 do
table.insert(blacks, black_moves.moves[i])
end
local whites = { }
for i = 0, white_moves.num_moves - 1 do
table.insert(whites, white_moves.moves[i])
end
return blacks, whites
end
function board.is_true_eye(b, x, y, player)
return C.IsTrueEyeXY(b, x - 1, y - 1, player) == common.TRUE
end
function board.is_self_atari(b, x, y, player)
local num_stone = ffi.new("int[1]")
if C.TryPlay(b, x - 1, y - 1, player, ids) == common.TRUE then
local is_self_atari = C.IsSelfAtariXY(b, ids, x - 1, y - 1, player, num_stone) == common.TRUE
return is_self_atari, tonumber(num_stone[0])
end
end
function board.is_move_giving_simple_ko(b, x, y, player)
if C.TryPlay(b, x - 1, y - 1, player, ids) == common.TRUE then
return C.IsMoveGivingSimpleKo(b, ids, player) == common.TRUE
end
end
function board.tryplay(b, x, y, player)
dprintf("Start board.tryplay()")
-- print(x, y)
return C.TryPlay(b, x - 1, y - 1, player, ids) == common.TRUE
end
function board.play(b, x, y, player)
dprintf("Start board.play()")
-- print(x, y)
if C.TryPlay(b, x - 1, y - 1, player, ids) == common.TRUE then
C.Play(b, ids)
return true
else
return false
end
end
function board.place_handicap(b, x, y, player)
return C.PlaceHandicap(b, x - 1, y - 1, player) == common.TRUE
end
function board.play2(b, m)
dprintf("Start board.play()")
-- print(x, y)
if C.TryPlay2(b, m, ids) == common.TRUE then
C.Play(b, ids)
return true
else
return false
end
end
function board.opponent(player)
return 3 - player
end
function board.get_ply(b)
return b._ply
end
function board.is_game_end(b)
return C.IsGameEnd(b) == common.TRUE
end
-- Feature extractors ---
function board.get_liberties_map(b, player)
dprintf("Start board.get_liberties_map()")
local liberties = torch.FloatTensor(19, 19)
C.GetLibertyMap(b, player, liberties:data())
return liberties
end
function board.get_stones(b, player)
local stones = torch.FloatTensor(19, 19)
C.GetStones(b, player, stones:data())
return stones
end
function board.get_simple_ko(b, player)
local simple_ko = torch.FloatTensor(19, 19)
C.GetSimpleKo(b, player, simple_ko:data())
return simple_ko
end
function board.get_history(b, player)
local history = torch.FloatTensor(19, 19)
C.GetHistory(b, player, history:data())
return history
end
function board.get_distance_map(b, player)
local distance_map = torch.FloatTensor(19, 19)
C.GetDistanceMap(b, player, distance_map:data())
return distance_map
end
function board.get_stones_bbox(b)
local r = ffi.new("Region")
C.GetBoardBBox(b, r)
return r
end
function board.expand_region(r, margin)
r.left = math.max(r.left - margin, 0)
r.top = math.max(r.top - margin, 0)
r.right = math.min(r.right + margin, common.board_size)
r.bottom = math.min(r.bottom + margin, common.board_size)
end
function board.get_attacker(b, r)
-- From the bounding box, we could get the likely attacker.
return C.GuessLDAttacker(b, r)
end
-- Check whether the play at (x, y) by player is the victim of ladder.
function board.check_ladder(b, x, y, player)
dprintf("Start board.is_ladder()")
-- print(x, y)
if C.TryPlay(b, x - 1, y - 1, player, ids) == common.TRUE then
return C.CheckLadder(b, ids, player)
end
end
-- Scoring
function board.get_fast_score(b, rule)
rule = rule or board.chinese_rule
return C.GetFastScore(b, rule)
end
--[[
function board.show_map(m)
local name = m:type()
return image.hflip(m:float()):transpose(1, 2):type(name)
end
]]
function board.show_compact_map(m)
assert(m:size(1) == 19)
assert(m:size(2) == 19)
local s = ""
for i = 1, 19 do
s = s .. " "
for j = 1, 19 do
local v = m[j][20 - i]
if v == common.black then
s = s .. 'x '
else
s = s .. 'o '
end
end
s = s .. "\n"
end
print(s)
end
return board
|
local Prop = {}
Prop.Name = "Strip Mall 1"
Prop.Cat = "Stores"
Prop.Price = 250
Prop.Doors = {
Vector( -8668.000000, -3826.000000, -13892.000000 ),
Vector( -8668.000000, -3918.000000, -13892.000000 ),
}
GM.Property:Register( Prop )
|
local M = {}
function M.script(path)
local dir_name = path:parent():head():gsub("/", "")
local file_name = path:head()
return table.concat({
[[tabedit | terminal]],
[[setlocal bufhidden=wipe]],
([[call chansend(&channel, "cat %s\n")]]):format(path),
([[file virtes://%s_%s]]):format(dir_name, file_name),
}, "\n")
end
function M.write(path, strs)
vim.validate({ strs = { strs, "table" } })
if #strs > 0 then
table.insert(strs, ([[" source %s " ex command to show screenshots]]):format(path) .. "\n")
end
local f = io.open(path, "w")
f:write(table.concat(strs, "\n"))
f:close()
end
return M
|
-----------------------------------
--
-- Zone: Valley_of_Sorrows (128)
--
-----------------------------------
local ID = require("scripts/zones/Valley_of_Sorrows/IDs");
require("scripts/globals/conquest");
require("scripts/globals/settings");
require("scripts/globals/zone");
-----------------------------------
function onInitialize(zone)
if (LandKingSystem_NQ ~= 1) then
UpdateNMSpawnPoint(ID.mob.ADAMANTOISE);
GetMobByID(ID.mob.ADAMANTOISE):setRespawnTime(900 + math.random(0, 6) * 1800)
end
end;
function onConquestUpdate(zone, updatetype)
tpz.conq.onConquestUpdate(zone, updatetype)
end;
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(45.25,-2.115,-140.562,0);
end
return cs;
end;
function onRegionEnter(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LocalLinker = ReplicatedStorage:FindFirstChild("LocalLinker")
-- Run outside of Hexolus environment
if not LocalLinker then
require(script.Parent)()
end
|
local Camera = require "libs.camera3d"
local cpml = require "libs.cpml"
local lume = require "libs.lume"
local geometry = require "geometry"
local PostProcess = require "postprocess"
local map = require "map_loader"
local Terrain = require "terrain"
local Gameplay = {}
--[[
1) terrain needs bounding boxes for each triangle (or just do a check on each tile's triangles)
2) implement gravity so tank falls and collides with terrain
3) use tank bounding box to grab terrain positions from each of the tank's corners
4) create new tile and adjust orientation to fix normals
5) adjust tank to this normal
--]]
function Gameplay:enter(from, name, resources, terrain, connection, chat, controls)
lurker.postswap = function(f)
if connection then
connection:disconnect()
end
Gamestate.switch(require "states.loading", name, resources, connection.host, connection.port, controls, chat)
end
self.wireframe = false
self.gamma = 2.2
self.post = PostProcess()
self.resources = resources
self.players = {}
self.map = map.new()
self.manager = require "client_manager"
self.manager:init(connection, name, self.map, self.players)
self.map:add_object(Terrain(
"Terrain_01",
terrain,
"assets/shaders/shader.glsl",
self.gamma,
"assets/textures/Grass0130_2_S.dds"
))
self.chat = chat or false
self.controls = controls
self.camera = Camera(cpml.vec3(0,0,0))
self.flat = love.graphics.newShader("assets/shaders/flat.glsl")
self.sniper = false
self.original_x, self.original_y = false, false
self.prevx, self.prevy = love.mouse.getPosition()
self.original_direction = 0
self.focused = love.window.hasFocus()
self.grabbed = true
self.first_press = true
self.camera:grab(self.focused)
self.map:set_camera(self.camera)
self.ui = require "ui.gameplay"
self.ui:init(self.manager)
Signal.register("pressed-a", function(...) self:pressed_a(...) end)
Signal.register("pressed-y", function(...) self:pressed_y(...) end)
Signal.register("pressed-back", function(...) self:pressed_back(...) end)
Signal.register("pressed-start", function(...) self:pressed_start(...) end)
Signal.register("moved-axisleft", function(...) self:moved_axisleft(...) end)
Signal.register("moved-axisright", function(...) self:moved_axisright(...) end)
Signal.register("moved-triggerright", function(...) self:moved_triggerright(...) end)
self.pew_pew = {}
self.cooldown = 0
self.released = true
end
function Gameplay:update(dt)
collectgarbage("step")
self.manager:update(dt)
if self.chat then
self.chat:update(dt)
end
self.cooldown = self.cooldown - dt
if self.cooldown < 0 then
self.cooldown = 0
end
local w, h = love.graphics.getDimensions()
local mx, my = love.mouse.getPosition()
local dx, dy = self.prevx - mx, self.prevy - my
self.prevx, self.prevy = mx, my
if not console.visible and self.focused then
if self.grabbed then
dx, dy = love.mouse.getPosition()
dx, dy = w/2 - dx, h/2 - dy
if self.first_press then
self.original_x, self.original_y = love.mouse.getPosition()
end
love.mouse.setPosition(w/2, h/2)
else
if self.original_x and self.original_y then
love.mouse.setPosition(self.original_x, self.original_y)
self.original_x, self.original_y = false, false
end
end
if self.grabbed then
if not self.first_press then
self.camera:rotateXY(dx, dy)
else
self.first_press = false
end
end
end
local move, turn = self:check_controls()
local mouse = cpml.vec2(-dx, -dy):normalize()
Signal.emit("moved-axisleft", nil, turn, move)
Signal.emit("moved-axisright", nil, mouse.x, mouse.y)
for _, player in pairs(self.players) do
self.map.draw_data[player.id] = {}
self.map.draw_data[player.id].Turret = cpml.mat4():rotate(player.turret, { 0, 0, 1 })
local terrain = self.map:get("Terrain_01")
local tiles = {}
tiles.start = terrain:get_tile(player.position)
tiles.top_left = terrain:get_tile(cpml.vec3(player.position.x-2, player.position.y+2, player.position.z))
tiles.top_right = terrain:get_tile(cpml.vec3(player.position.x+2, player.position.y+2, player.position.z))
tiles.bottom_right = terrain:get_tile(cpml.vec3(player.position.x+2, player.position.y-2, player.position.z))
tiles.bottom_left = terrain:get_tile(cpml.vec3(player.position.x-2, player.position.y-2, player.position.z))
-- I TOLD YOU ABOUT STAIRS BRO
-- STOP REMOVING THIS MOTHERFUCKING CHECK YOU ASSHOLE
-- @u@
if tiles.start and tiles.top_left and tiles.top_right and tiles.bottom_left and tiles.bottom_right then
local function ananas(tile, player_offset)
local hit = cpml.intersect.ray_triangle
local triangles = {
{ tile.positions[1], tile.positions[2], tile.positions[3] },
{ tile.positions[1], tile.positions[3], tile.positions[4] }
}
local ray = {
point = tile.center + cpml.vec3(player_offset.x, player_offset.y, 10),
direction = cpml.vec3(0, 0, -1)
}
-- only one of these will probably hit so we'll just go with that
local p = hit(ray, triangles[1]) or hit(ray, triangles[2])
if p then p = p + tile.offset end
return p
end
local offset = player.position - (tiles.start.center + tiles.start.offset)
local new_tile = {}
new_tile.vertices = {}
table.insert(new_tile.vertices, ananas(tiles.bottom_left, offset))
table.insert(new_tile.vertices, ananas(tiles.bottom_right, offset))
table.insert(new_tile.vertices, ananas(tiles.top_right, offset))
table.insert(new_tile.vertices, ananas(tiles.top_left, offset))
new_tile.center = cpml.mesh.average(new_tile.vertices)
local normals = {}
table.insert(normals, cpml.mesh.compute_normal(new_tile.vertices[1], new_tile.vertices[2], new_tile.vertices[3]))
table.insert(normals, cpml.mesh.compute_normal(new_tile.vertices[1], new_tile.vertices[3], new_tile.vertices[4]))
new_tile.normal = -(normals[1] + normals[2]):normalize()
player.up = new_tile.normal
player.orientation.x = -math.atan2(new_tile.normal.y, math.sqrt((new_tile.normal.x * new_tile.normal.x) + (new_tile.normal.z * new_tile.normal.z)))
player.orientation.y = math.atan2(new_tile.normal.x, new_tile.normal.z)
player.direction = player.orientation:orientation_to_direction()
player.position.z = new_tile.center.z
if self.debug_geometry then
local triangles = {
new_tile.vertices[1], new_tile.vertices[2], new_tile.vertices[3],
new_tile.vertices[1], new_tile.vertices[3], new_tile.vertices[4]
}
table.insert(self.debug_squares, (geometry.new_triangles(triangles, cpml.vec3(0, 0, 0.01))))
end
end
local model = cpml.mat4()
:rotate(-player.orientation.z, { 0, 0, 1 })
:rotate(-player.orientation.y, { 0, 1, 0 })
:rotate(-player.orientation.x, { 1, 0, 0 })
:scale(player.scale)
for k, buffer in ipairs(player.model.bounds) do
local m = model
local vb = player.model.vertex_buffer[k]
local draw_data = self.map.draw_data[id]
if draw_data[vb.name] then
m = m * draw_data[vb.name]:scale(cpml.vec3(-1, 1, 1))
end
geometry.update_bounding_box(buffer[1], buffer[2], m, vb.bounds.min, vb.bounds.max)
end
end
self.map:update(dt)
self.ui:update(dt)
end
function Gameplay:draw()
local color = cpml.vec3(0.7, 0.9, 1.0)
gl.ClearColor(color.x, color.y, color.z, color:dot(cpml.vec3(0.299, 0.587, 0.114)))
-- Disable blending because we use/abuse the alpha channel for other stuff.
gl.Disable(GL.BLEND)
self.post:bind()
self.map:draw()
love.graphics.setShader(self.flat)
self.camera:send(self.flat)
self.flat:send("u_color", { 1, 0, 1, 1 })
self.flat:send("u_model", cpml.mat4():to_vec4s())
gl.Enable(GL.DEPTH_TEST)
for _, pew in ipairs(self.pew_pew) do
self.flat:send("u_color", { 0, 1, 1, 1 })
love.graphics.draw(pew)
end
gl.Disable(GL.DEPTH_TEST)
self.post:unbind()
self.post:draw()
gl.Enable(GL.BLEND)
self.ui:set_nametags(self.map:get_nametags())
self.ui:draw()
end
function Gameplay:keypressed(key, isrepeat)
local move, turn = self:check_controls(key, isrepeat)
Signal.emit("moved-axisleft", nil, turn, move)
if key == "escape" then
Signal.emit("pressed-back")
end
if key == " " then
Signal.emit("pressed-y")
end
if key == "g" then
Signal.emit("pressed-start")
end
end
function Gameplay:keyreleased(key)
local move, turn = self:check_controls(key)
Signal.emit("moved-axisleft", nil, turn, move)
end
function Gameplay:mousepressed(x, y, button)
if button == "l" then
self.first_press = true
Signal.emit("moved-triggerright", nil, 1)
end
end
function Gameplay:mousereleased(x, y, button)
if button == "l" then
self.first_press = true
Signal.emit("moved-triggerright", nil, 0)
end
end
function Gameplay:resize(x, y)
self.post:rebuild()
end
function Gameplay:focus(f)
self.focused = f
if not f then
self.camera:grab(false)
else
if self.grabbed then
self.camera:grab(true)
end
end
end
function Gameplay:leave()
self.wireframe = nil
self.gamma = nil
self.post = nil
self.resources = nil
self.players = nil
self.map = nil
self.controls = nil
self.camera = nil
self.flat = nil
self.sniper = nil
self.original_x = nil
self.original_y = nil
self.prevx = nil
self.prevy = nil
self.grabbed = nil
self.first_press = nil
self.focused = nil
self.ui = nil
self.original_direction = nil
self.manager:destroy()
if self.chat then
self.chat:disconnect()
end
Signal.clear_pattern("pressed%-.*")
Signal.clear_pattern("released%-.*")
Signal.clear_pattern("moved%-.*")
end
function Gameplay:check_controls(key, isrepeat)
local move = 0
local turn = 0
local holding = {
forward = self.controls:check("move_forward", key) and not isrepeat,
back = self.controls:check("move_back", key) and not isrepeat,
left = self.controls:check("turn_left", key) and not isrepeat,
right = self.controls:check("turn_right", key) and not isrepeat,
}
if holding.forward then move = move - 1 end
if holding.back then move = move + 1 end
if holding.left then turn = turn - 1 end
if holding.right then turn = turn + 1 end
return move, turn
end
-- Gamepad Signals
function Gameplay:pressed_a(joystick)
if not self.manager.id then return end
end
function Gameplay:pressed_y(joystick)
if not self.manager.id then return end
if not self.grabbed or not self.focused then
return
end
self.sniper = not self.sniper
if self.sniper then
self.original_direction = self.camera.direction
self.camera.direction = 0
else
self.camera.direction = self.original_direction
self.original_direction = 0
end
end
function Gameplay:pressed_start(joystick)
self.grabbed = not self.grabbed
if not self.grabbed then
self.first_press = true
end
self.camera:grab(self.grabbed)
end
function Gameplay:pressed_back(joystick)
self.camera:grab(false)
Gamestate.switch(require "states.menu")
end
function Gameplay:moved_axisleft(joystick, x, y)
if not self.manager.id then return end
if not self.grabbed or not self.focused then
x = 0
y = 0
end
local dt = love.timer.getDelta()
local turn = -x
local move = -y
local move_speed = 420/6/6
local turn_speed = math.rad(35)
local turret_speed = math.rad(44)
local player = self.players[self.manager.id]
-- Normalize movement velocity so it never exceeds max speed
player.velocity = player.velocity + player.direction * move * move_speed
if player.velocity:len() > move_speed then
player.velocity = player.velocity:normalize() * move_speed
end
-- Check to see if you are going to collide if you move
local new_pos = player.position + player.velocity * dt
-- Don't let players clip half way over the map edge
local terrain = self.map:get("Terrain_01")
local bounds = terrain:get_bounding_box()
bounds.min = bounds.min + cpml.vec2(player.radius, player.radius)
bounds.max = bounds.max - cpml.vec2(player.radius, player.radius)
if new_pos.x < bounds.min.x or new_pos.y < bounds.min.y or
new_pos.x > bounds.max.x or new_pos.y > bounds.max.y then
player.velocity = cpml.vec3(0, 0, 0)
end
-- Don't let players hit each other.
for i, p in pairs(self.players) do
if i ~= self.manager.id then
local c1 = { point=new_pos, radius=player.radius }
local c2 = { point=p.position, radius=p.radius }
-- If collision, stop tank
if cpml.intersect.circle_circle(c1, c2) then
player.velocity = cpml.vec3(0, 0, 0)
break
end
end
end
-- Normalize rotational velocity so it never exceeds max speed
player.rot_velocity = player.rot_velocity + cpml.vec3(0, 0, turn * turn_speed)
if player.rot_velocity:len() > turn_speed then
player.rot_velocity = player.rot_velocity:normalize() * turn_speed
end
end
function Gameplay:moved_axisright(joystick, x, y)
if not self.manager.id then return end
-- kill the input if mouse isn't being captured.
if not self.grabbed or not self.focused then
x = 0
y = 0
end
local turret_speed = math.rad(44)
local stick = cpml.vec2(-x, -y)
local player = self.players[self.manager.id]
if self.sniper then
-- Normalize turret rotational velocity so it never exceeds max speed
player.turret_velocity = player.turret_velocity + stick.x * turret_speed
if player.turret_velocity > turret_speed then
player.turret_velocity = turret_speed
end
if player.turret_velocity < -turret_speed then
player.turret_velocity = -turret_speed
end
player.direction = player.orientation:orientation_to_direction()
local forward = player.direction:rotate(player.turret, player.up)
local offset = cpml.vec3(0, -1.97, 1.37)
-- Camera snaps to turret
self.camera.forced_transforms = true
self.camera:move_to(player.position + offset)
self.camera.direction = forward
self.camera.view = cpml.mat4()
:translate(offset)
:look_at(player.position, player.position + forward, player.up)
else
self.camera.forced_transforms = false
self.camera.pre_offset = cpml.vec3(0, 0, -11)
self.camera:move_to(player.position + cpml.vec3(0, 0, 4))
self.camera:rotateXY(stick.x * 18, stick.y * 9)
-- Get angle between Camera Forward and Turret Forward
local fwd = cpml.vec2(0, 1):rotate(player.orientation.z + player.turret)
local cam = cpml.vec2(1, 0):rotate(math.atan2(self.camera.direction.y, self.camera.direction.x))
local angle = fwd:angle_to(cam)
-- If the turret is not true, adjust it
if math.abs(angle) > 0 then
local function new_angle(direction)
local dt = love.timer.getDelta()
local velocity = direction * turret_speed * dt
return cpml.vec2(0, 1):rotate(player.orientation.z + player.turret + velocity):angle_to(cam)
end
-- Rotate turret into the correct direction
if new_angle(1) < 0 then
player.turret_velocity = turret_speed
elseif new_angle(-1) > 0 then
player.turret_velocity = -turret_speed
else
-- If rotating the turret a full frame will overshoot, set turret to camera position
-- atan2 starts from the left and we need to also add half a rotation. subtract player orientation to convert to local space.
player.turret = math.atan2(self.camera.direction.y, self.camera.direction.x) + (math.pi * 1.5) - player.orientation.z
player.turret_velocity = 0
end
end
end
local direction = cpml.mat4():rotate(player.turret, { 0, 0, 1 }) * cpml.mat4():rotate(player.orientation.z, { 0, 0, 1 })
player.turret_direction = cpml.vec3(direction * { 0, 1, 0, 1 })
end
function Gameplay:moved_triggerright(joystick, axis)
if not self.manager.id then return end
if axis >= 0.8 and self.cooldown == 0 and self.released then
self.released = false
self.cooldown = 5
Signal.emit("send-shoot")
end
if axis <= 0.5 then
self.released = true
end
end
function Gameplay:action_shoot(id)
local player = self.players[id]
local ray = {
point = player.position + player.up * 2.5,
direction = player.direction:rotate(player.turret, player.up),
}
table.insert(self.pew_pew, geometry.new_ray(ray, 50, 0.1))
if #self.pew_pew > 100 then
table.remove(self.pew_pew, 1)
end
end
function Gameplay:action_disconnect(id)
local player = self.players[id]
self.players[id] = nil
local map_id = self.map:get_id(player.id)
if map_id then
self.map:remove_object(map_id)
end
end
return Gameplay
|
-----------------------------------------------------------------------
-- FILE: luaotfload-harf-plug.lua
-- DESCRIPTION: part of luaotfload / HarfBuzz / fontloader plugin
-----------------------------------------------------------------------
do -- block to avoid to many local variables error
local ProvidesLuaModule = {
name = "luaotfload-harf-plug",
version = "3.13", --TAGVERSION
date = "2020-05-01", --TAGDATE
description = "luaotfload submodule / database",
license = "GPL v2.0",
author = "Khaled Hosny, Marcel Krüger",
copyright = "Luaotfload Development Team",
}
if luatexbase and luatexbase.provides_module then
luatexbase.provides_module (ProvidesLuaModule)
end
end
local hb = luaotfload.harfbuzz
local assert = assert
local next = next
local tonumber = tonumber
local type = type
local format = string.format
local open = io.open
local tableinsert = table.insert
local tableremove = table.remove
local ostmpname = os.tmpname
local osremove = os.remove
local direct = node.direct
local tonode = direct.tonode
local todirect = direct.todirect
local traverse = direct.traverse
local insertbefore = direct.insert_before
local insertafter = direct.insert_after
local protectglyph = direct.protect_glyph
local newnode = direct.new
local freenode = direct.free
local copynode = direct.copy
local removenode = direct.remove
local copynodelist = direct.copy_list
local ischar = direct.is_char
local uses_font = direct.uses_font
local getattrs = direct.getattributelist
local setattrs = direct.setattributelist
local getchar = direct.getchar
local setchar = direct.setchar
local getdir = direct.getdir
local setdir = direct.setdir
local getdisc = direct.getdisc
local setdisc = direct.setdisc
local getfont = direct.getfont
local getdata = direct.getdata
local setdata = direct.setdata
local getfont = direct.getfont
local setfont = direct.setfont
local getfield = direct.getfield
local setfield = direct.setfield
local getid = direct.getid
local getkern = direct.getkern
local setkern = direct.setkern
local getnext = direct.getnext
local setnext = direct.setnext
local getoffsets = direct.getoffsets
local setoffsets = direct.setoffsets
local getproperty = direct.getproperty
local setproperty = direct.setproperty
local getprev = direct.getprev
local setprev = direct.setprev
local getsubtype = direct.getsubtype
local setsubtype = direct.setsubtype
local getwidth = direct.getwidth
local setwidth = direct.setwidth
local is_char = direct.is_char
local tail = direct.tail
local properties = direct.get_properties_table()
local imgnode = img.node
local disc_t = node.id("disc")
local glue_t = node.id("glue")
local glyph_t = node.id("glyph")
local dir_t = node.id("dir")
local kern_t = node.id("kern")
local localpar_t = node.id("local_par")
local whatsit_t = node.id("whatsit")
local pdfliteral_t = node.subtype("pdf_literal")
local explicitdisc_t = 1
local fontkern_t = 0
local italiccorr_t = 3
local regulardisc_t = 3
local spaceskip_t = 13
local dir_ltr = hb.Direction.new("ltr")
local dir_rtl = hb.Direction.new("rtl")
local fl_unsafe = hb.Buffer.GLYPH_FLAG_UNSAFE_TO_BREAK
local startactual_p = "luaotfload_startactualtext"
local endactual_p = "luaotfload_endactualtext"
local empty_table = {}
-- "Copy" properties as done by LuaTeX: Make old properties metatable
local function copytable(old)
local new = {}
for k, v in next, old do
if type(v) == "table" then v = copytable(v) end
new[k] = v
end
setmetatable(new, getmetatable(old))
return new
end
-- Set and get properties.
local function setprop(n, prop, value)
local props = properties[n]
if not props then
props = {}
properties[n] = props
end
props[prop] = value
end
local function inherit(t, base, properties)
local n = newnode(t)
setattrs(n, getattrs(base))
if properties then
setproperty(n, setmetatable({}, {__index = properties}))
end
return n
end
-- New kern node of amount `v`, inheriting the properties/attributes of `n`.
local function newkern(v, n)
local kern = inherit(kern_t, n, getproperty(n))
setkern(kern, v)
return kern
end
local function insertkern(head, current, kern, rtl)
if rtl then
head = insertbefore(head, current, kern)
else
head, current = insertafter(head, current, kern)
end
return head, current
end
-- Convert list of integers to UTF-16 hex string used in PDF.
local function to_utf16_hex(uni)
if uni < 0x10000 then
return format("%04X", uni)
else
uni = uni - 0x10000
local hi = 0xD800 + (uni // 0x400)
local lo = 0xDC00 + (uni % 0x400)
return format("%04X%04X", hi, lo)
end
end
local process
local function itemize(head, fontid, direction)
local fontdata = font.getfont(fontid)
local hbdata = fontdata and fontdata.hb
local spec = fontdata and fontdata.specification
local options = spec and spec.features.raw
local runs, codes = {}, {}
local dirstack = {}
local currdir = direction or "TLT"
local lastskip, lastdir = true
local lastrun = {}
for n, id, subtype in direct.traverse(head) do
local code = 0xFFFC -- OBJECT REPLACEMENT CHARACTER
local skip = lastskip
local props = properties[n]
if props and props.zwnj then
code = 0x200C
-- skip = false -- Not sure about this, but lastskip should be a bit faster
elseif id == glyph_t then
if is_char(n) and getfont(n) == fontid then
code = getchar(n)
skip = false
else
skip = true
end
elseif id == glue_t and subtype == spaceskip_t then
code = 0x0020 -- SPACE
elseif id == disc_t then
if uses_font(n, fontid) then
code = 0x00AD -- SOFT HYPHEN
skip = false
else
skip = true
end
elseif id == dir_t then
local dir = getdir(n)
if dir:sub(1, 1) == "+" then
-- Push the current direction to the stack.
tableinsert(dirstack, currdir)
currdir = dir:sub(2)
else
assert(currdir == dir:sub(2))
-- Pop the last direction from the stack.
currdir = tableremove(dirstack)
end
elseif id == localpar_t then
currdir = getdir(n)
end
codes[#codes + 1] = code
if lastdir ~= currdir or lastskip ~= skip then
lastrun.after = n
lastrun = {
start = #codes,
len = 1,
font = fontid,
dir = currdir == "TRT" and dir_rtl or dir_ltr,
skip = skip,
codes = codes,
}
runs[#runs + 1] = lastrun
lastdir, lastskip = currdir, skip
else
lastrun.len = lastrun.len + 1
end
end
return runs
end
-- Check if it is not safe to break before this glyph.
local function unsafetobreak(glyph)
return glyph
and glyph.flags
and glyph.flags & fl_unsafe
end
local shape
-- Make s a sub run, used by discretionary nodes.
local function makesub(run, codes, nodelist)
local subrun = {
start = 1,
len = #codes,
font = run.font,
dir = run.dir,
fordisc = true,
node = nodelist,
codes = codes,
}
local glyphs
if nodelist == 0 then -- FIXME: This shouldn't happen
nodelist = nil
end
nodelist, nodelist, glyphs = shape(nodelist, nodelist, subrun)
return { glyphs = glyphs, run = subrun, head = nodelist }
end
local function printnodes(label, head, after)
after = tonode(after)
for n in node.traverse(tonode(head)) do
if n == after then return end
print(label, n, n.font or '', n.char or '')
local pre, post, rep = getdisc(todirect(n))
if pre then
printnodes(label .. '<', pre)
end
if post then
printnodes(label .. '>', post)
end
if rep then
printnodes(label .. '=', rep)
end
end
end
-- Main shaping function that calls HarfBuzz, and does some post-processing of
-- the output.
function shape(head, firstnode, run)
local node = firstnode
local codes = run.codes
local offset = run.start
local nodeindex = offset
run.start = offset
local len = run.len
local fontid = run.font
local dir = run.dir
local fordisc = run.fordisc
local cluster = offset - 2
local fontdata = font.getfont(fontid)
local hbdata = fontdata.hb
local spec = fontdata.specification
local features = spec.hb_features
local options = spec.features.raw
local hbshared = hbdata.shared
local hbfont = hbshared.font
local lang = spec.language
local script = spec.script
local shapers = options.shaper and { options.shaper } or {}
local buf = hb.Buffer.new()
if buf.set_flags then
buf:set_flags(hbdata.buf_flags)
end
buf:set_direction(dir)
buf:set_script(script)
buf:set_language(lang)
buf:set_cluster_level(buf.CLUSTER_LEVEL_MONOTONE_CHARACTERS)
buf:add_codepoints(codes, offset - 1, len)
local hscale = hbdata.hscale
local vscale = hbdata.vscale
hbfont:set_scale(hscale, vscale)
do
features = table.merged(features) -- We don't want to modify the global features
local current_features = {}
local n = node
for i = offset-1, offset+len-2 do
local props = properties[n] or empty_table
if props then
local local_feat = props.glyph_features or empty_table
if local_feat then
for tag, value in next, current_features do
local loc = local_feat[tag]
loc = loc ~= nil and (tonumber(loc) or (loc and 1 or 0)) or nil
if value.value ~= loc then -- This includes loc == nil
value._end = i
features[#features + 1] = value
current_features[tag] = nil
end
end
for tag, value in next, local_feat do
if not current_features[tag] then
local feat = hb.Feature.new(tag)
feat.value = tonumber(value) or (value and 1 or 0)
feat.start = i
current_features[tag] = feat
end
end
end
end
n = getnext(n)
end
for _, feat in next, current_features do
features[#features + 1] = feat
end
end
if hb.shape_full(hbfont, buf, features, shapers) then
-- The engine wants the glyphs in logical order, but HarfBuzz outputs them
-- in visual order, so we reverse RTL buffers.
if dir:is_backward() then buf:reverse() end
local glyphs = buf:get_glyphs()
local i = 0
while i < #glyphs do
i = i + 1
local glyph = glyphs[i]
-- Calculate the Unicode code points of this glyph. If cluster did not
-- change then this is a glyph inside a complex cluster and will be
-- handled with the start of its cluster.
if cluster ~= glyph.cluster then
cluster = glyph.cluster
for i = nodeindex, cluster do node = getnext(node) end
nodeindex = cluster + 1
local hex = ""
local str = ""
local nextcluster
for j = i+1, #glyphs do
nextcluster = glyphs[j].cluster
if cluster ~= nextcluster then
glyph.nglyphs = j - i
goto NEXTCLUSTERFOUND -- break
end
end -- else -- only executed if the loop reached the end without
-- finding another cluster
nextcluster = offset + len - 1
glyph.nglyphs = #glyphs + 1 - i
::NEXTCLUSTERFOUND:: -- end
glyph.nextcluster = nextcluster
do
local node = node
for j = cluster,nextcluster-1 do
local id = getid(node)
if id == glyph_t or (id == glue_t and getsubtype(node) == spaceskip_t) then
local code = codes[j + 1]
hex = hex..to_utf16_hex(code)
str = str..utf8.char(code)
end
end
glyph.tounicode = hex
glyph.string = str
end
if not fordisc then
local discindex = nil
local disc = node
for j = cluster + 1, nextcluster do
local props = properties[disc]
if (not (props and props.zwnj)) and getid(disc) == disc_t then
discindex = j
break
end
disc = getnext(disc)
end
if discindex then
-- Discretionary found.
local startindex, stopindex = nil, nil
local startglyph, stopglyph = nil, nil
-- Find the previous glyph that is safe to break at.
local startglyph = i
while startglyph > 1
and codes[glyphs[startglyph - 1].cluster + 1] ~= 0x20
and codes[glyphs[startglyph - 1].cluster + 1] ~= 0xFFFC
and unsafetobreak(glyphs[startglyph]) do
startglyph = startglyph - 1
end
-- Get the corresponding character index.
startindex = glyphs[startglyph].cluster + 1
-- Find the next glyph that is safe to break at.
stopglyph = i + 1
local lastcluster = glyphs[i].cluster
while stopglyph <= #glyphs
and codes[glyphs[stopglyph].cluster + 1] ~= 0x20
and codes[glyphs[stopglyph].cluster + 1] ~= 0xFFFC
and (unsafetobreak(glyphs[stopglyph])
or lastcluster == glyphs[stopglyph].cluster) do
lastcluster = glyphs[stopglyph].cluster
stopglyph = stopglyph + 1
end
stopindex = stopglyph <= #glyphs and glyphs[stopglyph].cluster + 1
or offset + len
local startnode, stopnode = node, node
for j=nodeindex - 1, startindex, -1 do
startnode = getprev(startnode)
end
for j=nodeindex + 1, stopindex do
stopnode = getnext(stopnode)
end
glyphs[startglyph] = glyph
glyph.cluster = startindex - 1
glyph.nextcluster = startindex
for j = stopglyph, #glyphs do
local glyph = glyphs[j]
glyph.cluster = glyph.cluster - (stopindex - startindex) + 1
end
len = len - (stopindex - startindex) + 1
table.move(glyphs, stopglyph, #glyphs + stopglyph - startglyph - 1, startglyph + 1)
local subcodes, subindex = {}
do
local node = startnode
while node ~= stopnode do
if node == disc then
subindex = #subcodes
startindex = startindex + 1
node = getnext(node)
elseif getid(node) == disc_t then
local oldnode = node
startnode, node = removenode(startnode, node)
freenode(oldnode)
tableremove(codes, startindex)
else
subcodes[#subcodes + 1] = tableremove(codes, startindex)
node = getnext(node)
end
end
end
local pre, post, rep, lastpre, lastpost, lastrep = getdisc(disc, true)
local precodes, postcodes, repcodes = {}, {}, {}
table.move(subcodes, 1, subindex, 1, repcodes)
for n, id, subtype in traverse(rep) do
repcodes[#repcodes + 1] = getfont(n) == fontid and getchar(n) or 0xFFFC
end
table.move(subcodes, subindex + 1, #subcodes, #repcodes + 1, repcodes)
table.move(subcodes, 1, subindex, 1, precodes)
for n, id, subtype in traverse(pre) do
precodes[#precodes + 1] = getfont(n) == fontid and getchar(n) or 0xFFFC
end
for n, id, subtype in traverse(post) do
postcodes[#postcodes + 1] = getfont(n) == fontid and getchar(n) or 0xFFFC
end
table.move(subcodes, subindex + 1, #subcodes, #postcodes + 1, postcodes)
if startnode ~= disc then
local newpre = copynodelist(startnode, disc)
setnext(tail(newpre), pre)
pre = newpre
end
if post then
setnext(lastpost, copynodelist(getnext(disc), stopnode))
else
post = copynodelist(getnext(disc), stopnode)
end
if startnode ~= disc then
local predisc = getprev(disc)
setnext(predisc, rep)
setprev(rep, predisc)
if firstnode == startnode then
firstnode = disc
end
if startnode == head then
head = disc
else
local before = getprev(startnode)
setnext(before, disc)
setprev(disc, before)
end
setprev(startnode, nil)
rep = startnode
lastrep = lastrep or predisc
end
if getnext(disc) ~= stopnode then
setnext(getprev(stopnode), nil)
setprev(stopnode, disc)
setprev(getnext(disc), lastrep)
setnext(lastrep, getnext(disc))
rep = rep or getnext(disc)
setnext(disc, stopnode)
end
glyph.replace = makesub(run, repcodes, rep)
glyph.pre = makesub(run, precodes, pre)
glyph.post = makesub(run, postcodes, post)
i = startglyph
node = disc
cluster = glyph.cluster
nodeindex = cluster + 1
end
end
end
end
return head, firstnode, glyphs, run.len - len
end
return head, firstnode, {}, 0
end
local function color_to_rgba(color)
local r = color.red / 255
local g = color.green / 255
local b = color.blue / 255
local a = color.alpha / 255
if a ~= 1 then
-- XXX: alpha
return format('%s %s %s rg', r, g, b)
else
return format('%s %s %s rg', r, g, b)
end
end
-- Cache of color glyph PNG data for bookkeeping, only because I couldn’t
-- figure how to make the engine load the image from the binary data directly.
local pngcache = {}
local pngcachefiles = {}
local function cachedpng(data)
local hash = md5.sumhexa(data)
local i = pngcache[hash]
if not i then
local path = ostmpname()
pngcachefiles[#pngcachefiles + 1] = path
open(path, "wb"):write(data):close()
-- local file = open(path, "wb"):write():close()
-- file:write(data)
-- file:close()
i = img.scan{filename = path}
pngcache[hash] = i
end
return i
end
local function get_png_glyph(gid, fontid, characters, haspng)
return gid
end
local push_cmd = { "push" }
local pop_cmd = { "pop" }
local nop_cmd = { "nop" }
--[[
In the following, "text" actually refers to "font" mode and not to "text"
mode. "font" mode is called "text" inside of virtual font commands (don't
ask me why, but the LuaTeX source does make it clear that this is intentional)
and behaves mostly like "page" (especially it does not enter a "BT" "ET"
block) except that it always resets the current position to the origin.
This is necessary to ensure that the q/Q pair does not interfere with TeX's
position tracking.
]]
local save_cmd = { "pdf", "text", "q" }
local restore_cmd = { "pdf", "text", "Q" }
-- Convert glyphs to nodes and collect font characters.
local function tonodes(head, node, run, glyphs)
local nodeindex = run.start
local dir = run.dir
local fontid = run.font
local fontdata = font.getfont(fontid)
local space = fontdata.parameters.space
local characters = fontdata.characters
local hbdata = fontdata.hb
local hfactor = (fontdata.extend or 1000) / 1000
local palette = hbdata.palette
local hbshared = hbdata.shared
local hbface = hbshared.face
local nominals = hbshared.nominals
local hbfont = hbshared.font
local fontglyphs = hbshared.glyphs
local gid_offset = hbshared.gid_offset
local rtl = dir:is_backward()
local lastprops
local scale = hbdata.scale
local haspng = hbshared.haspng
local fonttype = hbshared.fonttype
local nextcluster
for i, glyph in ipairs(glyphs) do
if glyph.cluster + 1 >= nodeindex then -- Reached a new cluster
nextcluster = glyph.nextcluster
assert(nextcluster)
for j = nodeindex, glyph.cluster do
local oldnode = node
head, node = removenode(head, node)
freenode(oldnode)
end
lastprops = getproperty(node)
nodeindex = glyph.cluster + 1
elseif nextcluster + 1 == nodeindex then -- Oops, we went too far
nodeindex = nodeindex - 1
local new = inherit(glyph_t, getprev(node), lastprops)
setfont(new, fontid)
head, node = insertbefore(head, node, new)
end
local gid = glyph.codepoint
local char = nominals[gid] or gid_offset + gid
local id = getid(node)
if glyph.replace then
-- For discretionary the glyph itself is skipped and a discretionary node
-- is output in place of it.
local rep, pre, post = glyph.replace, glyph.pre, glyph.post
setdisc(node, tonodes(pre.head, pre.head, pre.run, pre.glyphs),
tonodes(post.head, post.head, post.run, post.glyphs),
tonodes(rep.head, rep.head, rep.run, rep.glyphs))
node = getnext(node)
nodeindex = nodeindex + 1
elseif glyph.skip then
local oldnode = node
head, node = removenode(head, node)
freenode(oldnode)
nodeindex = nodeindex + 1
else
if lastprops and lastprops.zwnj and nodeindex == glyph.cluster + 1 then
elseif id == glyph_t then
local done
local fontglyph = fontglyphs[gid]
local character = characters[char]
if not character.commands then
if palette then
local layers = fontglyph.layers
if layers == nil then
layers = hbface:ot_color_glyph_get_layers(gid) or false
fontglyph.layers = layers
end
if layers then
local cmds = {} -- Every layer will add 5 cmds
local prev_color = nil
for j = 1, #layers do
local layer = layers[j]
local layerchar = characters[gid_offset + layer.glyph]
if layerchar.height > character.height then
character.height = layerchar.height
end
if layerchar.depth > character.depth then
character.depth = layerchar.depth
end
-- color_index has a special value, 0x10000, that mean use text
-- color, we don’t check for it here explicitly since we will
-- get nil anyway.
local color = palette[layer.color_index]
cmds[5*j - 4] = (color and not prev_color) and save_cmd or nop_cmd
cmds[5*j - 3] = prev_color == color and nop_cmd or (color and {"pdf", "page", color_to_rgba(color)} or restore_cmd)
cmds[5*j - 2] = push_cmd
cmds[5*j - 1] = {"char", layer.glyph + gid_offset}
cmds[5*j] = pop_cmd
fontglyphs[layer.glyph].used = true
prev_color = color
end
cmds[#cmds + 1] = prev_color and restore_cmd
if not character.colored then
local coloredcharacter = {}
for k,v in next, character do
coloredcharacter[k] = v
end
coloredcharacter.commands = cmds
local newcharacters = {[gid + 0x130000] = coloredcharacter}
characters[gid + 0x130000] = coloredcharacter
if char ~= gid + gid_offset then
newcharacters[char] = coloredcharacter
characters[char] = coloredcharacter
character.colored = char
else
character.colored = gid + 0x130000
end
font.addcharacters(fontid, {characters = newcharacters})
end
char = character.colored
character = characters[char]
end
end
if haspng then
local pngglyph = character.pngglyph
if pngglyph == nil then
local pngblob = hbfont:ot_color_glyph_get_png(gid)
if pngblob then
local glyphimg = cachedpng(pngblob:get_data())
local pngchar = { }
for k,v in next, character do
pngchar[k] = v
end
local i = img.copy(glyphimg)
i.width = character.width
i.depth = 0
i.height = character.height + character.depth
pngchar.commands = fonttype and {
{"push"}, {"char", gid_offset + gid}, {"pop"},
{"down", character.depth}, {"image", i}
} or { {"down", character.depth}, {"image", i} }
if not nominals[gid] then
char = 0x130000 + gid
end
characters[char] = pngchar
pngglyph = char
font.addcharacters(fontid, {characters = {[char] = pngchar}})
end
character.pngglyph = pngglyph
end
if pngglyph then
char = pngglyph
elseif not fonttype then
-- Color bitmap font with no glyph outlines (like Noto
-- Color Emoji) but has no bitmap for current glyph (most likely
-- `.notdef` glyph). The engine does not know how to embed such
-- fonts, so we don’t want them to reach the backend as it will cause
-- a fatal error. We use `nullfont` instead. That is a hack, but I
-- think it is good enough for now. We could make the glyph virtual
-- with empty commands suh that LuaTeX ignores it, but we still want
-- a missing glyph warning.
-- We insert the glyph node and move on, no further work is needed.
setfont(node, 0)
done = true
end
end
end
if not done then
local oldcharacter = characters[getchar(node)]
-- If the glyph index of current font character is the same as shaped
-- glyph, keep the node char unchanged. Helps with primitives that
-- take characters as input but actually work on glyphs, like
-- `\rpcode`.
if not oldcharacter then
if gid == 0 then
local new = copynode(node)
head, node = insertafter(head, node, new)
end
setchar(node, char)
elseif character.commands
or character.index ~= oldcharacter.index then
setchar(node, char)
end
local xoffset = (rtl and -glyph.x_offset or glyph.x_offset) * scale
local yoffset = glyph.y_offset * scale
setoffsets(node, xoffset, yoffset)
fontglyph.used = fonttype and true
-- The engine will use this string when printing a glyph node e.g. in
-- overfull messages, otherwise it will be trying to print our
-- invalid pseudo Unicode code points.
-- If the string is empty it means this glyph is part of a larger
-- cluster and we don’t to print anything for it as the first glyph
-- in the cluster will have the string of the whole cluster.
local props = properties[node]
if not props then
props = {}
properties[node] = props
end
props.glyph_info = glyph.string or ""
-- Handle PDF text extraction:
-- * Find how many characters in this cluster and how many glyphs,
-- * If there is more than 0 characters
-- * One glyph: one to one or one to many mapping, can be
-- represented by font’s /ToUnicode
-- * More than one: many to one or many to many mapping, can be
-- represented by /ActualText spans.
-- * If there are zero characters, then this glyph is part of complex
-- cluster that will be covered by an /ActualText span.
local tounicode = glyph.tounicode
if tounicode then
if glyph.nglyphs == 1
and not character.commands
and not fontglyph.tounicode then
fontglyph.tounicode = tounicode
elseif character.commands or tounicode ~= fontglyph.tounicode then
setprop(node, startactual_p, tounicode)
glyphs[i + glyph.nglyphs - 1].endactual = true
end
end
if glyph.endactual then
setprop(node, endactual_p, true)
end
local x_advance = glyph.x_advance
local width = fontglyph.width * hfactor
if width ~= x_advance then
-- The engine always uses the glyph width from the font, so we need
-- to insert a kern node if the x advance is different.
local kern = newkern((x_advance - width) * scale, node)
head, node = insertkern(head, node, kern, rtl)
end
end
elseif id == glue_t and getsubtype(node) == spaceskip_t then
-- If the glyph advance is different from the font space, then a
-- substitution or positioning was applied to the space glyph changing
-- it from the default. We try to maintain as much as possible from the
-- original value because we assume that we want to keep spacefactors and
-- assume that we got mostly positioning applied. TODO: Handle the case that
-- we became a glyph in the process.
-- We are intentionally not comparing with the existing glue width as
-- spacing after the period is larger by default in TeX.
local width = glyph.x_advance * scale
-- if space > width + 2 or width > space + 2 then
if space ~= width then
setwidth(node, getwidth(node) - space + width)
-- setfield(node, "stretch", width / 2)
-- setfield(node, "shrink", width / 3)
end
elseif id == kern_t and getsubtype(node) == italiccorr_t then
-- If this is an italic correction node and the previous node is a
-- glyph, update its kern value with the glyph’s italic correction.
local prevchar, prevfontid = ischar(getprev(node))
if prevfontid == fontid and prevchar and prevchar > 0 then
local italic = characters[prevchar].italic
if italic then
setkern(node, italic)
end
end
end
node = getnext(node)
nodeindex = nodeindex + 1
end
end
while node ~= run.after do
local oldnode = node
head, node = removenode(head, node)
freenode(oldnode)
end
return head, node
end
local function shape_run(head, current, run)
if not run.skip then
-- Font loaded with our loader and an HarfBuzz face is present, do our
-- shaping.
local glyphs, offset
head, current, glyphs, offset = shape(head, current, run)
return offset, tonodes(head, current, run, glyphs)
else
return 0, head, run.after
end
end
function process(head, font, _attr, direction)
local newhead, current = head, head
local runs = itemize(head, font, direction)
local offset = 0
for i = 1,#runs do
local run = runs[i]
run.start = run.start - offset
local new_offset
new_offset, newhead, current = shape_run(newhead, current, run)
offset = offset + new_offset
end
return newhead or head
end
local function pageliteral(data)
local n = newnode(whatsit_t, pdfliteral_t)
setfield(n, "mode", 1) -- page
setdata(n, data)
return n
end
local function post_process(head)
for n in traverse(head) do
local props = properties[n]
local startactual, endactual
if props then
startactual = rawget(props, startactual_p)
endactual = rawget(props, endactual_p)
end
if startactual then
local actualtext = "/Span<</ActualText<FEFF"..startactual..">>>BDC"
head = insertbefore(head, n, pageliteral(actualtext))
end
if endactual then
head = insertafter(head, n, pageliteral("EMC"))
end
local replace = getfield(n, "replace")
if replace then
setfield(n, "replace", post_process(replace))
end
local subhead = getfield(n, "head")
if subhead then
setfield(n, "head", post_process(subhead))
end
end
return head
end
local function post_process_nodes(head, groupcode)
return tonode(post_process(todirect(head)))
end
local function run_cleanup()
-- Remove temporary PNG files that we created, if any.
-- FIXME: It would be nice if we wouldn't need this
for _, path in next, pngcachefiles do
osremove(path)
end
end
local function set_tounicode()
for fontid, fontdata in font.each() do
local hbdata = fontdata.hb
if hbdata and fontid == pdf.getfontname(fontid) then
local characters = fontdata.characters
local newcharacters = {}
local hbshared = hbdata.shared
local glyphs = hbshared.glyphs
local nominals = hbshared.nominals
local gid_offset = hbshared.gid_offset
for gid = 0, #glyphs do
local glyph = glyphs[gid]
if glyph.used then
local character = characters[gid + gid_offset]
newcharacters[gid + gid_offset] = character
local unicode = nominals[gid]
if unicode then
newcharacters[unicode] = character
end
character.tounicode = glyph.tounicode or "FFFD"
character.used = true
end
end
font.addcharacters(fontid, { characters = newcharacters })
end
end
end
-- FIXME: Move this into generic parts of luaotfload
local utfchar = utf8.char
local function get_glyph_info(n)
n = todirect(n)
local props = properties[n]
return props and props.glyph_info or utfchar(getchar(n)):gsub('\0', '^^@')
end
fonts.handlers.otf.registerplugin('harf', process)
-- luatexbase does not know how to handle `wrapup_run` callback, teach it.
-- TODO: Move these into ltluatex
luatexbase.callbacktypes.wrapup_run = 1 -- simple
luatexbase.callbacktypes.glyph_info = 1 -- simple
local base_callback_descriptions = luatexbase.callback_descriptions
local base_add_to_callback = luatexbase.add_to_callback
local base_remove_from_callback = luatexbase.remove_from_callback
-- Remove all existing functions from given callback, insert ours, then
-- reinsert the removed ones, so ours takes a priority.
local function add_to_callback(name, func)
local saved_callbacks = {}, ff, dd
for k, v in next, base_callback_descriptions(name) do
saved_callbacks[k] = { base_remove_from_callback(name, v) }
end
base_add_to_callback(name, func, "Harf "..name.." callback")
for _, v in next, saved_callbacks do
base_add_to_callback(name, v[1], v[2])
end
end
add_to_callback('pre_output_filter', post_process_nodes) -- FIXME: Wrong callback, but I want to get rid of the whole function anyway
add_to_callback('wrapup_run', run_cleanup)
add_to_callback('finish_pdffile', set_tounicode)
add_to_callback('glyph_info', get_glyph_info)
|
--[[------------
Q U A K E II
Heads Up Display
Ammo data
]]--------------
if CLIENT then
-- Default half-life ammo
Q2HUD:AddAmmoIcon("Pistol", "hammo0");
Q2HUD:AddAmmoIcon("357", "hammo1");
Q2HUD:AddAmmoIcon("SMG1", "hammo2");
Q2HUD:AddAmmoIcon("AR2", "hammo3");
Q2HUD:AddAmmoIcon("SMG1_Grenade", "hammo4");
Q2HUD:AddAmmoIcon("AR2AltFire", "hammo5");
Q2HUD:AddAmmoIcon("XBowBolt", "hammo6");
Q2HUD:AddAmmoIcon("Buckshot", "qammo2");
Q2HUD:AddAmmoIcon("RPG_Round", "qammo3");
Q2HUD:AddAmmoIcon("Grenade", "qammo0");
Q2HUD:AddAmmoIcon("slam", "qammo0");
-- Quake II SWEPs support
Q2HUD:AddAmmoIcon("Cells", "qammo5");
Q2HUD:AddAmmoIcon("Slugs", "qammo4");
end
|
ffi.cdef [[
typedef struct { bool value; } refbool;
typedef struct { float value; } refnumber;
]]
---Stores a boolean value and can be used as a reference to it.
---@class refbool
---@field value boolean @Stored value.
refbool = ffi.metatype('refbool', { __index = {
---@return boolean
isrefbool = function(x) return ffi.istype('refbool', x) end,
---For easier use with UI controls.
---@param newValue boolean
---@return refbool
set = function (s, newValue) s.value = newValue return s end
} })
---Stores a numerical value and can be used as a reference to it.
---@class refnumber
---@field value number @Stored value.
refnumber = ffi.metatype('refnumber', { __index = {
---@return boolean
isrefnumber = function(x) return ffi.istype('refnumber', x) end,
---For easier use with UI controls.
---@param newValue number
---@return refnumber
set = function (s, newValue) s.value = newValue return s end
} })
|
-- EXIT --
shell.exit()
|
local adt = require('algebraic-data-types')
local list -- Forward declaration
local function _table(self)
local ret = {n=0}
local function loop(xs)
xs:match {
Nil = function () end,
Cons = function (hd, tl)
ret[ret.n + 1] = hd
ret.n = ret.n + 1
return loop(tl)
end
}
end
loop(self)
return ret
end
local function cons(self, x)
return list.Cons(x, self)
end
local function uncons(self)
return self:match {
Nil = function ()
error("Cannot decompose an empty list", 2)
end,
Cons = function (hd, tl)
return hd, tl
end
}
end
local function head(self)
local hd = self:uncons()
return hd
end
local function tail(self)
return select(2, self:uncons())
end
local function __concat(xs, ys)
return xs:match {
Nil = function ()
return ys
end,
Cons = function (hd, tl)
return list.Cons(hd, __concat(tl, ys))
end
}
end
local function length(self)
local len = 0
while true do
if self:is(list.Nil) then
return len
else
len = len+1
self = self.fields[2]
end
end
end
local function null(self)
return self:is(list.Nil)
end
local function map(self, f)
checkArg(1, f, "function")
return self:match {
Nil = function ()
return self
end,
Cons = function (hd, tl)
return list.Cons(f(hd), tl:map(f))
end
}
end
local function _rev(xs, acc)
return xs:match {
Nil = function ()
return acc
end,
Cons = function (hd, tl)
return _rev(tl, list.Cons(hd, acc))
end
}
end
local function reverse(self)
return _rev(self, list.Nil)
end
local function prependToAll(sep, xs)
return xs:match {
Nil = function ()
return xs
end,
Cons = function (hd, tl)
return list.Cons(sep, list.Cons(hd, prependToAll(sep, tl)))
end
}
end
local function intersperse(self, sep)
return self:match {
Nil = function ()
return self
end,
Cons = function (x, xs)
return list.Cons(x, prependToAll(sep, xs))
end
}
end
local function intercalate(self, xs)
return self:intersperse(xs):concat()
end
local function foldl_(f, a, xs)
return xs:match {
Nil = function ()
return a
end,
Cons = function (hd, tl)
return foldl_(f, f(a, hd), tl)
end
}
end
local function foldl(self, f, ...)
checkArg(1, f, "function")
local args = table.pack(...)
if args.n == 0 then
return self:match {
Nil = function ()
error("List is empty", 2)
end,
Cons = function (x, xs)
return foldl_(f, x, xs)
end
}
else
return foldl_(f, args[1], self)
end
end
local function foldr1(f, xs)
return xs:match {
Nil = function ()
error("List is empty", 2)
end,
Cons = function (hd, tl)
if tl:null() then
return hd
else
return f(hd, foldr1(f, tl))
end
end
}
end
local function foldr_(f, a, xs)
return xs:match {
Nil = function ()
return a
end,
Cons = function (hd, tl)
return f(hd, foldr_(f, a, tl))
end
}
end
local function foldr(self, f, ...)
checkArg(1, f, "function")
local args = table.pack(...)
if args.n == 0 then
return foldr1(f, self)
else
return foldr_(f, args[1], self)
end
end
local function concat(self)
return self:foldl(__concat, list.Nil)
end
local function concatMap(self, f)
checkArg(1, f, "function")
return self:foldl(
function (a, x)
return a .. f(x)
end,
list.Nil)
end
local function any(self, f)
checkArg(1, f, "function")
return self:match {
Nil = function ()
return false
end,
Cons = function (hd, tl)
if f(hd) then
return true
else
return tl:any(f)
end
end
}
end
local function all(self, f)
checkArg(1, f, "function")
return self:match {
Nil = function ()
return true
end,
Cons = function (hd, tl)
if f(hd) then
return tl:all(f)
else
return false
end
end
}
end
local function maximum(self)
return self:foldl(
function (max, x)
return max > x and max or x
end)
end
local function minimum(self)
return self:foldl(
function (min, x)
return min < x and min or x
end)
end
local function scanl_(f, a, xs)
return list.Cons(
a,
xs:match {
Nil = function ()
return xs
end,
Cons = function (hd, tl)
return scanl_(f, f(a, hd), tl)
end
})
end
local function scanl(self, f, ...)
checkArg(1, f, "function")
local args = table.pack(...)
if args.n == 0 then
return self:match {
Nil = function ()
return self
end,
Cons = function (x, xs)
return scanl_(f, x, xs)
end
}
else
return scanl_(f, args[1], self)
end
end
local function scanr1(f, xs)
return xs:match {
Nil = function ()
return xs
end,
Cons = function (hd, tl)
if tl:null() then
return xs
else
-- tl isn't null so qs is guaranteed to be non-null.
local qs = scanr1(f, tl)
return list.Cons(f(hd, qs:head()), qs)
end
end
}
end
local function scanr_(f, a, xs)
return xs:match {
Nil = function ()
return list.of(a)
end,
Cons = function (hd, tl)
-- qs can never be non-null.
local qs = scanr_(f, a, tl)
return list.Cons(f(hd, qs:head()), qs)
end
}
end
local function scanr(self, f, ...)
checkArg(1, f, "function")
local args = table.pack(...)
if args.n == 0 then
return scanr1(f, self)
else
return scanr_(f, args[1], self)
end
end
local function take(self, n)
checkArg(1, n, "number")
if n <= 0 then
return list.Nil
elseif self:null() then
return self
else
return list.Cons(self:head(), self:tail():take(n-1))
end
end
local function drop(self, n)
checkArg(1, n, "number")
if n <= 0 then
return self
elseif self:null() then
return self
else
return self:tail():drop(n-1)
end
end
local function splitAt_(n, xs)
return xs:match {
Nil = function ()
return xs, xs
end,
Cons = function (hd, tl)
if n == 1 then
return list.of(hd), tl
else
local ys, zs = splitAt_(n-1, tl)
return list.Cons(hd, ys), zs
end
end
}
end
local function splitAt(self, n)
checkArg(1, n, "number")
if n <= 0 then
return list.Nil, self
else
return splitAt_(n, self)
end
end
local function takeWhile(self, p)
checkArg(1, p, "function")
return self:match {
Nil = function ()
return self
end,
Cons = function (hd, tl)
if p(hd) then
return list.Cons(hd, tl:takeWhile(p))
else
return list.Nil
end
end
}
end
local function dropWhile(self, p)
checkArg(1, p, "function")
return self:match {
Nil = function ()
return self
end,
Cons = function (hd, tl)
if p(hd) then
return tl:dropWhile(p)
else
return self
end
end
}
end
local function span(self, p)
checkArg(1, p, "function")
return self:match {
Nil = function ()
return self, self
end,
Cons = function (hd, tl)
if p(hd) then
local ys, zs = tl:span(p)
return list.Cons(hd, ys), zs
else
return list.Nil, self
end
end
}
end
local function nth(self, n)
checkArg(1, n, "number")
if n <= 0 then
error("List index out of range: "..n, 2)
else
return self:match {
Nil = function ()
error("List index out of range: "..n, 2)
end,
Cons = function (hd, tl)
if n == 1 then
return hd
else
return tl:nth(n-1)
end
end
}
end
end
-- NOTE: There are obviously more functions to be added, but I'm tired
-- of doing this. Maybe I will do it later.
list = adt.define(
adt.constructor('Nil'),
adt.constructor('Cons', adt.field(), adt.field()),
adt.method('table', _table),
adt.method('cons', cons),
adt.method('uncons', uncons),
adt.metamethod('__concat', __concat),
adt.method('head', head),
adt.method('tail', tail),
adt.method('null', null),
adt.metamethod('__len', length),
adt.method('map', map),
adt.method('reverse', reverse),
adt.method('intersperse', intersperse),
adt.method('intercalate', intercalate),
adt.method('foldl', foldl),
adt.method('foldr', foldr),
adt.method('concat', concat),
adt.method('concatMap', concatMap),
adt.method('any', any),
adt.method('all', all),
adt.method('maximum', maximum),
adt.method('minimum', minimum),
adt.method('scanl', scanl),
adt.method('scanr', scanr),
adt.method('take', take),
adt.method('drop', drop),
adt.method('splitAt', splitAt),
adt.method('takeWhile', takeWhile),
adt.method('dropWhile', dropWhile),
adt.method('span', span),
adt.method('nth', nth))
-- This is just an alias.
list.empty = list.Nil
function list.of(...)
local args = table.pack(...)
local self = list.Nil
for i = args.n, 1, -1 do
self = list.Cons(args[i], self)
end
return self
end
function list.from(...)
local args = table.pack(...)
checkArg(1, args[1], "table", "function")
local self = list.Nil
if type(args[1]) == "table" then
local seq = args[1]
for i = #seq, 1, -1 do
self = list.Cons(seq[i], self)
end
else
for _, v in table.unpack(args) do
self = list.Cons(v, self)
end
self = self:reverse()
end
return self
end
return list
|
-----------------------------------
-- Physical Shield
-- Blocks all physical attacks
--
-----------------------------------
require("scripts/globals/status")
-----------------------------------
function onEffectGain(target,effect)
if (effect:getPower() < 2) then
target:addMod(tpz.mod.UDMGPHYS, -100)
else
target:addMod(tpz.mod.PHYS_ABSORB, 100)
end
end
function onEffectTick(target,effect)
end
function onEffectLose(target,effect)
if (effect:getPower() < 2) then
target:delMod(tpz.mod.UDMGPHYS, -100)
else
target:delMod(tpz.mod.PHYS_ABSORB, 100)
end
end
|
--[[
TheNexusAvenger
Stores settings.
--]]
local NexusVRCharacterModel = require(script.Parent.Parent)
local NexusObject = NexusVRCharacterModel:GetResource("NexusInstance.NexusObject")
local NexusEventCreator = NexusVRCharacterModel:GetResource("NexusInstance.Event.NexusEventCreator")
local Settings = NexusObject:Extend()
Settings:SetClassName("Settings")
--[[
Creates a settings object.
--]]
function Settings:__new()
self:InitializeSuper()
--Store the settings.
self.Defaults = {}
self.Overrides = {}
self.SettingsChangeEvents = {}
self.SettingsCache = {}
end
--[[
Returns the value of a setting.
--]]
function Settings:GetSetting(Setting)
--Return a cached entry if one exists.
if self.SettingsCache[Setting] ~= nil then
return self.SettingsCache[Setting]
end
--Get the table containing the setting.
local Defaults,Overrides = self.Defaults,self.Overrides
local SplitSettingNames = string.split(Setting,".")
for i = 1,#SplitSettingNames - 1 do
Defaults = Defaults[SplitSettingNames[i]] or {}
Overrides = Overrides[SplitSettingNames[i]] or {}
end
--Return the value.
local Value = Overrides[SplitSettingNames[#SplitSettingNames]]
if Value == nil then
Value = Defaults[SplitSettingNames[#SplitSettingNames]]
end
self.SettingsCache[Setting] = Value
return Value
end
--[[
Sets the value of a setting.
--]]
function Settings:SetSetting(Setting,Value)
--Set the setting.
local Overrides = self.Overrides
local SplitSettingNames = string.split(Setting,".")
for i = 1,#SplitSettingNames - 1 do
if not Overrides[SplitSettingNames[i]] then
Overrides[SplitSettingNames[i]] = {}
end
Overrides = Overrides[SplitSettingNames[i]]
end
Overrides[SplitSettingNames[#SplitSettingNames]] = Value
self.SettingsCache[Setting] = Value
--Fire the changed signal.
local Event = self.SettingsChangeEvents[string.lower(Setting)]
if Event then
Event:Fire()
end
end
--[[
Sets all the defaults.
--]]
function Settings:SetDefaults(Defaults)
--Set the defaults.
self.Defaults = Defaults
self.SettingsCache = {}
--Fire all the event changes.
for _,Event in pairs(self.SettingsChangeEvents) do
Event:Fire()
end
end
--[[
Sets all the overrides.
--]]
function Settings:SetOverrides(Overrides)
--Set the overrides.
self.Overrides = Overrides
self.SettingsCache = {}
--Fire all the event changes.
for _,Event in pairs(self.SettingsChangeEvents) do
Event:Fire()
end
end
--[[
Returns a changed signal for a setting.
--]]
function Settings:GetSettingsChangedSignal(SettingName)
SettingName = string.lower(SettingName)
--Create the event if none exists.
if not self.SettingsChangeEvents[SettingName] then
self.SettingsChangeEvents[SettingName] = NexusEventCreator:CreateEvent()
end
--Return the event.
return self.SettingsChangeEvents[SettingName]
end
--[[
Destroys the settings.
--]]
function Settings:Destroy()
--Disconnect the settings.
for _,Event in pairs(self.SettingsChangeEvents) do
Event:Disconnect()
end
self.SettingsChangeEvents = {}
end
return Settings
|
package("libxkbcommon")
set_homepage("https://xkbcommon.org/")
set_description("keymap handling library for toolkits and window systems")
set_license("MIT")
add_urls("https://github.com/xkbcommon/libxkbcommon/archive/xkbcommon-$(version).tar.gz",
"https://github.com/xkbcommon.git")
add_versions("1.0.3", "5d10a57ab65daad7d975926166770eca1d2c899131ab96c23845df1c42da5c31")
if is_plat("linux") then
add_extsources("apt::libxkbcommon-dev")
end
add_configs("x11", {description = "Switch backend to X11 (default is wayland).", default = false, type = "boolean"})
on_load("linux", function (package)
if package:config("x11") then
package:add("deps", "libxcb", "xcb-proto", "libxml2")
else
package:add("deps", "wayland")
end
end)
add_deps("meson")
on_install("linux", function (package)
package:addenv("PATH", "bin")
local configs = {"-Denable-docs=false", "-Dc_link_args=-lm"}
table.insert(configs, "--libdir=lib")
if package:config("x11") then
table.join2(configs, {"-Denable-wayland=false", "-Dxkb-config-root=/usr/share/X11/xkb", "-Dx-locale-root=/usr/share/X11/locale"})
else
table.join2(configs, {"-Denable-x11=false", "-Dxkb-config-root=/usr/share/X11/xkb", "-Dx-locale-root=/usr/share/X11/locale"})
end
import("package.tools.meson").install(package, configs)
end)
on_test(function (package)
assert(package:has_cfuncs("xkb_context_new", {includes = "xkbcommon/xkbcommon.h"}))
end)
|
return
{
head = false,
face =
{
{
"ActionEditor/Model/Output/boy.clip|face",
{"positionX",-2},
{"positionY",2},
},
},
fHair =
{
{
"ActionEditor/Model/Output/boy.clip|fHair",
{"positionX",43},
{"positionY",70},
},
},
bHair =
{
{
"ActionEditor/Model/Output/boy.clip|bHair",
{"positionX",17},
{"positionY",24},
},
},
fBody =
{
{
"ActionEditor/Model/Output/boy.clip|fBody",
{"positionX",5},
{"positionY",-3},
},
},
bBody =
{
{
"ActionEditor/Model/Output/boy.clip|bBody",
{"positionX",1},
{"positionY",-34},
},
},
lArm =
{
{
"ActionEditor/Model/Output/boy.clip|lArm",
{"positionX",14},
{"positionY",27},
},
},
lHand =
{
{
"ActionEditor/Model/Output/boy.clip|lHand",
{"positionX",22},
{"positionY",46},
},
},
rArm =
{
{
"ActionEditor/Model/Output/boy.clip|rArm",
{"positionX",10},
{"positionY",24},
},
},
rHand =
{
{
"ActionEditor/Model/Output/boy.clip|rHand",
{"positionX",10},
{"positionY",44},
},
},
lLeg =
{
{
"ActionEditor/Model/Output/boy.clip|lLeg",
{"positionX",7},
{"positionY",34},
},
},
lFoot =
{
{
"ActionEditor/Model/Output/boy.clip|lLegD",
{"positionX",14},
{"positionY",56},
},
{
"ActionEditor/Model/Output/boy.clip|lFoot",
{"positionX",6},
{"positionY",6},
{"angle",15},
},
},
rLeg =
{
{
"ActionEditor/Model/Output/boy.clip|rLeg",
{"positionX",14},
{"positionY",30},
},
},
rFoot =
{
{
"ActionEditor/Model/Output/boy.clip|rLegD",
{"positionX",8},
{"positionY",56},
},
{
"ActionEditor/Model/Output/boy.clip|lFoot",
{"positionX",5},
{"positionY",5},
{"angle",15},
},
},
}
|
-- Causa Dano a todos jogadores
local rolagem = arg[1];
if rolagem==nil then
rolagem = inputQuery("Rolagem de dano a ser causado.");
end;
local resultado = rolar(rolagem, "Dano em Area");
for i = 1, #jogadores, 1 do
if jogadores[i].isJogador then
local min, max = jogadores[i]:getBarValue(1);
local novo = min - resultado;
jogadores[i]:requestSetBarValue(1, novo);
end;
end;
|
corellia_selonian_patrol_neutral_none = Lair:new {
mobiles = {{"selonian_scout",1},{"selonian_thief",1},{"selonian_healer",1},{"domestic_humbaba",1},{"domestic_krahbu",1}},
spawnLimit = 15,
buildingsVeryEasy = {},
buildingsEasy = {},
buildingsMedium = {},
buildingsHard = {},
buildingsVeryHard = {},
mobType = "npc",
buildingType = "none"
}
addLairTemplate("corellia_selonian_patrol_neutral_none", corellia_selonian_patrol_neutral_none)
|
--[[ =================================================================
Description:
All strings (Chinese) used by MailTips.
================================================================= --]]
-- Strings used within MailTips
-- Locale by 急云@CWDG 2008-10-9
if (GetLocale()=="zhCN") then
MT_STARTUP_MESSAGE = MT_NAME.." ("..C_GREEN..MT_VERSION..C_CLOSE..") \229\183\178\232\189\189\229\133\165.";
MT_ENCLOSED_ITEMS = "\232\180\167\231\137\169\230\184\133\229\141\149";
end;
|
-- ----------------------------------------------------------------------------------------------------
-- INFINITY CHEATS DEFINITIONS
-- Definitions for infinity cheats. Basically just a bunch of enormous tables!
local abs = math.abs
local conditional_event = require('scripts/util/conditional-event')
local chunk = require('__stdlib__/stdlib/area/chunk')
local event = require('__stdlib__/stdlib/event/event')
local table = require('__stdlib__/stdlib/utils/table')
local util = require('scripts/util/util')
local defs = {}
local vanilla_loaders_recipes = {
'loader',
'fast-loader',
'express-loader'
}
-- cheat data and functions
defs.cheats = {
player = {
god_mode = {type='toggle', functions={
value_changed = function(player, cheat, cheat_global, new_value)
local player_table = util.player_table(player)
local character = player.character
if new_value == true then
-- make sure the player is not in god mode
if player.controller_type == defines.controllers.character then
-- store character in global
player_table.character = character
-- 'deactivate' (freeze) character
player_table.character.active = false
-- switch controller and transfer inventory
player.set_controller{type=defines.controllers.god}
util.transfer_inventory_contents(character.get_inventory(defines.inventory.character_main), player.get_inventory(defines.inventory.god_main))
end
else
-- make sure the player is in god mode
if player.controller_type == defines.controllers.god then
-- save inventory
local god_inventory = player.get_inventory(defines.inventory.god_main)
-- if the player does not own a character, create one
if not player_table.character then
player_table.character = player.surface.create_entity{name='character', position=player.position, force=player.force}
end
-- teleport character to current position and reenable movement
player_table.character.teleport(player.position)
player_table.character.active = true
-- transfer inventory and switch controller
util.transfer_inventory_contents(god_inventory, player_table.character.get_inventory(defines.inventory.character_main))
player.set_controller{type=defines.controllers.character, character=player_table.character}
end
end
end,
get_value = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.god
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.editor
end
}},
true_zoom_to_world = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
player.spectator = new_value
end,
get_value = function(player, cheat, cheat_global)
return player.spectator
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.god
end
}},
invincible_character = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then
player.character.destructible = not new_value
end
end,
get_value = function(player, cheat, cheat_global)
return player.character and not player.character.destructible or false
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
instant_blueprint = {type='toggle', defaults={on=true, off=false}, functions={
setup_global_global = function(player, default)
return {next_tick_entities={}}
end,
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.instant_blueprint.on_built_entity')
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.instant_blueprint.on_built_entity')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.editor
end
}},
instant_upgrade = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.instant_upgrade.on_marked_for_upgrade')
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.instant_upgrade.on_marked_for_upgrade')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.editor
end
}},
instant_deconstruction = {type='toggle', defaults={on=true, off=false}, functions={
setup_global_global = function(player, default)
return {next_tick_entities={}}
end,
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.instant_deconstruction.on_deconstruction')
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.instant_deconstruction.on_deconstruction')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.editor
end
}},
cheat_mode = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
player.cheat_mode = new_value
end,
get_value = function(player, cheat, cheat_global)
return player.cheat_mode
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.editor
end
}},
keep_last_item = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.keep_last_item.on_put_item')
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.keep_last_item.on_put_item')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.editor
end
}},
single_stack_limit = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.single_stack_limit.on_main_inventory_changed')
conditional_event.dispatch('cheats.player.single_stack_limit.on_main_inventory_changed', {player_index=player.index})
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.single_stack_limit.on_main_inventory_changed')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type ~= defines.controllers.editor
end
}},
repair_used_item = {type='toggle', defaults={on=true, off=false}, functions={
setup_global_global = function(player, default)
return {cur_players={}}
end,
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.repair_used_item.on_main_inventory_changed')
conditional_event.cheat_register(player, cheat, 'cheats.player.repair_used_item.on_cursor_stack_changed')
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.repair_used_item.on_main_inventory_changed')
conditional_event.cheat_deregister(player, cheat, 'cheats.player.repair_used_item.on_cursor_stack_changed')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end
}},
instant_request = {type='toggle', defaults={on=true, off=false}, functions={
setup_global = function(player, default)
return {cur_value=default}
end,
setup_global_global = function(player, default)
return {active_players={}}
end,
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.instant_request.on_main_inventory_changed')
conditional_event.cheat_register(player, cheat, 'cheats.player.instant_request.on_gui_opened')
event.dispatch{name=defines.events.on_player_main_inventory_changed, player_index=player.index}
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.instant_request.on_main_inventory_changed')
conditional_event.cheat_deregister(player, cheat, 'cheats.player.instant_request.on_gui_opened')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
instant_trash = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(player, cheat, 'cheats.player.instant_trash.on_trash_inventory_changed')
event.dispatch{name=defines.events.on_player_trash_inventory_changed, player_index=player.index}
else
conditional_event.cheat_deregister(player, cheat, 'cheats.player.instant_trash.on_trash_inventory_changed')
end
end,
get_value = function(player, cheat, cheat_global)
return cheat_global.cur_value
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_reach_distance_bonus = {type='number', defaults={on=1000000, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_reach_distance_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_reach_distance_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_build_distance_bonus = {type='number', defaults={on=1000000, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_build_distance_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_build_distance_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_resource_reach_distance_bonus = {type='number', defaults={on=1000000, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_resource_reach_distance_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_resource_reach_distance_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_item_drop_distance_bonus = {type='number', defaults={on=1000000, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_item_drop_distance_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_item_drop_distance_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_item_pickup_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_item_pickup_distance_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_item_pickup_distance_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_loot_pickup_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_loot_pickup_distance_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_loot_pickup_distance_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_mining_speed_modifier = {type='number', defaults={on=100, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_mining_speed_modifier = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_mining_speed_modifier
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_running_speed_modifier = {type='number', defaults={on=2, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_running_speed_modifier = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_running_speed_modifier
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_crafting_speed_modifier = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_crafting_speed_modifier = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_crafting_speed_modifier
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_inventory_slots_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_inventory_slots_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_inventory_slots_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
character_health_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(player, cheat, cheat_global, new_value)
if player.character then player.character_health_bonus = new_value end
end,
get_value = function(player, cheat, cheat_global)
return player.character and player.character_health_bonus
end,
get_enabled = function(player, cheat, cheat_global)
return player.controller_type == defines.controllers.character
end
}},
clear_inventory = {type='action', functions={
action = function(player, cheat, cheat_table)
player.get_main_inventory().clear()
end
}}
},
force = {
instant_research = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(force, cheat, 'cheats.force.instant_research.on_research_started')
else
conditional_event.cheat_deregister(force, cheat, 'cheats.force.instant_research.on_research_started')
end
end,
get_value = function(force, cheat, cheat_global)
return cheat_global.cur_value
end
}},
research_queue = {type='toggle', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.research_queue_enabled = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.research_queue_enabled
end
}},
infinity_tools_recipes = {type='toggle', defaults={on=true, off=true}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
for n,r in pairs(game.recipe_prototypes) do
if string.find(n, 'im_tool_') and force.recipes[n] then force.recipes[n].enabled = new_value end
end
end,
get_value = function(force, cheat, cheat_global)
return cheat_global.cur_value
end
}},
free_resource_recipes = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
for n,r in pairs(game.recipe_prototypes) do
if string.find(n, 'im_free_resource_') and force.recipes[n] then force.recipes[n].enabled = new_value end
end
end,
get_value = function(force, cheat, cheat_global)
return cheat_global.cur_value
end
}},
vanilla_loaders_recipes = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
for _,n in pairs(vanilla_loaders_recipes) do
if force.recipes[n] then force.recipes[n].enabled = new_value end
end
end,
get_value = function(force, cheat, cheat_global)
return cheat_global.cur_value
end
}},
misc_vanilla_recipes = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
--force.recipes['player-port'].enabled = new_value
--force.recipes['railgun'].enabled = new_value
--force.recipes['railgun-dart'].enabled = new_value
end,
get_value = function(force, cheat, cheat_global)
return cheat_global.cur_value
end
}},
character_reach_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_reach_distance_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_reach_distance_bonus
end
}},
character_build_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_build_distance_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_build_distance_bonus
end
}},
character_resource_reach_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_resource_reach_distance_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_resource_reach_distance_bonus
end
}},
character_item_drop_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_item_drop_distance_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_item_drop_distance_bonus
end
}},
character_item_pickup_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_item_pickup_distance_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_item_pickup_distance_bonus
end
}},
character_loot_pickup_distance_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_loot_pickup_distance_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_loot_pickup_distance_bonus
end
}},
manual_mining_speed_modifier = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.manual_mining_speed_modifier = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.manual_mining_speed_modifier
end
}},
character_running_speed_modifier = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_running_speed_modifier = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_running_speed_modifier
end
}},
manual_crafting_speed_modifier = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.manual_crafting_speed_modifier = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.manual_crafting_speed_modifier
end
}},
character_inventory_slots_bonus = {type='number', defaults={on=10, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_inventory_slots_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_inventory_slots_bonus
end
}},
character_health_bonus = {type='number', defaults={on=0, off=0}, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.character_health_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.character_health_bonus
end
}},
inserter_stack_size_bonus = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.inserter_stack_size_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.inserter_stack_size_bonus
end
}},
stack_inserter_capacity_bonus = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.stack_inserter_capacity_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.stack_inserter_capacity_bonus
end
}},
mining_drill_productivity_bonus = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.mining_drill_productivity_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.mining_drill_productivity_bonus
end
}},
laboratory_speed_modifier = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.laboratory_speed_modifier = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.laboratory_speed_modifier
end
}},
laboratory_productivity_bonus = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.laboratory_productivity_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.laboratory_productivity_bonus
end
}},
worker_robots_speed_modifier = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.worker_robots_speed_modifier = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.worker_robots_speed_modifier
end
}},
worker_robots_battery_modifier = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.worker_robots_battery_modifier = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.worker_robots_battery_modifier
end
}},
worker_robots_storage_bonus = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.worker_robots_storage_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.worker_robots_storage_bonus
end
}},
train_braking_force_bonus = {type='number', functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.train_braking_force_bonus = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.train_braking_force_bonus
end
}},
evolution_factor = {type='number', max_value=1, functions={
value_changed = function(force, cheat, cheat_global, new_value)
force.evolution_factor = new_value
end,
get_value = function(force, cheat, cheat_global)
return force.evolution_factor
end
}},
chart_all = {type='action', defaults={on=true}, functions={
action = function(force, cheat, cheat_global)
force.chart_all()
end
}},
kill_all_units = {type='action', functions={
action = function(force, cheat, cheat_global)
force.kill_all_units()
end
}},
research_all_technologies = {type='action', defaults={on=true}, functions={
action = function(force, cheat, cheat_global)
force.research_all_technologies()
end
}},
reset_technologies = {type='action', functions={
action = function(force, cheat, cheat_global)
force.reset()
end
}},
restart_current_research = {type='action', functions={
action = function(force, cheat, cheat_global)
if force.current_research then
force.research_progress = 0
end
end
}},
finish_current_research = {type='action', functions={
action = function(force, cheat, cheat_global)
if force.current_research then
force.research_progress = 1
end
end
}}
},
surface = {
peaceful_mode = {type='toggle', functions={
value_changed = function(surface, cheat, cheat_global, new_value)
surface.peaceful_mode = new_value
end,
get_value = function(surface, cheat, cheat_global)
return surface.peaceful_mode
end
}},
dont_generate_biters = {type='toggle', functions={
value_changed = function(surface, cheat, cheat_global, new_value)
if not surface.map_gen_settings.autoplace_controls then return end
if new_value then
local map_gen_settings = table.deepcopy(surface.map_gen_settings)
cheat_global.settings_copy = table.deepcopy(map_gen_settings)
map_gen_settings.autoplace_controls['enemy-base'].size = 0
surface.map_gen_settings = map_gen_settings
else
if cheat_global.settings_copy == nil then return end
surface.map_gen_settings = cheat_global.settings_copy
cheat_global.settings_copy = nil
end
end,
get_value = function(surface, cheat, cheat_global)
return cheat_global.cur_value or false
end
}},
freeze_time = {type='toggle', defaults={on=true, off=false}, functions={
value_changed = function(surface, cheat, cheat_global, new_value)
surface.freeze_daytime = new_value
end,
get_value = function(surface, cheat, cheat_global)
return surface.freeze_daytime
end
}},
time_of_day = {type='number', defaults={on=0}, max_value=1, functions={
value_changed = function(surface, cheat, cheat_global, new_value)
surface.daytime = new_value
end,
get_value = function(surface, cheat, cheat_global)
return surface.daytime
end
}},
solar_power_multiplier = {type='number', functions={
value_changed = function(surface, cheat, cheat_global, new_value)
surface.solar_power_multiplier = new_value
end,
get_value = function(surface, cheat, cheat_global)
return surface.solar_power_multiplier
end
}},
min_brightness = {type='number', functions={
value_changed = function(surface, cheat, cheat_global, new_value)
surface.min_brightness = new_value
end,
get_value = function(surface, cheat, cheat_global)
return surface.min_brightness
end
}},
clear_pollution = {type='action', functions={
action = function(surface, cheat, cheat_global)
surface.clear_pollution()
end
}},
clear_all_entities = {type='action', functions={
action = function(surface, cheat, cheat_global)
for pos in surface.get_chunks() do
for _,entity in pairs(surface.find_entities_filtered{area=chunk.to_area(pos), type='character', invert=true}) do
entity.destroy()
end
end
end
}},
auto_clear_all_entities = {type='toggle', functions={
value_changed = function(surface, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(surface, cheat, 'cheats.surface.auto_clear_all_entities.on_chunk_generated')
else
conditional_event.cheat_deregister(surface, cheat, 'cheats.surface.auto_clear_all_entities.on_chunk_generated')
end
end,
get_value = function(surface, cheat, cheat_global)
return cheat_global.cur_value or false
end
}},
fill_with_lab_tiles = {type='action', functions={
action = function(surface, cheat, cheat_global)
surface.destroy_decoratives{}
for chunk_pos in surface.get_chunks() do
local tiles = {}
local chunk_area = chunk.to_area(chunk_pos)
for y=chunk_area.left_top.y,chunk_area.right_bottom.y-1 do
for x=chunk_area.left_top.x,chunk_area.right_bottom.x-1 do
table.insert(tiles, {name=((x+y)%2==0 and 'lab-dark-1' or 'lab-dark-2'), position={x,y}})
end
end
surface.set_tiles(tiles, false)
end
end
}},
auto_fill_with_lab_tiles = {type='toggle', functions={
value_changed = function(surface, cheat, cheat_global, new_value)
if new_value then
conditional_event.cheat_register(surface, cheat, 'cheats.surface.auto_fill_with_lab_tiles.on_chunk_generated')
else
conditional_event.cheat_deregister(surface, cheat, 'cheats.surface.auto_fill_with_lab_tiles.on_chunk_generated')
end
end,
get_value = function(surface, cheat, cheat_global)
return cheat_global.cur_value or false
end
}}
},
game = {
pollution = {type='toggle', functions={
value_changed = function(game, cheat, cheat_global, new_value)
game.map_settings.pollution.enabled = new_value
end,
get_value = function(game, cheat, cheat_global)
return game.map_settings.pollution.enabled
end
}},
evolution = {type='toggle', functions={
value_changed = function(game, cheat, cheat_global, new_value)
game.map_settings.enemy_evolution.enabled = new_value
end,
get_value = function(game, cheat, cheat_global)
return game.map_settings.enemy_evolution.enabled
end
}},
biter_expansion = {type='toggle', functions={
value_changed = function(game, cheat, cheat_global, new_value)
game.map_settings.enemy_expansion.enabled = new_value
end,
get_value = function(game, cheat, cheat_global)
return game.map_settings.enemy_expansion.enabled
end
}},
recipe_difficulty = {type='list', items={'normal','expensive'}, functions={
value_changed = function(game, cheat, cheat_global, selected_index)
game.difficulty_settings.recipe_difficulty = defines.difficulty_settings.recipe_difficulty[cheat.items[selected_index]]
end,
get_value = function(game, cheat, cheat_global)
return table.invert(cheat.items)[table.invert(defines.difficulty_settings.recipe_difficulty)[game.difficulty_settings.recipe_difficulty]]
end
}},
game_speed = {type='number', min_value=0.01, max_value=1000, functions={
value_changed = function(game, cheat, cheat_global, new_value)
game.speed = new_value
end,
get_value = function(game, cheat, cheat_global)
return game.speed
end
}}
}
}
-- cheats GUI parameters
defs.cheats_gui_elems = {
player = {
has_defaults = true,
toggles = {
interaction = {
god_mode = {},
true_zoom_to_world = {tooltip=true},
invincible_character = {},
instant_blueprint = {},
instant_upgrade = {},
instant_deconstruction = {}
},
inventory = {
cheat_mode = {},
keep_last_item = {tooltip=true},
single_stack_limit = {tooltip=true},
repair_used_item = {tooltip=true},
instant_request = {tooltip=true},
instant_trash = {}
}
},
bonuses = {
character_reach_distance_bonus = {},
character_build_distance_bonus = {},
character_resource_reach_distance_bonus = {},
character_item_drop_distance_bonus = {},
character_item_pickup_distance_bonus = {},
character_loot_pickup_distance_bonus = {},
character_mining_speed_modifier = {},
character_running_speed_modifier = {},
character_crafting_speed_modifier = {},
character_inventory_slots_bonus = {},
character_health_bonus = {}
},
actions = {
clear_inventory = {}
}
},
force = {
has_defaults = true,
toggles = {
instant_research = {},
research_queue = {},
infinity_tools_recipes = {},
free_resource_recipes = {tooltip=true},
vanilla_loaders_recipes = {},
misc_vanilla_recipes = {tooltip=true}
},
bonuses = {
character_reach_distance_bonus = {},
character_build_distance_bonus = {},
character_resource_reach_distance_bonus = {},
character_item_drop_distance_bonus = {},
character_item_pickup_distance_bonus = {},
character_loot_pickup_distance_bonus = {},
manual_mining_speed_modifier = {},
character_running_speed_modifier = {},
manual_crafting_speed_modifier = {},
character_inventory_slots_bonus = {},
character_health_bonus = {},
inserter_stack_size_bonus = {},
stack_inserter_capacity_bonus = {},
mining_drill_productivity_bonus = {},
laboratory_speed_modifier = {},
laboratory_productivity_bonus = {},
worker_robots_speed_modifier = {},
worker_robots_battery_modifier = {},
worker_robots_storage_bonus = {},
train_braking_force_bonus = {},
evolution_factor = {textfield={allow_decimal=true}}
},
actions = {
chart_all = {tooltip=true},
kill_all_units = {tooltip=true}
},
research_actions = {
restart_current_research = {},
finish_current_research = {}
}
},
surface = {
has_defaults = false,
toggles = {
peaceful_mode = {},
dont_generate_biters = {tooltip=true},
clear_pollution = {tooltip=true}
},
time = {
freeze_time = {},
time_of_day = {
slider = {min_value=0, max_value=1, value_step=0.1},
textfield = {allow_decimal=true, width=42}
},
min_brightness = {tooltip=true, textfield={allow_decimal=true, width=50}},
solar_power_multiplier = {tooltip=true, textfield={allow_decimal=true, width=50}}
},
clear_entities = {
auto_clear_all_entities = {tooltip=true},
clear_all_entities = {tooltip=true}
},
fill = {
auto_fill_with_lab_tiles = {tooltip=true},
fill_with_lab_tiles = {tooltip=true}
}
},
game = {
has_defaults = false,
toggles = {
pollution = {},
evolution = {},
biter_expansion = {},
-- recipe_difficulty = {},
game_speed = {
slider = {min_value=1, max_value=10, value_step=1},
textfield = {allow_decimal=true, width=50}
}
}
}
}
return defs
|
--- Terra Volta
--- MISSIONS
printDebug("Finished Loading missions.lua")
|
-- TODO: maybe local cache?
function getMailFile(playername)
local saneplayername = string.gsub(playername, "[.|/]", "")
return mail.maildir .. "/" .. saneplayername .. ".json"
end
mail.getMessages = function(playername)
local file = io.open(getMailFile(playername), "r")
local messages = {}
if file then
local json = file:read("*a")
messages = minetest.parse_json(json or "[]") or {}
mail.hud_update(playername, messages)
file:close()
end
return messages
end
mail.setMessages = function(playername, messages)
local file = io.open(getMailFile(playername),"w")
local json = minetest.write_json(messages)
if file and file:write(json) and file:close() then
mail.hud_update(playername, messages)
return true
else
minetest.log("error","[mail] Save failed - messages may be lost!")
return false
end
end
|
---
-- @realm client
-- @section SimpleRoleIcon
local math = math
local surface = surface
local vgui = vgui
local matHover = Material("vgui/spawnmenu/hover")
local PANEL = {}
---
-- @function GetIconSize()
-- @return number
--
---
-- @function SetIconSize(i)
-- @param number i
---
AccessorFunc(PANEL, "m_iIconSize", "IconSize")
function PANEL:Init()
self.Icon = vgui.Create("DRoleImage", self)
self.Icon:SetMouseInputEnabled(false)
self.Icon:SetKeyboardInputEnabled(false)
self.animPress = Derma_Anim("Press", self, self.PressedAnim)
self:SetIconSize(64)
end
---
-- @param number mcode mouse key / code
function PANEL:OnMousePressed(mcode)
if mcode == MOUSE_LEFT then
self:DoClick()
self.animPress:Start(0.1)
end
end
function PANEL:OnMouseReleased()
end
function PANEL:DoClick()
end
function PANEL:OpenMenu()
end
function PANEL:ApplySchemeSettings()
end
local oldPaintOver = PANEL.PaintOver
---
-- @param number w width
-- @param number h height
function PANEL:PaintOver(w, h)
if self.toggled then
surface.SetDrawColor(0, 200, 0, 255)
surface.SetMaterial(matHover)
self:DrawTexturedRect()
end
if isfunction(oldPaintOver) then
oldPaintOver(self, w, h)
end
end
function PANEL:OnCursorEntered()
self.PaintOverOld = self.PaintOver
self.PaintOver = self.PaintOverHovered
end
function PANEL:OnCursorExited()
if self.PaintOver == self.PaintOverHovered then
self.PaintOver = self.PaintOverOld
end
end
function PANEL:PaintOverHovered()
if self.animPress:Active() or self.toggled then return end
surface.SetDrawColor(255, 255, 255, 80)
surface.SetMaterial(matHover)
self:DrawTexturedRect()
end
function PANEL:PerformLayout()
if self.animPress:Active() then return end
self:SetSize(self.m_iIconSize, self.m_iIconSize)
self.Icon:StretchToParent(0, 0, 0, 0)
end
---
-- @param Material icon
function PANEL:SetIcon(icon)
self.Icon:SetImage(icon)
end
---
-- @return Material
function PANEL:GetIcon()
return self.Icon:GetImage()
end
function PANEL:SetIconColor(c)
self.Icon:SetImageColor(c)
end
function PANEL:Think()
self.animPress:Run()
end
---
-- @param table anim
-- @param number delta
-- @param table data
function PANEL:PressedAnim(anim, delta, data)
if anim.Started then return end
if anim.Finished then
self.Icon:StretchToParent(0, 0, 0, 0)
return
end
local border = math.sin(delta * math.pi) * (self.m_iIconSize * 0.05)
self.Icon:StretchToParent(border, border, border, border)
end
---
-- @param boolean b
function PANEL:Toggle(b)
self.toggled = b
end
vgui.Register("SimpleRoleIcon", PANEL, "Panel")
|
project "cpp_redis"
language "C++"
cppdialect "C++11"
kind "StaticLib"
targetname "cpp_redis"
includedirs { "includes", "tacopie/includes" }
dependson { "tacopie" }
links { "tacopie" }
vpaths {
["Headers/*"] = "includes/cpp_redis/**.hpp",
["Sources/*"] = "sources/**.cpp",
["*"] = "premake5.lua"
}
files {
"premake5.lua",
"**.cpp",
"**.hpp"
}
excludes {
"tacopie/**",
"examples/**",
"tests/**"
}
|
--RasPegacy v0.1
--Menu Child
gl.setup(720, 40)
node.alias("menu")
bg = resource.load_image("bg_top.png")
title = resource.load_image("title.png")
local json = require "json"
local font = resource.load_font("Exo2.otf")
util.file_watch("menu.json", function(content)
menu = json.decode(content)
cur = menu.current
steps = string.format(cur.step1 .. cur.step2 .. cur.step3 .. '.png')
menpic = resource.load_image(steps)
end)
local clk = "00:00"
local tmp = "0"
util.data_mapper{
["clock/clk"] = function(new_clk)
--print("CLK", new_clk)
if new_clk ~= nil then
clk = new_clk
else
clk = "--"
end
end;
["clock/tmp"] = function(new_tmp)
--print("TMP", new_tmp)
if new_tmp ~= nil then
tmp = new_tmp
else
tmp = "--"
end
end;
}
function node.render()
gl.clear(0, 0, 0, 1)
--if tonumber(clk) < 2000 then
-- gl.clear(0, 0, 0, 0)
--end
-- Load menu background
bg:draw(0, 0, 720, 40, 1)
-- Load Title (alpha determined by if menu is active [json "current:step1"]
title:draw(241, 0, WIDTH, HEIGHT, 1)
-- Load menu items (menu selection based on json file "current";file is selected by [steps]
-- which corresponds to the file names [i.e. "000.png" is the top most menu level)
menpic:draw(0, 0, 240, 40)
-- Draw clock
font:write(WIDTH - 50, 2, clk, 18, 1, 1, 1, 1)
font:write(WIDTH - 190, 2, 'Inside: ' .. tmp .. '°', 18, 1, 1, 1, 1)
end
|
ui = {}
function ui.load()
end
function ui.draw()
love.graphics.print("HUNGER:", 50, 0)
love.graphics.print("HEALTH:", 250, 0)
love.graphics.print("SCORE:", 450, 0)
love.graphics.print("ROUND:", 650, 0)
love.graphics.print(game.score, 450, 25)
love.graphics.print(game.round, 650, 25)
love.graphics.setColor(0, 0, 0)
love.graphics.rectangle("fill", 50, 26, 100, 8)
love.graphics.rectangle("fill", 250, 26, 100, 8)
love.graphics.setColor(255, 170, 0)
love.graphics.rectangle("fill", 50, 25, whale.hunger, 10)
love.graphics.setColor(255, 0, 0)
love.graphics.rectangle("fill", 250, 25, whale.health, 10)
love.graphics.setColor(255, 255, 255)
end
function ui.update()
end
|
local theme={colors={normal={blue={0.31764705882353,0.4156862745098,0.92549019607843,1},green={0.56862745098039,0.54509803921569,0.23137254901961,1},cyan={0.082352941176471,0.57647058823529,0.57647058823529,1},white={0.67058823529412,0.6078431372549,0.67058823529412,1},red={0.7921568627451,0.25098039215686,0.16862745098039,1},magenta={0.48235294117647,0.34901960784314,0.75294117647059,1},black={0.10588235294118,0.094117647058824,0.10588235294118,1},yellow={0.73333333333333,0.54117647058824,0.2078431372549,1}},primary={background={0.10588235294118,0.094117647058824,0.10588235294118,1},foreground={0.67058823529412,0.6078431372549,0.67058823529412,1}},bright={blue={0.61960784313725,0.56078431372549,0.61960784313725,1},green={0.16078431372549,0.13725490196078,0.16078431372549,1},cyan={0.8,0.2,0.8,1},white={0.96862745098039,0.95294117647059,0.96862745098039,1},red={0.65098039215686,0.34901960784314,0.14901960784314,1},magenta={0.84705882352941,0.7921568627451,0.84705882352941,1},black={0.46666666666667,0.41176470588235,0.46666666666667,1},yellow={0.41176470588235,0.36470588235294,0.41176470588235,1}},cursor={text={0.10588235294118,0.094117647058824,0.10588235294118,1},cursor={0.67058823529412,0.6078431372549,0.67058823529412,1}}}}
return theme.colors
|
-----------------------------------
-- Area: Quicksand Caves
-- NPC: Goblin Geologist
-- Type: Mission
-- !pos -737.000 -11.125 -550.000 208
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:startEvent(100);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
Statemachine = class{}
function Statemachine:init(states)
self.empty = {
render = function() end,
update = function() end,
enter = function() end,
exit = function() end
}
self.states = states or {} -- [name] -> [function that returns states]
self.current = self.empty
end
function Statemachine:change(stateName, enterParams)
self.current = self.states[stateName]()
end
function Statemachine:update(dt)
self.current:update(dt)
end
function Statemachine:render()
self.current:render()
end
|
--[=[
Module:utils v0.3.1
Date: 2015-08-14
This module contains some common useful functions.
Fill free to add another universal functions here.
]=]--
local export = {}
-- Function to clone table (sometimes it works better then mw.clone)
function export.clone(original)
local copy = {}
for key, value in pairs(original) do
copy[key] = value
end
return copy
end
-- Function to get current PAGENAME and related
function export.get_base()
local PAGENAME = mw.title.getCurrentTitle().text
local SUBPAGENAME = mw.title.getCurrentTitle().subpageText
local NAMESPACE = mw.title.getCurrentTitle().nsText
if NAMESPACE == 'User' or NAMESPACE == 'Участник' then
return SUBPAGENAME
end
return PAGENAME
end
-- Function to iterate table with sorted keys (sorting function can be different)
function export.spairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- sort
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
-- Functions to measure working time of scripts (start)
function export.start()
export.started = os.clock()
end
-- Functions to measure working time of scripts (stop)
function export.stop(desc)
export.stoped = os.clock()
export.delta = export.stoped - export.started
if desc == nil then
desc = 'time delta'
end
mw.log('™ ' .. desc .. ' = ' .. export.delta)
end
-- Function to find common part (length) of two strings
-- (common part from the beginning of strings)
function export.find_common(str_1, str_2)
if not str_1 or not str_2 then
return 1
end
for pos = 1, #str_1 do
local char_1 = str_1:sub(pos, pos)
local char_2 = str_2:sub(pos, pos)
if char_1 ~= char_2 then
return pos
end
end
return 1
end
-- Function that allows easily add values into dict of dicts of lists
-- Example of this structure:
-- dict = {
-- key1 = {
-- sub_key1 = {value1, value2, value3},
-- sub_key2 = {value4, value5},
-- },
-- key2 = {
-- sub_key3 = {value6},
-- sub_key4 = {value7, value8},
-- },
-- }
function export.put_value(dict, key, sub_key, value)
if not dict[key] then
dict[key] = {}
end
if not dict[key][sub_key] then
dict[key][sub_key] = {}
end
table.insert(dict[key][sub_key], value)
end
-- Compare two items, recursively comparing lists.
-- FIXME, doesn't work for tables that aren't lists.
function export.equals(x, y)
if type(x) == "table" and type(y) == "table" then
if #x ~= #y then
return false
end
for key, value in ipairs(x) do
if not export.equals(value, y[key]) then
return false
end
end
return true
end
return x == y
end
-- true if list contains item
function export.contains(tab, item)
for _, value in pairs(tab) do
if export.equals(value, item) then
return true
end
end
return false
end
-- append to list if element not already present
function export.insert_if_not(tab, item, pos)
if not export.contains(tab, item) then
if pos then
table.insert(tab, pos, item)
else
table.insert(tab, item)
end
end
end
-- convert list to set
function export.list_to_set(list)
local set = {}
for _, item in ipairs(list) do
set[item] = true
end
return set
end
-- Inhibit Regular Expression magic characters ^$()%.[]*+-?)
function export.escape(value)
-- Prefix every non-alphanumeric character (%W) with a % escape character,
-- where %% is the % escape, and %1 is original character
return mw.ustring.gsub(value, "(%W)","%%%1")
end
return export
|
--[[
desc: WORLD, a system set.
author: Musoucrow
since: 2018-3-20
alter: 2019-8-25
]]--
local _CONFIG = require("config")
local _TABLE = require("lib.table")
local _GRAPHICS = require("lib.graphics")
local _RESOURCE = require("lib.resource")
local _ECSMGR = require("actor.ecsmgr")
local _MAP = require("map.init")
local _QuickList = require("core.quickList")
local _DigitTip = require("actor.digitTip")
local _damageTipDataMap = {
player = _RESOURCE.GetFontData("digitTip/player"),
other = _RESOURCE.GetFontData("digitTip/other"),
beaten = _RESOURCE.GetFontData("digitTip/beaten"),
hp = _RESOURCE.GetFontData("digitTip/hp"),
mp = _RESOURCE.GetFontData("digitTip/mp")
}
local _WORLD = {isPaused = false} ---@class Actor.WORLD
local _systems ---@type table<number, Actor.System>
local _adds = {} ---@type table<int, Actor.System>
local _dels = {} ---@type table<int, Actor.System>
local _updateList = _QuickList.New()
local _lateUpdateList = _QuickList.New()
local _drawList = _QuickList.New()
local _digitTips = {} ---@type table<number, Actor.DigitTip> | table<number, Core.Gear>
local _sortTick = false
local _shader = _RESOURCE.NewShader(_RESOURCE.GetShaderData("white"))
local _player ---@type Actor.Entity
---@param a Actor.System
---@param b Actor.System
---@return boolean
local function _Sorting(a, b)
return a:GetID() < b:GetID()
end
local function _OnClean()
_digitTips = {}
end
function _WORLD.Init()
local event = {
AddSystem = function(system)
if (system.Update and not _updateList:HasValue(system)) then
_updateList:Add(system)
end
if (system.LateUpdate and not _lateUpdateList:HasValue(system)) then
_lateUpdateList:Add(system)
end
if (system.Draw and not _drawList:HasValue(system)) then
_drawList:Add(system)
end
_sortTick = true
end,
DelSystem = function(system)
if (system.Update and _updateList:HasValue(system)) then
_updateList:Del(system)
end
if (system.LateUpdate and _lateUpdateList:HasValue(system)) then
_lateUpdateList:Del(system)
end
if (system.Draw and _drawList:HasValue(system)) then
_drawList:Del(system)
end
end,
Add = function(system)
table.insert(_adds, system)
end,
Del = function(system)
table.insert(_dels, system)
end
}
--Init combo list
require("actor.service.duelist")
require("actor.service.ai")
require("actor.service.pathgate")
_systems = {
require("actor.system.obstacle").New(event),
require("actor.system.attacker").New(event),
require("actor.system.effect").New(event),
require("actor.system.transparency").New(event),
require("actor.system.drawing").New(event),
require("actor.system.onceplay").New(event),
require("actor.system.battle").New(event),
require("actor.system.ais").New(event),
require("actor.system.states").New(event),
require("actor.system.duelist.init").New(event),
require("actor.system.duelist.cowardGoblin").New(event),
require("actor.system.effect.figure").New(event),
require("actor.system.effect.colorize").New(event),
require("actor.system.article").New(event),
require("actor.system.article.grass").New(event),
require("actor.system.article.pathgate").New(event),
require("actor.system.bullet").New(event),
require("actor.system.bullet.throwStone").New(event),
require("actor.system.trigger").New(event),
require("actor.system.skills").New(event),
require("actor.system.equipments").New(event),
require("actor.system.buffs").New(event),
require("actor.system.summon").New(event),
require("actor.system.sound").New(event),
require("actor.system.transport").New(event),
require("actor.system.attributes").New(event),
require("actor.system.life").New(event),
require("actor.system.input").New(event),
}
--Init combo list
require("actor.gear.attack").Init()
require("actor.ai.battleJudge")
require("actor.ai.attackJudge")
require("actor.ai.searchMove")
_MAP.AddLoadListener(self, _OnClean)
end
function _WORLD.Update(dt, rate)
if (_WORLD.isPaused) then
return
end
if (_ECSMGR.AddComponentTick()) then
if (_sortTick) then
_updateList:Sort(_Sorting)
_lateUpdateList:Sort(_Sorting)
_drawList:Sort(_Sorting)
_sortTick = false
end
table.sort(_adds, _Sorting)
for n=1, #_adds do
_adds[n]:Enter()
end
for n=1, #_adds do
_adds[n]:Init()
end
_adds = {}
end
for n=1, _updateList:GetLength() do
_updateList:Get(n):Update(dt, rate)
end
for n=1, _lateUpdateList:GetLength() do
_lateUpdateList:Get(n):LateUpdate(dt, rate)
end
for n=1, #_digitTips do
_digitTips[n]:Update(dt)
end
if (_ECSMGR.DelComponentTick()) then
table.sort(_dels, _Sorting)
for n=1, #_dels do
_dels[n]:Exit()
end
_dels = {}
end
end
function _WORLD.Draw()
for n=1, _drawList:GetLength() do
_drawList:Get(n):Draw()
end
for n=1, #_digitTips do
_digitTips[n]:Draw()
end
_GRAPHICS.SetShader(_shader)
for n=1, #_digitTips do
_digitTips[n]:DrawFlash()
end
_GRAPHICS.SetShader()
end
---@param value int
---@param type string @playerDamage
---@param x int
---@param y int
---@param isCritical boolean
---@return Actor.DigitTip
function _WORLD.AddDamageTip(value, type, x, y, isCritical)
if (not _CONFIG.setting.digit) then
return
end
local flashTime = isCritical and 100 or 0
local scale = isCritical and 3 or 1.5
local scaleTime = isCritical and 200 or 150
local digitTip ---@type Actor.DigitTip
for n=1, #_digitTips do
if (not _digitTips[n].isRunning) then
digitTip = _digitTips[n]
break
end
end
if (not digitTip) then
digitTip = _DigitTip.New()
table.insert(_digitTips, digitTip)
end
digitTip:Enter(tostring(value), _damageTipDataMap[type], x, y, scale, scaleTime, 350, 350, flashTime, -40)
return digitTip
end
return _WORLD
|
local gears = require('gears')
local theme = {}
theme.font = 'JetBrains Mono 10'
theme.useless_gap = 5
theme.border_width = 0
theme.snap_bg = "#E8E3E3"
theme.snap_shape = gears.shape.rectangle
return theme
|
--[[ Trade class ]]--
local Trade = {}
Trade.__index = Trade
Trade.__tostring = function(self)
return table.tostring(self)
end
Trade.trades = {}
Trade.handshakes = {}
setmetatable(Trade, {
__call = function (cls, name)
return cls.new(name)
end,
})
function Trade.new(id, party1, party2)
print("new trade")
local self = setmetatable({}, Trade)
self.id = id
self.party1 = {
name = party1, lands = {}, teleporters = {}, utilities = {}, hasJailFreeCommu = false, hasJailFreeChance = false, money = 0, submitted = false
}
self.party2 = {
name = party2, lands = {}, teleporters = {}, utilities = {}, hasJailFreeCommu = false, hasJailFreeChance = false, money = 0, submitted = false
}
players[party1].tradeID = id
players[party2].tradeID = id
Trade.trades[id] = self
return self
end
function Trade:updateInterface()
print("[trade] updte interface")
local p1Name, p2Name = self.party1.name, self.party2.name
local player1, player2 = players[p1Name], players[p2Name]
local p1Txt, p2Txt = "[" .. p1Name .. "]\n", "[" .. p2Name .. "]\n"
local col = lands[2].color
for id, land in next, lands do
if not land.isSpecial then
if land.color ~= col then
col = land.color
p1Txt = p1Txt .. "\n" ..col
p2Txt = p2Txt .. "\n" .. col
end
-- todo: create another string to displayed to the other party so that they can't add lands to the trade
local p1Owns = not not (player1.ownedLands[col] and player1.ownedLands[col][id])
local p2Owns = not not (player2.ownedLands[col] and player2.ownedLands[col][id])
local p1Added = p1Owns and self.party1.lands[id]
local p2Added = p2Owns and self.party2.lands[id]
if p1Added then print(id) end
p1Txt = p1Txt .. (p1Owns and "<VP><a href='event:trade-addLand:" .. id .. "'>" or "<N2>") .. (p1Added and "<b><T>" or "") .. land.name .. (p1Added and "</T></b>" or "") .. (p1Owns and "</a></VP>" or "</N2>") .. ", "
p2Txt = p2Txt .. (p2Owns and "<VP><a href='event:trade-addLand:" .. id .. "'>" or "<N2>") .. (p2Added and "<b><T>" or "") .. land.name .. (p2Added and "</T></b>" or "") .. (p2Owns and "</a></VP>" or "</N2>") .. ", "
end
end
for _, player in next, ({self.party1.name, self.party2.name}) do
ui.updateTextArea(200, player == p1Name and p1Txt or p2Txt, player)
ui.updateTextArea(201, player == p1Name and p2Txt or p1Txt, player)
end
end
function Trade:addLand(player, landId, add)
print("[trade] add land")
add = add == nil and true or add
local party = player == self.party1.name and 1 or 2
self["party" .. party].lands[landId] = add and true or nil
print(table.tostring(self))
self.party1.submitted = false
self.party2.submitted = false
self:updateInterface()
end
function Trade:addCard(player, type)
local party = player == self.party1.name and 1 or 2
local hasJailFreeChance, hasJailFreeCommu = players[player].hasJailFreeCards["chance"], players[player].hasJailFreeCards["community chest"]
self["party" .. party]["hasJailFree" .. type] = type == "Chance" and hasJailFreeChance or hasJailFreeCommu
local addJailFreeChance, addJailFreeCommu = self["party" .. party].hasJailFreeChance, self["party" .. party].hasJailFreeCommu
local res = player ..
((addJailFreeChance and "<T>" or "") .. (hasJailFreeChance and "<a href='event:jailFreeChance:" .. self.id .. "'>" or "<N2>") .. "Get out of jail free (chance) " .. (hasJailFreeChance and "</a>" or "</N2>") .. (addJailFreeChance and "</T>" or "")) .. "|" ..
((addJailFreeCommu and "<T>" or "") .. (hasJailFreeCommu and "<a href='event:jailFreeCommu:" .. self.id .. "'>" or "<N2>") .. "Get out of jail free (commu)" .. (hasJailFreeCommu and "</a>" or "</N2>") .. (addJailFreeCommu and "</T>" or ""))
ui.updateTextArea(206, res, player)
ui.updateTextArea(207, res, player == self.party1.name and self.party2.name or self.party1.name)
end
function Trade:addMoney(player, amount)
local playerObj = players[player]
if not amount then
tfm.exec.chatMessage("<R>Please specify a valid number!", player)
elseif amount > playerObj.money then
tfm.exec.chatMessage("<R>Not enough money for that action!", player)
else
local party = player == self.party1.name and 1 or 2
self["party" .. party].money = amount
ui.updateTextArea(204, "<a href='event:trade-addMoney:" .. self.id .. "'>Money: $" .. amount .. "</a>", player)
ui.updateTextArea(205, "<a href='event:trade-addMoney:" .. self.id .. "'>Money: $" .. amount .. "</a>", player == self.party1.name and self.party2.name or self.party1.name)
end
end
function Trade:close(closedBy)
print("[trade] close")
if closedBy then
tfm.exec.chatMessage("You cancelled the trade!", closedBy)
tfm.exec.chatMessage("The trade has been cancelled by " .. closedBy, self.party1.name == closeBy and self.party2.name or self.party1.name)
end
handleCloseBtn(200, self.party1.name)
handleCloseBtn(200, self.party2.name)
players[self.party1.name].tradeID = nil
players[self.party2.name].tradeID = nil
Trade.trades[self.id] = nil
self = nil
end
function Trade:submit(submittedBy)
print("[trade] submit")
local party = submittedBy == self.party1.name and 1 or 2
self["party" .. party].submitted = true
if self.party1.submitted and self.party2.submitted then
-- both parties submitted, start the transaction
for party, partyData in next, ({self.party1, self.party2}) do
local partyName = partyData.name
local otherName = partyName == self.party1.name and self.party2.name or self.party1.name
-- exchanging lands
for landID, _ in next, partyData.lands do
lands[landID]:removeOwner()
lands[landID]:setOwner(otherName, 0)
end
-- exchanging money
players[partyName]:addMoney(-(partyData.money))
players[otherName]:addMoney(partyData.money)
-- exchanging cards
if partyData.hasJailFreeChance then
players[partyName].hasJailFreeCards["chance"] = false
players[otherName].hasJailFreeCards["chance"] = true
end
if partyData.hasJailFreeCommu then
players[partyName].hasJailFreeCards["community chest"] = false
players[otherName].hasJailFreeCards["community chest"] = true
end
end
self:close()
end
end
|
ESX = nil
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
while ESX.GetPlayerData().job == nil do
Citizen.Wait(10)
end
ESX.PlayerData = ESX.GetPlayerData()
-- Update the door list
ESX.TriggerServerCallback('esx_doorlock:getDoorInfo', function(doorInfo)
for doorID,state in pairs(doorInfo) do
Config.DoorList[doorID].locked = state
end
end)
end)
RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
ESX.PlayerData.job = job
end)
-- Get objects every second, instead of every frame
Citizen.CreateThread(function()
while true do
for _,doorID in ipairs(Config.DoorList) do
if doorID.doors then
for k,v in ipairs(doorID.doors) do
if not v.object or not DoesEntityExist(v.object) then
v.object = GetClosestObjectOfType(v.objCoords, 1.0, GetHashKey(v.objName), false, false, false)
end
end
else
if not doorID.object or not DoesEntityExist(doorID.object) then
doorID.object = GetClosestObjectOfType(doorID.objCoords, 1.0, GetHashKey(doorID.objName), false, false, false)
end
end
end
Citizen.Wait(1000)
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
local playerCoords = GetEntityCoords(PlayerPedId())
for k,doorID in ipairs(Config.DoorList) do
local distance
if doorID.doors then
distance = #(playerCoords - doorID.doors[1].objCoords)
else
distance = #(playerCoords - doorID.objCoords)
end
local isAuthorized = IsAuthorized(doorID)
local maxDistance, size, displayText = 1.25, 1, _U('unlocked')
if doorID.distance then
maxDistance = doorID.distance
end
if distance < 50 then
if doorID.doors then
for _,v in ipairs(doorID.doors) do
FreezeEntityPosition(v.object, doorID.locked)
if doorID.locked and v.objYaw and GetEntityRotation(v.object).z ~= v.objYaw then
SetEntityRotation(v.object, 0.0, 0.0, v.objYaw, 2, true)
end
end
else
FreezeEntityPosition(doorID.object, doorID.locked)
if doorID.locked and doorID.objYaw and GetEntityRotation(doorID.object).z ~= doorID.objYaw then
SetEntityRotation(doorID.object, 0.0, 0.0, doorID.objYaw, 2, true)
end
end
end
if distance < maxDistance then
if doorID.size then
size = doorID.size
end
if doorID.locked then
displayText = _U('locked')
end
if isAuthorized then
displayText = _U('press_button', displayText)
end
ESX.Game.Utils.DrawText3D(doorID.textCoords, displayText, size)
if IsControlJustReleased(0, 38) then
if isAuthorized then
doorID.locked = not doorID.locked
TriggerServerEvent('esx_doorlock:updateState', k, doorID.locked) -- Broadcast new state of the door to everyone
end
end
end
end
end
end)
function IsAuthorized(doorID)
if ESX.PlayerData.job == nil then
return false
end
for _,job in pairs(doorID.authorizedJobs) do
if job == ESX.PlayerData.job.name then
return true
end
end
return false
end
-- Set state for a door
RegisterNetEvent('esx_doorlock:setState')
AddEventHandler('esx_doorlock:setState', function(doorID, state)
Config.DoorList[doorID].locked = state
end)
|
--------------------------------
-- @module TransitionSceneOriented
-- @extend TransitionScene
-- @parent_module cc
--------------------------------
-- Creates a transition with duration, incoming scene and orientation.<br>
-- param t Duration time, in seconds.<br>
-- param scene A given scene.<br>
-- param orientation A given orientation: LeftOver, RightOver, UpOver, DownOver.<br>
-- return A autoreleased TransitionSceneOriented object.
-- @function [parent=#TransitionSceneOriented] create
-- @param self
-- @param #float t
-- @param #cc.Scene scene
-- @param #int orientation
-- @return TransitionSceneOriented#TransitionSceneOriented ret (return value: cc.TransitionSceneOriented)
return nil
|
--- === cp.web.html ===
---
--- Functions for Generating HTML markup.
---
--- This library allows the creation of 'safe' HTML using via code.
---
--- Examples:
---
--- ```lua
--- local html = require "cp.web.html"
--- print html.p "Hello world!" -- "<p>Hello world!</p>"
--- print html.p { class = "custom" } "Hello world!" -- "<p class='custom'>Hello world!</p>"
--- print html.p { class = "custom" } (
--- html.b "Bold" .. " and " .. html.i "italic" .. "."
--- )
--- -- "<p class='custom'><b>Bold</b> and <i>italic</i>.</p>"
--- print html("1 < 2") -- "1 < 2" (escaped)
--- print html("1 < 2", true) -- "1 < 2" (unescaped)
--- print html.p ("<b>bold</b>", true) -- "<p><b>bold</b></p>"
--- ```
---
--- Be aware that concatonating with ".." can behave unexpectedly in some cases. For example:
---
--- ```lua
--- local name = "world!"
--- print html.p "Hello " .. name -- "<p>Hello </p>world!"
--- ```
---
--- The `"Hello"` gets inserted into the `p` tag, but the `name` gets concatonated after the closing tag.
--- To get the `name` inside the `p` tag, we need to put brackets around the content:
---
--- ```lua
--- print html.p ("Hello " .. name) -- "<p>Hello world!</p>"
--- ```
---
--- Any tag name can be generated, along with any attribute. The results are correctly escaped.
--- There are two 'special' tag names:
--- * `CDATA` - will generate a `<![CDATA[ ... ]]>` section with the content contained.
--- * `__` - (double underscore) will generate a `<!-- ... -->` comment block.
local require = require
local block = require "cp.web.block"
local template = require "resty.template"
local htmlEscape = template.escape
local html = {}
--- cp.web.html.is(value) -> boolean
--- Function
--- Checks if the `value` is an `cp.web.html` block.
---
--- Parameters:
--- * value - the value to check
---
--- Returns:
--- * `true` if it is an HTML block, or `false` otherwise.
html.is = block.is
html.__index = function(_, name)
return function(param, ...)
local pType = type(param)
if param ~= nil and (pType ~= "table" or block.is(param)) then
-- it's content, not attributes
return block.new(name, nil, htmlEscape)(param, ...)
else
return block.new(name, param, htmlEscape)
end
end
end
html.__call = function(_, content, ...)
return block.is(content) and content or block.new("_", nil, htmlEscape)(content, ...)
end
return setmetatable(html, html)
|
local Root = script:FindFirstAncestor("BarrierCreator")
local Roact = require(Root.dependencies.Roact)
return function()
return Roact
end
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
if msgcontains(msg, 'mission') then
if Player(cid):getStorageValue(Storage.WrathoftheEmperor.Questline) == 33 then
npcHandler:say('Oh yez, let me zee ze documentz. Here we go: zree cheztz filled wiz platinum, one houze, a zet of elite armor, and an unending mana cazket. Iz ziz correct?', cid)
npcHandler.topic[cid] = 1
end
elseif msgcontains(msg, 'yes') and npcHandler.topic[cid] == 1 then
npcHandler:say({
'Fine, zo let\'z prozeed. You uzed forged documentz to enter our zity, killed zeveral guardz who enjoyed a quite excluzive and expenzive training, deztroyed rare magical devizez in ze pozzezzion of ze emperor. ...',
'Ze good newz iz, your zree cheztz of platinum should be nearly enough to pay ze finez. Lucky you, ziz could have left you broke. ...',
'Zere are alzo zertain noble familiez complaining about ze murder of zeveral of zeir beloved onez. ...',
'I zink I can make a deal wiz ze noblez by zelling zem your property in ze zity. Your prezenze would ruin ze houze prizez zere anyway. ...',
'Of courze zat will not zuffize to compenzate zeir grief, zo I guezz you\'ll have to part wiz zat elite armor, too. Zadly, prizez for armor are on an all time low right now. ...',
'But luckily you ztill have zat mana cazket. Well, you had it. Now we have to zell it. ...',
'But not all iz lozt my blank-zkinned vizitor. According to my calculationz, zere iz ztill a bit left. ...',
'I zink we can zave you zome gold and zome treazurez, and you can keep one pieze of your elite armor at leazt. ...',
'You will find your rewardz in one of ze old zupply zellarz. Beware of ze ratz zough. ...',
'Ze rednezz of your faze and ze zound you make wiz your teez iz obviouzly a zign of gratitude of your zpeziez! I am flattered, but pleaze leave now az I have to attend to zome important buzinezz.'
}, cid)
Player(cid):setStorageValue(Storage.WrathoftheEmperor.Questline, 34)
npcHandler.topic[cid] = 0
end
return true
end
npcHandler:setMessage(MESSAGE_GREET, 'Greetingz zcalelezz being.')
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
|
function setup()
background(0,0,0)
end
function draw()
if mouse.pressed['1'] then
fill(255,0,0,.2)
else
fill(0,0,255,.2)
end
ellipse(mouse.x,mouse.y,30,30)
end
|
--游戏服务
--主责:战斗模块
local cmd_define = require("app.public.global.cmd_define")
local gate_manager = require("app.public.config.gate_manager")
local game_server = {}
function game_server:deal_game_msg(sub_id, data)
if sub_id == cmd_define.sub_stop_auto_fight_req then
self:send_event(cmd_define.main_game, cmd_define.sub_stop_auto_fight_rsp, {})
return true
elseif sub_id == cmd_define.sub_find_fight_req then
if not data then return false end
local _info = gate_manager.get_instance():get_gate_info(data.gate_id)
if not _info then return false end
if not _info.enemy then return false end
local _index = math.random(1, #_info.enemy)
self:send_event(cmd_define.main_game, cmd_define.sub_find_fight_rsp, {enemy = _info.enemy[_index]})
return true
elseif sub_id == cmd_define.sub_fight_result_req then
self:send_event(cmd_define.main_game, cmd_define.sub_fight_result_rsp, {})
return true
end
return false
end
return game_server
|
local ffi = require "ffi"
local ffi_cdef = ffi.cdef
ffi_cdef[[
int __cdecl xlSheetCellTypeA(SheetHandle handle, int row, int col);
int __cdecl xlSheetIsFormulaA(SheetHandle handle, int row, int col);
FormatHandle __cdecl xlSheetCellFormatA(SheetHandle handle, int row, int col);
void __cdecl xlSheetSetCellFormatA(SheetHandle handle, int row, int col, FormatHandle format);
const char* __cdecl xlSheetReadStrA(SheetHandle handle, int row, int col, FormatHandle* format);
int __cdecl xlSheetWriteStrA(SheetHandle handle, int row, int col, const char* value, FormatHandle format);
double __cdecl xlSheetReadNumA(SheetHandle handle, int row, int col, FormatHandle* format);
int __cdecl xlSheetWriteNumA(SheetHandle handle, int row, int col, double value, FormatHandle format);
int __cdecl xlSheetReadBoolA(SheetHandle handle, int row, int col, FormatHandle* format);
int __cdecl xlSheetWriteBoolA(SheetHandle handle, int row, int col, int value, FormatHandle format);
int __cdecl xlSheetReadBlankA(SheetHandle handle, int row, int col, FormatHandle* format);
int __cdecl xlSheetWriteBlankA(SheetHandle handle, int row, int col, FormatHandle format);
const char* __cdecl xlSheetReadFormulaA(SheetHandle handle, int row, int col, FormatHandle* format);
int __cdecl xlSheetWriteFormulaA(SheetHandle handle, int row, int col, const char* value, FormatHandle format);
const char* __cdecl xlSheetReadCommentA(SheetHandle handle, int row, int col);
void __cdecl xlSheetWriteCommentA(SheetHandle handle, int row, int col, const char* value, const char* author, int width, int height);
int __cdecl xlSheetIsDateA(SheetHandle handle, int row, int col);
int __cdecl xlSheetReadErrorA(SheetHandle handle, int row, int col);
double __cdecl xlSheetColWidthA(SheetHandle handle, int col);
double __cdecl xlSheetRowHeightA(SheetHandle handle, int row);
int __cdecl xlSheetSetColA(SheetHandle handle, int colFirst, int colLast, double width, FormatHandle format, int hidden);
int __cdecl xlSheetSetRowA(SheetHandle handle, int row, double height, FormatHandle format, int hidden);
int __cdecl xlSheetRowHiddenA(SheetHandle handle, int row);
int __cdecl xlSheetSetRowHiddenA(SheetHandle handle, int row, int hidden);
int __cdecl xlSheetColHiddenA(SheetHandle handle, int col);
int __cdecl xlSheetSetColHiddenA(SheetHandle handle, int col, int hidden);
int __cdecl xlSheetGetMergeA(SheetHandle handle, int row, int col, int* rowFirst, int* rowLast, int* colFirst, int* colLast);
int __cdecl xlSheetSetMergeA(SheetHandle handle, int rowFirst, int rowLast, int colFirst, int colLast);
int __cdecl xlSheetDelMergeA(SheetHandle handle, int row, int col);
int __cdecl xlSheetMergeSizeA(SheetHandle handle);
int __cdecl xlSheetMergeA(SheetHandle handle, int index, int* rowFirst, int* rowLast, int* colFirst, int* colLast);
int __cdecl xlSheetDelMergeByIndexA(SheetHandle handle, int index);
int __cdecl xlSheetPictureSizeA(SheetHandle handle);
int __cdecl xlSheetGetPictureA(SheetHandle handle, int index, int* rowTop, int* colLeft, int* rowBottom, int* colRight,
int* width, int* height, int* offset_x, int* offset_y);
void __cdecl xlSheetSetPictureA(SheetHandle handle, int row, int col, int pictureId, double scale, int offset_x, int offset_y);
void __cdecl xlSheetSetPicture2A(SheetHandle handle, int row, int col, int pictureId, int width, int height, int offset_x, int offset_y);
int __cdecl xlSheetGetHorPageBreakA(SheetHandle handle, int index);
int __cdecl xlSheetGetHorPageBreakSizeA(SheetHandle handle);
int __cdecl xlSheetGetVerPageBreakA(SheetHandle handle, int index);
int __cdecl xlSheetGetVerPageBreakSizeA(SheetHandle handle);
int __cdecl xlSheetSetHorPageBreakA(SheetHandle handle, int row, int pageBreak);
int __cdecl xlSheetSetVerPageBreakA(SheetHandle handle, int col, int pageBreak);
void __cdecl xlSheetSplitA(SheetHandle handle, int row, int col);
int __cdecl xlSheetSplitInfoA(SheetHandle handle, int* row, int* col);
int __cdecl xlSheetGroupRowsA(SheetHandle handle, int rowFirst, int rowLast, int collapsed);
int __cdecl xlSheetGroupColsA(SheetHandle handle, int colFirst, int colLast, int collapsed);
int __cdecl xlSheetGroupSummaryBelowA(SheetHandle handle);
void __cdecl xlSheetSetGroupSummaryBelowA(SheetHandle handle, int below);
int __cdecl xlSheetGroupSummaryRightA(SheetHandle handle);
void __cdecl xlSheetSetGroupSummaryRightA(SheetHandle handle, int right);
void __cdecl xlSheetClearA(SheetHandle handle, int rowFirst, int rowLast, int colFirst, int colLast);
int __cdecl xlSheetInsertColA(SheetHandle handle, int colFirst, int colLast);
int __cdecl xlSheetInsertRowA(SheetHandle handle, int rowFirst, int rowLast);
int __cdecl xlSheetRemoveColA(SheetHandle handle, int colFirst, int colLast);
int __cdecl xlSheetRemoveRowA(SheetHandle handle, int rowFirst, int rowLast);
int __cdecl xlSheetCopyCellA(SheetHandle handle, int rowSrc, int colSrc, int rowDst, int colDst);
int __cdecl xlSheetFirstRowA(SheetHandle handle);
int __cdecl xlSheetLastRowA(SheetHandle handle);
int __cdecl xlSheetFirstColA(SheetHandle handle);
int __cdecl xlSheetLastColA(SheetHandle handle);
int __cdecl xlSheetDisplayGridlinesA(SheetHandle handle);
void __cdecl xlSheetSetDisplayGridlinesA(SheetHandle handle, int show);
int __cdecl xlSheetPrintGridlinesA(SheetHandle handle);
void __cdecl xlSheetSetPrintGridlinesA(SheetHandle handle, int print);
int __cdecl xlSheetZoomA(SheetHandle handle);
void __cdecl xlSheetSetZoomA(SheetHandle handle, int zoom);
int __cdecl xlSheetPrintZoomA(SheetHandle handle);
void __cdecl xlSheetSetPrintZoomA(SheetHandle handle, int zoom);
int __cdecl xlSheetGetPrintFitA(SheetHandle handle, int* wPages, int* hPages);
void __cdecl xlSheetSetPrintFitA(SheetHandle handle, int wPages, int hPages);
int __cdecl xlSheetLandscapeA(SheetHandle handle);
void __cdecl xlSheetSetLandscapeA(SheetHandle handle, int landscape);
int __cdecl xlSheetPaperA(SheetHandle handle);
void __cdecl xlSheetSetPaperA(SheetHandle handle, int paper);
const char* __cdecl xlSheetHeaderA(SheetHandle handle);
int __cdecl xlSheetSetHeaderA(SheetHandle handle, const char* header, double margin);
double __cdecl xlSheetHeaderMarginA(SheetHandle handle);
const char* __cdecl xlSheetFooterA(SheetHandle handle);
int __cdecl xlSheetSetFooterA(SheetHandle handle, const char* footer, double margin);
double __cdecl xlSheetFooterMarginA(SheetHandle handle);
int __cdecl xlSheetHCenterA(SheetHandle handle);
void __cdecl xlSheetSetHCenterA(SheetHandle handle, int hCenter);
int __cdecl xlSheetVCenterA(SheetHandle handle);
void __cdecl xlSheetSetVCenterA(SheetHandle handle, int vCenter);
double __cdecl xlSheetMarginLeftA(SheetHandle handle);
void __cdecl xlSheetSetMarginLeftA(SheetHandle handle, double margin);
double __cdecl xlSheetMarginRightA(SheetHandle handle);
void __cdecl xlSheetSetMarginRightA(SheetHandle handle, double margin);
double __cdecl xlSheetMarginTopA(SheetHandle handle);
void __cdecl xlSheetSetMarginTopA(SheetHandle handle, double margin);
double __cdecl xlSheetMarginBottomA(SheetHandle handle);
void __cdecl xlSheetSetMarginBottomA(SheetHandle handle, double margin);
int __cdecl xlSheetPrintRowColA(SheetHandle handle);
void __cdecl xlSheetSetPrintRowColA(SheetHandle handle, int print);
int __cdecl xlSheetPrintRepeatRowsA(SheetHandle handle, int* rowFirst, int* rowLast);
void __cdecl xlSheetSetPrintRepeatRowsA(SheetHandle handle, int rowFirst, int rowLast);
int __cdecl xlSheetPrintRepeatColsA(SheetHandle handle, int* colFirst, int* colLast);
void __cdecl xlSheetSetPrintRepeatColsA(SheetHandle handle, int colFirst, int colLast);
int __cdecl xlSheetPrintAreaA(SheetHandle handle, int* rowFirst, int* rowLast, int* colFirst, int* colLast);
void __cdecl xlSheetSetPrintAreaA(SheetHandle handle, int rowFirst, int rowLast, int colFirst, int colLast);
void __cdecl xlSheetClearPrintRepeatsA(SheetHandle handle);
void __cdecl xlSheetClearPrintAreaA(SheetHandle handle);
int __cdecl xlSheetGetNamedRangeA(SheetHandle handle, const char* name, int* rowFirst, int* rowLast, int* colFirst, int* colLast, int scopeId, int* hidden);
int __cdecl xlSheetSetNamedRangeA(SheetHandle handle, const char* name, int rowFirst, int rowLast, int colFirst, int colLast, int scopeId);
int __cdecl xlSheetDelNamedRangeA(SheetHandle handle, const char* name, int scopeId);
int __cdecl xlSheetNamedRangeSizeA(SheetHandle handle);
const char* __cdecl xlSheetNamedRangeA(SheetHandle handle, int index, int* rowFirst, int* rowLast, int* colFirst, int* colLast, int* scopeId, int* hidden);
int __cdecl xlSheetHyperlinkSizeA(SheetHandle handle);
const char* __cdecl xlSheetHyperlinkA(SheetHandle handle, int index, int* rowFirst, int* rowLast, int* colFirst, int* colLast);
int __cdecl xlSheetDelHyperlinkA(SheetHandle handle, int index);
void __cdecl xlSheetAddHyperlinkA(SheetHandle handle, const char* hyperlink, int rowFirst, int rowLast, int colFirst, int colLast);
const char* __cdecl xlSheetNameA(SheetHandle handle);
void __cdecl xlSheetSetNameA(SheetHandle handle, const char* name);
int __cdecl xlSheetProtectA(SheetHandle handle);
void __cdecl xlSheetSetProtectA(SheetHandle handle, int protect);
int __cdecl xlSheetHiddenA(SheetHandle handle);
int __cdecl xlSheetSetHiddenA(SheetHandle handle, int hidden);
void __cdecl xlSheetGetTopLeftViewA(SheetHandle handle, int* row, int* col);
void __cdecl xlSheetSetTopLeftViewA(SheetHandle handle, int row, int col);
int __cdecl xlSheetRightToLeftA(SheetHandle handle);
void __cdecl xlSheetSetRightToLeftA(SheetHandle handle, int rightToLeft);
void __cdecl xlSheetSetAutoFitAreaA(SheetHandle handle, int rowFirst, int colFirst, int rowLast, int colLast);
void __cdecl xlSheetAddrToRowColA(SheetHandle handle, const char* addr, int* row, int* col, int* rowRelative, int* colRelative);
const char* __cdecl xlSheetRowColToAddrA(SheetHandle handle, int row, int col, int rowRelative, int colRelative);
]]
|
--[[
BloxStore module for integrating BloxStore into Roblox games.
Getting started:
1. Sign up for a BloxStore account by going to https://bloxstore.whats-in.space
2. Create a table
3. Add some columns
4. Put this script into a ModuleScript and require() it
5. Using the API you can integrate your game into BloxStore
Important Notes:
- Do NOT interface with BloxStore on the client-side, doing so can leave your table open to exploiters
- When running a SQL statement, replace the name of the table with %table% for the statement to work
Created by: CoreDev
Website: https://bloxstore.whats-in.space
--]]
local BloxStore = {}
local httpService = game:GetService("HttpService")
local defaultTableKey = ""
local debugMode = false
--[[
@description Encodes the data to be sent in the POST request
@param data: The table of data
@returns string: The data that is encoded for POST requests
--]]
function BloxStore:buildQuery(data)
local built = ""
for key, value in pairs(data) do
if built ~= "" then
built = built .. "&"
end
built = built .. key .. "=" .. value
end
return built
end
--[[
@description Sets the default table key for the runSQL function
@param tableKey: The table key
--]]
function BloxStore:setTableKey(tableKey)
defaultTableKey = tableKey
if debugMode then
local i = 0
local censored = ""
while string.len(tableKey) > i do
i = i + 1
if (string.len(tableKey) - 5) < i then
censored = censored .. string.sub(tableKey, i, i)
else
censored = censored .. "*"
end
end
print("BloxStore: Setting default table key to: " .. censored)
end
end
--[[
@description Used to set the debug mode which prints out useful information to the console
@param value: A boolean for wether or not debug should be enable
--]]
function BloxStore:setDebugMode(value)
if value == true or value == false then
debugMode = value
if debugMode then
print("BloxStore: Enabling debug mode.")
else
print("BloxStore: Disabling debug mode.")
end
end
end
--[[
@description Sends a POST request to the BloxStore API
@param path: The path starting with / with the endpoint
@param requestData: The encoded post data
@returns table: The JSON response from the API decoded
--]]
function BloxStore:sendApiRequest(path, requestData)
local response = httpService:PostAsync(
"https://bloxstore.whats-in.space/api/v1" .. path,
BloxStore:buildQuery(requestData),
Enum.HttpContentType.ApplicationUrlEncoded
)
if debugMode then
print("BloxStore: Response received from the API: " .. response)
end
return httpService:JSONDecode(response)
end
--[[
@description Runs an SQL statement on the table
@param tableKey: (Optional) The table key for the table to run the statement on
@param query: The SQL statement to run on the API
@returns table: The JSON response from the API decoded
--]]
function BloxStore:runSQL(...)
local args = {...}
if #args == 1 then
local query = args[1]
if debugMode then
print("BloxStore: Running \"" .. query .. "\" on the table.")
end
return BloxStore:sendApiRequest("/sql", {
tablekey = defaultTableKey,
query = query
})
elseif #args == 2 then
local tableKey = args[1]
local query = args[2]
if debugMode then
print("BloxStore: Running \"" .. query .. "\" on the table.")
end
return BloxStore:sendApiRequest("/sql", {
tablekey = tableKey,
query = query
})
end
end
--[[
@description Runs an SQL prepared statement on the table
@param tableKey: (Optional) The table key for the table to run the statement on
@param query: The SQL statement to run on the API
@param values: The values in a table for the prepared statement
@returns table: The JSON response from the API decoded
--]]
function BloxStore:runPreparedSQL(...)
local args = {...}
if #args == 2 then
local query = args[1]
local values = args[2]
if debugMode then
print("BloxStore: Running \"" .. query .. "\" on the table with values: " .. httpService:JSONEncode(values))
end
return BloxStore:sendApiRequest("/sql", {
tablekey = defaultTableKey,
query = query,
values = httpService:JSONEncode(values)
})
elseif #args == 3 then
local tableKey = args[1]
local query = args[2]
local values = args[3]
if debugMode then
print("BloxStore: Running \"" .. query .. "\" on the table with values: " .. httpService:JSONEncode(values))
end
return BloxStore:sendApiRequest("/sql", {
tablekey = tableKey,
query = query,
values = httpService:JSONEncode(values)
})
end
end
return BloxStore
|
--[[
BUT DU JEU
Pour les Villageois: éliminer les Loups-Garous
Pour les Loups-Garous: éliminer les Villageois
LES PERSONNAGES
Les Loups-Garous:
Chaque nuit, ils dévorent un Villageois. Le jour ils essaient de masquer leur identité nocturne pour échapper à la vindicte populaire. Ils sont 1, 2, 3 ou 4 suivant le nombre de joueurs et les variantes appliquées.
Les Villageois (tous ceux qui ne sont pas Loups-Garous):
Chaque nuit, l'un d'entre eux est dévoré par les Loups-Garous. Ce joueur est éliminé du jeu.
Les Villageois survivant se réunissent le lendemain matin et essaient de remarquer , chez les autres joueurs, les signes qui trahiraient leur identité nocturne de mangeur d'homme. Après discussion, ils votent l'éxécution d'un suspect qui sera éliminé du jeu.
Le simple Villageois:
Il n'a aucune compétence particulière. Ses seules armes sont la capacité d'analyse des comportements pour identifier les Loups Garous et la force de conviction pour empêcher l'exécution de l'innocent qu'il est.
La voyante:
Chaque nuit, elle découvre la vraie personnalité d'un joueur de son choix.
Elle doit aider les autres villageois, mais rester discrète pour ne pas être démasquée par les Loups-garous.
Le Chasseur:
S'il se fait dévorer par les Loups Garous ou exécuter malencontreusement par les joueurs, le Chasseur a le pouvoir de répliquer avant de rendre l'âme, en éliminant immédiatement n'importe quel autre joueur de son choix.
Cupidon:
En décochant ses célèbres flèches magique, Cupidon a le pouvoir de rendre 2 personnes amoureuses à jamais.
La première nuit (tour préliminaire), il désigne les 2 joueurs (ou joueuses ou 1 joueur et 1 joueuse) amoureux. Cupidon peut, s'il le veut, se désigner comme l'un des Amoureux.
Si l'un des amoureux est éliminé, l'autre meurt de chagrin immédiatement. Un Amoureux ne doit jamais voter contre son aimé (même pour faire semblant !)
Attention: Si l'un des deux Amoureux est un Loup-Garou et l'autre un Villageois, le but de la partie change pour eux. Pour vivre en paix leur amour et gagner la partie, ils doivent éliminer tous les autres joueurs , Loups-Garous et Villageois, en respectant les règles du jeu.
La Sorcière:
Elle sait concocter 2 potions extrèmement puissantes:
Une potion de guérison, pour ressusciter le joueur tué par les Loups-Garous, une potion d'empoisonnement, utilisée la nuit pour éliminer un joueur. La sorcière ne peut utiliser chaque potion qu'une seule fois dans la partie. Elle peut se servir de ses 2 potions dans la même nuit. Le matin suivant il pourra, suivant l'usage de ce pouvoir, y avoir 0 mort, 1 mort ou 2 morts. La sorcière peut utiliser les potions à son profit, et donc se guérir elle-même.
Si au bout d'un certain nombre de parties, vous trouvez ce personnage trop puissant, limitez ses pouvoirs à une seule potion pour la partie.
La Petite Fille:
La Petite Fille peut, en entrouvrant les yeux, espionner les Loups Garous pendant leur réveil. Si elle se fait surprendre par un des Loups-Garous, elle meurt immédiatement (en silence), à la place de la victime désignée. Le Petite Fille ne peut espionner que la nuit, durant le tour d'éveil des Loups-Garous.
Le Capitaine:
Cette carte est confiée à un des joueurs, en plus de se carte de personnage.
Le Capitaine est élu par vote, à la majorité relative.
On ne peut refuser l'honneur d'être capitaine.
Dorénavant, les votes de ce joueur comptent pour 2 voix.
Si ce joueur se fait éliminer, dans son dernier souffle il désigne son successeur.
Le Voleur:
Si on veut jouer le Voleur, il faut ajouter deux cartes Simples Villageois en plus de toutes celles déja choisies.
Après disttribution, les deux cartes non distribuées sont placées au centre de la table face cachée.
La première nuit, le voleur pourra prendre connaissance de ses deux cartes, et échanger sa carte contre l'une des deux autres.
Si ces deux cartes sont des Loups Garous, il est obligé d'échanger sa carte contre un des deux Loups Garous.
Il jouera désormais ce personnage jusqu'à la fin de la partie.
Distribution des personnages pour parties simplifiées
2 Loups-garous (ou plus selon le nombre de joueur)
La voyante
Les simples Villageois (en nombre suffisant)
TOURS DE JEU
MISE EN PLACE
Les joueurs désignent ou tirent au sort un meneur de jeu qui ne joue pas, mais dirige la partie. Pour les premières parties, quelqu'un qui connaît bien le jeu ou celui qui a déchiffré la règle ou un habile meneur de groupe sera le plus à même de restituer la meilleure ambiance.
Le meneur de jeu distribue à chaque joueur 1 carte personnage face cachée. Chaque joueur regarde discrètement son personnage, puis repose sa carte face cachée devant lui.
Le meneur endort le village.
Le meneur dit: "C'est la nuit tout le village s'endort, les joueurs ferment les yeux".
Tous les joueurs baissent la tête et ferment les yeux. Puis selon le choix des personnages en jeu, le meneur appelle les différents personnages.
TOUR DE PRÉPARATION (sauf parties simplifiées)
- Le meneur appelle le Voleur:
Le meneur dit: "le Voleur se réveille !". Le joueur qui possède la carte Voleur, ouvre les yeux et regarde discrètement les deux cartes cachées au milieu, puis change éventuellement de personnage.
Le meneur dit : "Le Voleur se rendort". Le Voleur referme les yeux.
- Le meneur appelle Cupidon
Le meneur dit: "Cupidon se réveille !". Cupidon ouvre les yeux et désigne deux joueurs (dont éventuellement lui-même). Le meneur fait le tour de la table et touche discrètement le dos des deux Amoureux.
Le meneur dit: "Cupidon se rendort". Cupidon referme les yeux.
- Le meneur appelle les Amoureux
Le meneur dit: "les Amoureux se réveillent, se reconnaissent, et se rendorment !".
Ils ne se montrent pas leur carte de sorte que chacun ignore la véritable personnalité de l'être aimé.
Puis le meneur suit le tour normal.
TOUR NORMAL
II varie selon le choix des personnages en jeu et leur survie dans la partie, mais les personnages sont toujours appelés dans l'ordre suivant:
1 - Le meneur appelle la Voyante.
Le meneur dit: "la Voyante se réveille, et désigne un joueur dont elle veut sonder la véritable personnalité !".
Le meneur montre à la Voyante la face cachée de la carte du joueur que la Voyante a désigné.
Le meneur dit: "La Voyante se rendort". La Voyante referme les yeux.
2 - Le meneur appelle les Loups-Garous
Le meneur dit: "les Loups-Carous se réveillent, se reconnaissent et désignent une nouvelle victime !!!".
Les Loups-Garous (et eux seulement) lèvent la tête, ouvrent les yeux, se concertent silencieusement et désignent une victime. Durant ce tour, la Petite Fille peut espionner les Loups-Garous (en entrouvrant les yeux discrètement). Elle n'y est pas obligée.
Si elle se fait prendre, les Loups-Garous ont le droit de changer d'avis et elle meurt à la place de la victime éventuellement choisie.
Le meneur dit: "les Loups-Garous repus se rendorment et rêvent de prochaines victimes savoureuses !".
Les Loups-Garous ferment les yeux.
3 - Le meneur appelle la Sorcière
Le meneur dit: "la Sorcière se réveille, je lui montre la victime des Loups-Garous. Va-t-elle user de sa potion de guérison, ou d'empoisonnement ?"
Le meneur montre à la Sorcière la victime des Loups-Garous. La Sorcière n'est pas obligée d'user de son pouvoir à un tour spécifique.
Si elle utilise une potion, elle doit désigner au meneur sa cible avec le pouce tendu vers le haut pour la guérison, ou vers le bas pour I'empoisonnement.
Le meneur révélera son effet éventuel le matin suivant.
4 - Le meneur réveille tout le village.
Le meneur dit: "c'est le matin, le village se réveille, tout le monde se réveille et ouvre les yeux, tout le monde sauf..."
Le meneur désigne alors le ou les joueurs qui ont été Victimes des Loups-Garous ou de la Sorcière durant la nuit.
Ce ou ces joueurs révèlent leur carte car ils sont éliminés du jeu. Il ne pourront plus communiquer avec les autres joueurs de quelque manière que ce soit. Si un de ces joueurs est le Chasseur, il a le droit de répliquer et de tuer immédiatement un autre joueur de son choix.
Si un des joueurs est un des deux Amoureux, l'autre Amoureux meurt de chagrin immédiatement.
Si un des joueurs est le Capitaine, il désigne son successeur.
5 - Le village débat des suspects.
Le meneur anime et relance les débats.
Un bruit suspect pendant la nuit, un comportement bizarre par rapport à un autre joueur, ou une façon de voter toujours identique de certains villageois: voici des exemples d'indices qui peuvent laisser suspecter certains joueurs d'être Loups-Garous.
Au cours de cette phase il ne faut pas perdre de vue que les objectifs de chacun sont différents:
- Chaque Villageois tente de démasquer un Loup-Garou et de faire voter contre lui.
- Les Loups-Garous doivent se faire passer pour des villageois.
- La Voyante ainsi que la Petite Fille doivent aider les autres Villageois, mais sans mettre trop tôt leur vie en danger en exposant leur identité.
- Les Amoureux doivent se protéger l'un l'autre.
Chacun a le droit de se faire passer pour un autre. Cette phase est le cœur du jeu. Faites briller vos talents de tribun, bluffez ou dites la vérité, mais soyez toujours crédible.
Croyez-nous, on finit toujours par se dévoiler d'une façon ou d'une autre, et les soupçons finissent toujours par tomber juste. Enfin, presque toujours !
6 - Le village vote.
Les joueurs doivent éliminer un joueur suspecté d'être un Loup-Garou.
Au signal du meneur, chaque joueur pointe son doigt dans la direction du joueur qu'il souhaite éliminer. Le joueur qui a la majorité des voix est éliminé. N'oubliez pas que la voix du Capitaine compte double.
En cas d'égalité, s'il est présent, le vote du Capitaine désigne la victime. Sinon, les joueurs votent à nouveau (y compris les joueurs en cause) pour départager les ex-aequo.
S'il y a toujours égalité, aucun joueur n'est éliminé.
Le joueur éliminé révèle sa carte et ne pourra plus communiquer avec les autres joueurs d'aucune manière.
7 - Le village S'endort
Le meneur dit : "c'est la nuit, les survivants se rendorment !",
les joueurs referment les yeux. (Les joueurs éliminés se taisent, surtout quand ils découvrent qui sont vraiment les Loups-Garous...). Le jeu reprend au début du tour normal, étape 1.
CONDITIONS DE VICTOIRE
Les Villageois gagnent dès qu'ils réussissent à éliminer le dernier Loup-Garou.
Les Loups Garous gagnent s'ils éliminent le dernier des villageois.
Cas particulier:
si les Amoureux sont 1 Loup-Garou + 1 Villageois, ils gagnent dès qu'ils ont éliminé tous les autres.
CONSEILS AU MENEUR
Votre rôle est fondamental: de votre talent dépend l'ambiance du jeu. Grâce à vous les joueurs vont passer un bon moment. N'hésitez pas à créer une atmosphère d'angoisse. Installez un suspense quand vous révélez les victimes des Loups-Garous. N'hésitez pas à relancer les débats s'ils s'épuisent.
Les phrases d'appel nocturne des personnages vous sont données en exemple. Quand vous aurez bien maîtrisé la technique, laissez-vous aller à un délire plus personnel.
Avec des joueurs expérimentés, même si vous n'êtes pas très nombreux, n'hésitez pas à utiliser les villageois avec des pouvoirs spéciaux, cela ajoute de l'intérêt aux parties.
Avec des joueurs débutants introduisez progressivement les autres cartes personnages.
L'essentiel du plaisir est dans l'ambiance.
Les parties sont relativement courtes, faites-en plusieurs dans la même soirée et variez les personnages.
Points de procédures importants:
- Lorsque vous parlez, faites très attention à ne pas laisser passer d'indices sur l'identité des personnages, ex: "j'appelle le Voyant... heu, pardon, la Voyante"
- La nuit, quand vous vous adressez aux personnages appelés, ne dirigez pas votre voix uniquement vers eux, les joueurs pourraient en déduire leur position !
- Si les Loups-Garous n'arrivent pas à se décider, tant pis pour eux, il n'y aura pas de mort cette nuit là.
- Si on joue la Petite Fille, les joueurs ne doivent pas baisser la tête, ni mettre les mains devant les yeux.
- Lorsque la Voyante espionne, feignez de retourner les cartes de tous les joueurs.
- Faites le tour complet de la table pour désigner les Amoureux.
- Vous pouvez attendre quelques tours avant de mettre aux voix le poste de Capitaine, le temps que les joueurs se fassent une opinion sur leurs congénères.
CONSEILS AUX JOUEURS
Les Loups-Garous: un stratagème efficace pour se dédouaner d'une accusation, est de voter contre son partenaire. Encore faut-il que les Villageois le remarquent.
La Voyante: attention, si vous avez découvert un Loup-Garou, cela vaut peut-être la peine de vous dévoiler pour accuser le joueur, mais pas trop tôt !
La Petite Fille: personnage très puissant, mais très angoissant à jouer. N'hésitez pas à espionner! Cela fait peur mais il faut en profiter rapidement avant d'être éliminé.
Le Chasseur: II est toujours bon en cas d'accusation de se faire passer pour le Chasseur.
Cupidon: si vous vous désignez comme un des Amoureux, ne choisissez pas comme partenaire une trop "grande gueule".Le Capitaine: n'hésitez pas à vous présenter au poste de Capitaine, faites votre campagne. Mais si vous êtes Loup-Garou, ne soyez pas trop ouvertement candidat à ce poste. Soyez fier de ce poste, accrochez la carte au revers de votre vêtement.
La Sorcière: ce personnage devient plus puissant en fin de partie, ne gaspillez pas vos sorts.
--]]
if not WereWolf.IsCorrectVersion() then
return
end
local L = WereWolf.L
local WereWolf = WereWolf
local Comm = WereWolf.Comm
local players = WereWolf.players
local UnitGUID, UnitClass = UnitGUID, UnitClass
local stereotypes = {
-- add notion for lover and remove the role
-- werewolf can be lovers
werewolf = {
Class = L["Werewolf"],
Name = L["Werewolf"],
Icon = 132224,
Tips = L["Just kill"],
Goal = L["Kill every peon"],
},
peon = {
Class = L["Peon"],
Name = L["Peon"],
Icon = 132275,
Tips = L["Just survive"],
Goal = L["Survive to werewolf attacks"],
},
special = {
hunter = {
Class = L["Peon"],
Name = L["Hunter"],
Icon = 132217,
Tips = L["Can point a player to come with him into death"],
Goal = L["Survive to werewolf attacks"],
isApplyed = false,
},
caty = {
Class = L["Peon"],
Name = L["Cathy"],
Icon = 132311,
Tips = L["Can spy the werewolf during night. Beware! do not be catch or you will be immediatly dead!"],
Goal = L["Spy and survive to werewolf attacks"],
isApplyed = false,
},
witch = {
Class = L["Peon"],
Name = L["Witch"],
Icon = 132378,
Tips = L["Can concoct poisonous or healing potion"],
Goal = L["Survive to werewolf attacks"],
isApplyed = false,
},
captain = {
Class = L["Peon"],
Name = L["Captain"],
Icon = 132341,
Tips = L["Vote count double. On death, point another player to become the new captain."],
Goal = L["Survive to werewolf attacks"],
isApplyed = false,
},
cupidon = {
Class = L["Peon"],
Name = L["Cupid"],
Icon = 134131,
Tips = L["Point two players to become the lovers"],
Goal = L["Survive to werewolf attacks"],
isApplyed = false,
},
rogue = {
Class = L["Peon"],
Name = L["Rogue"],
Icon = 132320,
Tips = L["During the first night, can choose its new role among two roles"],
Goal = L["Survive to werewolf attacks"],
isApplyed = false,
}
},
seer = {
Class = L["Peon"],
Name = L["Seer"],
Icon = 132327,
Tips = L["Each night, can discover the true nature of players"],
Goal = L["Survive to werewolf attacks"],
},
gamemaster = {
Class = L["Game Master"],
Name = L["Game Master"],
Icon = 133073,
Tips = L["You are the game master"],
Goal = L["Manage the game!"],
}
};
function WereWolf.IsPlayerKnown(playerName)
for key, value in pairs(players) do
if value.Name == playerName then
return true
end
end
return false
end
function WereWolf.AddPlayer(playerName)
if (not (IsPlayerKnown(playerName))) then
local player = {
id = UnitGUID(playerName),
Name = playerName,
Class = select(2, UnitClass(playerName)),
Role = nil,
hasVoted = false,
isAlive = true,
isLover = false
}
table.insert(players, player)
else
-- player is already known
WereWolf.prettyPrint("Player " .. playerName .. " has already joined the game")
end
end
function WereWolf.RemovePlayer(playerName)
local playerPos
for key, value in pairs(players) do
if value.Name == playerName then
playerPos = key
break
end
end
if playerPos then
table.remove(players, playerPos)
end
end
--[[
Nombre de joueurs | Loups-Garous | Voyante | Villageois
8 | 2 | 1 | 5 -> 2 speciaux
9 | 2 | 1 | 6 -> 3 speciaux
10 | 2 | 1 | 7 -> 3 speciaux
11 | 2 | 1 | 8 -> 4 speciaux
12 | 3 | 1 | 8 -> 4 speciaux
13 | 3 | 1 | 9 -> 4 speciaux
14 | 3 | 1 | 10 -> 5 speciaux
15 | 3 | 1 | 11 -> 5 speciaux
16 | 3 | 1 | 12 -> 6 speciaux
17 | 3 | 1 | 13 -> 6 speciaux
18 | 4 | 1 | 13 -> 6 speciaux --]]
local peonNumber = 0;
local specialPeonNumber = 0;
local werewolfNumber = 0;
local seerApplyed = false;
local isSetupStep = false;
function WereWolf.NextStep()
if WereWolf.currentStep == "" or WereWolf.currentStep == "Vote" then
WereWolf.SetNight()
else
if isSetupStep then
if WereWolf.currentStep == "Night" then
WereWolf.WakeUpRogue()
elseif WereWolf.currentStep == "Rogue" then
WereWolf.WakeUpCupid()
elseif WereWolf.currentStep == "Cupid" then
WereWolf.WakeUpLovers()
elseif WereWolf.currentStep == "Lovers" then
WereWolf.WakeUpSeer()
end
else
if WereWolf.CanContinue() then
if WereWolf.currentStep == "Night" then
WereWolf.WakeUpSeer()
elseif WereWolf.currentStep == "Seer" then
WereWolf.WakeUpWerewolves()
elseif WereWolf.currentStep == "Werewolves" then
WereWolf.WakeUpWitch()
elseif WereWolf.currentStep == "Witch" then
WereWolf.SetDay()
elseif WereWolf.currentStep == "Day" then
WereWolf.Vote()
end
else
WereWolf.GameEnds()
end
end
end
end
function WereWolf.Reset()
for key, value in pairs(players) do
value.isAlive = true
end
for key, value in pairs(stereotypes.special) do
value.isApplyed = false
end
for key, value in pairs(players) do
value.Role = nil
end
seerApplyed = false
peonNumber = 0
specialPeonNumber = 0
werewolfNumber = 0
WereWolf.currentStep = ""
isSetupStep = true
end
function WereWolf.SendPlayerTable()
for _, value in pairs(players) do
if value.id ~= WereWolf.me.id then
Comm:SendCommand(value.Name, "add_player", value)
end
end
end
function WereWolf.StartAsPlayer()
WereWolf.Reset()
WereWolf.SetRoleToAllPlayer()
WereWolf.SendRoleToAllPlayer()
end
function WereWolf.GameEnds()
local alivePeon = 0
local aliveWerewolf = 0
local msg = L["win"]
for key, value in pairs(players) do
if value.isAlive == true then
if value.Role.Class == L["Peon"] then
alivePeon = alivePeon + 1
elseif value.Role.Class == L["Werewolf"] then
aliveWerewolf = aliveWerewolf + 1
else
WereWolf.printDebug("unknown role : "..value.Role.Class)
end
end
end
if alivePeon == 0 and aliveWerewolf > 0 then
msg = L["Werewolves"].." "..msg.."!"
elseif alivePeon > 0 and aliveWerewolf == 0 then
msg = L["Peons"].." "..msg.."!"
end
for key, value in pairs(players) do
Comm:SendCommand(value.Name, "game_ends", msg)
end
end
function WereWolf.CanContinue()
local ret = true
if(WereWolf.isDevVersion) then
return false
end
--[[
CONDITIONS DE VICTOIRE
Les Villageois gagnent dès qu'ils réussissent à éliminer le dernier Loup-Garou.
Les Loups Garous gagnent s'ils éliminent le dernier des villageois.
Cas particulier:
si les Amoureux sont 1 Loup-Garou + 1 Villageois, ils gagnent dès qu'ils ont éliminé tous les autres.
--]]
local werewolfcount = 0
local peoncount = 0
for key, value in pairs(players) do
if value.isAlive then
if value.Role.class == L["Werewolf"] then
werewolfcount = werewolfcount + 1
elseif value.Role.class == L["Peon"] then
peoncount = peoncount + 1
end
end
end
if werewolfcount > 0 and peoncount == 0 then
ret = false
elseif werewolfcount == 0 and peoncount > 0 then
ret = false
end
return ret
end
function WereWolf.SendRoleToAllPlayer()
for _, value in pairs(players) do
if value.id ~= WereWolf.me.id then
Comm:SendCommand(value.Name, "player_role", value.Role)
end
end
end
function WereWolf.SetNight()
WereWolf.currentStep = "Night"
WereWolf.prettyPrint(L["The night fall on the village and everyone fells asleep"])
for key, value in pairs(players) do
if(value.Role and value.Role.Class ~= L["Game Master"]) then
Comm:SendCommand(value.Name, "set_night")
end
end
end
function WereWolf.SetDay()
--[[
4 - Le meneur réveille tout le village.
Le meneur dit: "c'est le matin, le village se réveille, tout le monde se réveille et ouvre les yeux, tout le monde sauf..."
Le meneur désigne alors le ou les joueurs qui ont été Victimes des Loups-Garous ou de la Sorcière durant la nuit.
Ce ou ces joueurs révèlent leur carte car ils sont éliminés du jeu.
Il ne pourront plus communiquer avec les autres joueurs de quelque manière que ce soit.
Si un de ces joueurs est le Chasseur, il a le droit de répliquer et de tuer immédiatement un autre joueur de son choix.
Si un des joueurs est un des deux Amoureux, l'autre Amoureux meurt de chagrin immédiatement.
Si un des joueurs est le Capitaine, il désigne son successeur.
--]]
WereWolf.currentStep = "Day"
isSetupStep = false
WereWolf.prettyPrint(L["The day rises again with its shinny sun and its grim discovery..."])
for key, value in pairs(players) do
if(value.Role.Class ~= L["Game Master"]) then
Comm:SendCommand(value.Name, "set_day")
end
end
end
function WereWolf.Vote()
--[[
6 - Le village vote.
Les joueurs doivent éliminer un joueur suspecté d'être un Loup-Garou.
Au signal du meneur, chaque joueur pointe son doigt dans la direction du joueur qu'il souhaite éliminer.
Le joueur qui a la majorité des voix est éliminé. N'oubliez pas que la voix du Capitaine compte double.
En cas d'égalité, s'il est présent, le vote du Capitaine désigne la victime. Sinon, les joueurs votent à nouveau (y compris les joueurs en cause) pour départager les ex-aequo.
S'il y a toujours égalité, aucun joueur n'est éliminé.
Le joueur éliminé révèle sa carte et ne pourra plus communiquer avec les autres joueurs d'aucune manière.
--]]
WereWolf.currentStep = "Vote"
isSetupStep = false
WereWolf.prettyPrint(L["Villagers vote! Point the one who killed!"])
for key, value in pairs(players) do
if value.isAlive then
Comm:SendCommand(value.Name, "set_vote")
end
end
end
local function IsRolePick(role)
local rolePick = false
for key, value in pairs(players) do
if(value.Role.Name == role and value.isAlive) then
rolePick = true
break
end
end
return rolePick
end
function WereWolf.WakeUpRogue()
WereWolf.currentStep = "Rogue"
if IsRolePick(L["Rogue"]) then
WereWolf.prettyPrint(L["Rogue, wake up and do your sneaky thing!"])
for key, value in pairs(players) do
Comm:SendCommand(value.Name, "set_rogue", value.Role)
end
else
WereWolf.NextStep()
end
end
function WereWolf.WakeUpCupid()
WereWolf.currentStep = "Cupid"
if IsRolePick(L["Cupid"]) then
WereWolf.prettyPrint(L["Cupid, wake up and throw your arrows!"])
for key, value in pairs(players) do
Comm:SendCommand(value.Name, "set_cupid", value.Role)
end
else
WereWolf.NextStep()
end
end
function WereWolf.WakeUpLovers()
WereWolf.currentStep = "Lovers"
if IsRolePick(L["Lover"]) then
WereWolf.prettyPrint(L["Lovers, wake up and face your beloved!"])
for key, value in pairs(players) do
Comm:SendCommand(value.Name, "set_lover", value.Role)
end
else
WereWolf.NextStep()
end
end
function WereWolf.WakeUpSeer()
WereWolf.currentStep = "Seer"
isSetupStep = false
if IsRolePick(L["Seer"]) then
for key, value in pairs(players) do
if value.isAlive then
Comm:SendCommand(value.Name, "set_seer", value.Role)
end
end
else
WereWolf.NextStep()
end
end
function WereWolf.WakeUpWerewolves()
WereWolf.currentStep = "Werewolves"
isSetupStep = false
WereWolf.prettyPrint(L["Werewolves, wake up and eat, eat till your hunger are filled!"])
for key, value in pairs(players) do
if value.isAlive then
Comm:SendCommand(value.Name, "set_werwolves", value.Role)
end
end
end
function WereWolf.WakeUpWitch()
WereWolf.currentStep = "Witch"
isSetupStep = false
if IsRolePick(L["Witch"]) then
for key, value in pairs(players) do
if value.isAlive then
Comm:SendCommand(value.Name, "set_witch", value.Role)
end
end
else
WereWolf.NextStep()
end
end
-- select among werewolf and peon role and set it to player
local function SetRoleToPlayer(player)
local classType = math.random(#players)
if ((classType% 2) == 0) then -- werewolf
if not (werewolfNumber == #players / 4) then
WereWolf.SetSpecificRoleToPlayer(player, stereotypes.werewolf)
werewolfNumber = werewolfNumber + 1
else -- peon
WereWolf.SetSpecificRoleToPlayer(player, stereotypes.peon)
peonNumber = peonNumber + 1
end
else -- peon
WereWolf.SetSpecificRoleToPlayer(player, stereotypes.peon)
peonNumber = peonNumber + 1
end
end
-- Apply the given role to player
function WereWolf.SetSpecificRoleToPlayer(player, role)
player.Role = {
Class = role.Class,
Name = role.Name,
Icon = role.Icon,
Tips = role.Tips,
Goal = role.Goal,
};
end
function WereWolf.SetRoleToAllPlayer()
for key, value in pairs(players) do
if value.Role == nil then
SetRoleToPlayer(value)
end
end
for key, value in pairs(players) do
if value.Role.Class == stereotypes.peon.Class then
if not(seerApplyed) then
WereWolf.SetSpecificRoleToPlayer(value, stereotypes.seer)
seerApplyed = true
else
if not(specialPeonNumber == #players / 4) then
local availableClass = {}
for key, value in pairs(stereotypes.special) do
if value.isApplyed == false then
table.insert(availableClass, value)
end
end
if #availableClass > 0 then
local classType = math.random(#availableClass)
local newRole = availableClass[classType]
WereWolf.SetSpecificRoleToPlayer(value, newRole)
specialPeonNumber = specialPeonNumber + 1
for key, value in pairs(stereotypes.special) do
if value.Name == newRole.Name then
value.isApplyed = true
break
end
end
end
end
end
end
end
end
function WereWolf.GetAvailabelRoleForRogue()
local possibleRole = {}
for i=0,2 do
if not (werewolfNumber == #players / 4) then
table.insert(possibleRole, stereotypes.werewolf)
elseif not(specialPeonNumber == #players / 4) then
local availableClass = {}
for key, value in pairs(stereotypes.special) do
if value.isApplyed == false then
table.insert(availableClass, value)
end
end
if #availableClass > 0 then
local classType = math.random(#availableClass)
local newRole = availableClass[classType]
table.insert(possibleRole, newRole)
end
else
table.insert(possibleRole, stereotypes.peon)
end
end
return possibleRole
end
function WereWolf.ManageDeathOfPlayer(player)
if player.Role.Class == L["Hunter"] then
-- another should die
-- WereWolf.AllowPlayerToPointFollower(player)
elseif player.Role.Class == L["Captain"] then
-- point the new captain
-- WereWolf.AllowPlayerToPointSuccessor(player)
elseif player.Role.Class == L["Lover"] then
-- the other lover die as well
for key, value in pairs(players) do
if not (value == player) and value.Role.Class == L["Lover"] then
-- WerWolf.SignifyDeathToPlayer(value)
value.isAlive = false
break
end
end
end
player.isAlive = false
end
|
local auth = function(token)
return token
end
return auth(ARGV[1])
|
--[[
License : GLPv3, see LICENCE in root of repository
Authors : Nikolay Fiykov, v1
--]]
local contains = require("contains")
local PinState = {
pin = 0,
mode = 4, --gpio.OPENDRAIN,
pullup = 6, -- gpio.FLOAT
cbGetValue = function()
return 1 --gpio.HIGH
end,
cbOnWrite = function()
end,
trigWhat = "none",
trigCb = function()
end
}
function PinState:new(pin, o)
o = o or {}
setmetatable(o, self)
self.__index = self
self.pin = pin
return o
end
PinState.writeEnum = {0, 1}
PinState.createPins = function()
local arr = {}
for i = 1, 12 do
arr[i] = PinState:new(i)
end
return arr
end
PinState.assertPinRange = function(pin, pins)
assert(type(pin) == "number", "pin must be number")
assert(pin > 0 and pin < 13, "pin must be 0<pin<13")
assert(pins[pin] ~= nil, "pin does not exists in test data array " .. pin)
return pins[pin]
end
PinState.changePinValue = function(pinState, val)
pinState.cbGetValue = function()
return val
end
if
(val == 1 and contains({"up", "high", "both"}, pinState.trigWhat)) or
(val == 0 and contains({"down", "low", "both"}, pinState.trigWhat))
then
pinState.trigCb(val, os.time())
end
end
return PinState
|
-- munin thermometer using DS18B20 sensors on ESP8622
-- (c) 2016, Florian Heimgaertner
-- This software may be modified and distributed under the terms
-- of the MIT license. See the LICENSE file for details.
local modname = ...
local M = {}
_G[modname] = M
local plugin = {}
local action = {}
local hostname = ('esp%06x'):format(node.chipid())
local ver = '0.04n'
local luaver = _VERSION
local pin = nil
local sensors = nil
local table = table
local string = string
local ow = ow
local tmr = tmr
local node = node
local file = file
local net = net
local pairs = pairs
setfenv(1,M)
-- munin node actions
action['config'] = function(socket,p)
if plugin[p] then
plugin[p](socket,'conf')
else
socket:send('# Unknown service\n')
end
socket:send('.\n')
end
action['fetch'] = function(socket,p)
if plugin[p] then
plugin[p](socket)
else
socket:send('# Unknown service\n')
end
socket:send('.\n')
end
action['list'] = function(socket)
for k,v in pairs(plugin) do
socket:send(k..' ')
end
socket:send('\n')
end
action['version'] = function(socket)
socket:send(('munins node on %s version: %s (lunin, %s/NodeMCU %i.%i.%i)\n'):format(hostname, ver, luaver, node.info()))
end
action['nodes'] = function(socket)
socket:send(hostname..'\n.\n')
end
action['help'] = function(socket)
socket:send('# Unknown command. Try ')
for k,v in pairs(action) do socket:send(k..' ') end
socket:send('\n')
end
action['quit'] = function(socket)
socket:close()
end
-- plugins
plugin['ds18b20'] = function(socket, x)
if sensors == nil then -- find sensors
sensors = {}
ow.setup(pin)
ow.reset_search(pin)
local nc = 0
repeat
local addr = ow.search(pin)
if (addr == nil) then
nc = nc + 1
elseif (addr:byte(1) == 0x28 and addr:byte(8) == ow.crc8(string.sub(addr,1,7))) then
table.insert(sensors, addr)
end
tmr.wdclr()
until (nc > 1)
ow.reset_search(pin)
end
if x == 'conf' then
socket:send('graph_title DS18B20 Temperature Sensors\ngraph_vlabel degrees Celsius\ngraph_category sensors\n')
for _,addr in pairs(sensors) do
local saddr = ("%02x%02x%02x%02x%02x%02x"):format(addr:byte(2,7))
socket:send('temp'..saddr..'.label '..saddr..'\n')
end
else
for _,addr in pairs(sensors) do
local s = ''
local t = 850001
ow.setup(pin)
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0xBE, 1)
local data = ow.read_bytes(pin, 9)
if (data:byte(9) == ow.crc8(string.sub(data,1,8))) then
t = (data:byte(1) + data:byte(2) * 256)
if (t > 0x7fff) then
t = t - 0x10000
s = '-'
end
t = t * 625
end
tmr.wdclr()
if t < 850000 then
local saddr = ("%02x%02x%02x%02x%02x%02x"):format(addr:byte(2,7))
socket:send(('temp%s.value %s%i.%04u\n'):format(saddr, s, t/10000,t %10000))
end
end
end
end
plugin['heap'] = function(socket, x)
if x == 'conf' then
socket:send('graph_title Heap remaining\ngraph_vlabel Bytes\ngraph_category system\ngraph_args --base 1024\nheap.label heap\n')
else
socket:send('heap.value '..node.heap()..'\n')
end
end
plugin['fsinfo'] = function(socket, x)
local remaining, used, total = file.fsinfo()
if x == 'conf' then
socket:send('graph_title Flash usage\ngraph_vlabel Bytes\ngraph_category system\ngraph_args --base 1024 -l 0 --upper-limit '..total..'\nusage.label usage\n')
else
socket:send('usage.value '..used..'\n')
end
end
function start(owpin)
pin = owpin
ow.setup(pin)
srv=net.createServer(net.TCP,10)
srv:listen(4949,function(socket)
socket:send('# munin node at '..hostname..'\n')
socket:on("receive",function(socket,payload)
local cmd, arg = payload:match('^(%l+)%s?([%w_]*)\r?\n?$')
if action[cmd] then
action[cmd](socket, arg)
else
action['help'](socket)
end
end)
end)
end
return M
|
-- Load dependencies
local mnist = require 'mnist'
local optim = require 'optim'
local gnuplot = require 'gnuplot'
local image = require 'image'
local cuda = pcall(require, 'cutorch') -- Use CUDA if available
local hasCudnn, cudnn = pcall(require, 'cudnn') -- Use cuDNN if available
local npy4th = require 'npy4th'
local nn = require 'nn'
require 'dpnn'
require 'tools'
require 'distributions'
-- Set up Torch
print('Setting up')
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(torch.random())
if cuda then
require 'cunn'
cutorch.manualSeed(torch.random())
print(string.format("GPU number: %d", cutorch.getDeviceCount()))
cutorch.setDevice(1)
print(string.format("Using GPU %d", cutorch.getDevice()))
end
-- Choose model to train
local cmd = torch.CmdLine()
cmd:option('-model', 'DEC', 'Model: AE|SparseAE|DeepAE|ConvAE|UpconvAE|DenoisingAE|Seq2SeqAE|VAE|AAE')
cmd:option('-learningRate', 0.0001, 'Learning rate')
cmd:option('-optimiser', 'adam', 'Optimiser')
cmd:option('-epochs', 300, 'Training epochs')
cmd:option('-sample_times', 12, 'sampling times before calculate gradient')
cmd:option('-K', 3, 'calculate gradient for K times and then averaging')
cmd:option('-n_points', 60000, 'randomly sample n_points instances from dataset to train')
cmd:option('-delta', 0.03, 'balance the loss of ae and ddcrp')
cmd:option('-alpha', 1, 'alpha')
cmd:option('-batchSize', 250, 'batchSize')
cmd:option('-name', 'mnist_joint', 'name of the trained model')
cmd:option('-task', 'ddcrp', 'ddcrp or ae')
cmd:option('-dataset', 'mnist', 'dataset')
cmd:option('-gamma', '0', 'gamma')
cmd:option('-criterion', 'mse','criterion')
local opt = cmd:parse(arg)
if opt.task == 'ddcrp' then
opt.n_points = 1000
opt.batchSize = 1000
end
local n_points = opt.n_points
local feature_size = 0
local XTrain = nil
local yTrain = nil
local XTest = nil
local N = nil
-- Load MNIST data
if opt.dataset == 'mnist' then
XTrain = mnist.traindataset().data:float():div(50) -- Normalise to [0, 1]
yTrain = mnist.traindataset().label
XTest = mnist.testdataset().data:float():div(50)
yTest = mnist.testdataset().label
N = XTrain:size(1)
if cuda then
XTrain = XTrain:cuda()
XTest = XTest:cuda()
end
else
local map = npy4th.loadnpz(string.format('%s.npz', opt.dataset))
XTrain = map['arr_0']
yTrain = map['arr_1']
XTest = XTrain
N = XTrain:size(1)
if cuda then
XTrain = XTrain:cuda()
XTest = XTrain
end
print(XTrain:size())
end
local index = torch.randperm(N)[{{1, n_points}}]:long()
XTrain = XTrain:index(1, index):cuda()
yTrain = yTrain:index(1, index)
-- torch.save('data/image.t7', XTrain:double())
-- torch.save('data/label.t7', yTrain)
local label_unique = {}
for i = 1, n_points do
if label_unique[yTrain[i]+1] == nil then
label_unique[yTrain[i]+1] = 1
else
label_unique[yTrain[i]+1] = label_unique[yTrain[i]+1] + 1
end
end
print(#label_unique)
-- Create model
Model = require ('models/' .. opt.model)
Model:createAutoencoder(XTrain)
local autoencoder = Model.autoencoder
local encoder = Model.encoder
local normalized_encoder = nn.Sequential()
normalized_encoder:add(encoder)
normalized_encoder:add(nn.Normalize(2))
if cuda then
autoencoder:cuda()
encoder:cuda()
normalized_encoder:cuda()
-- Use cuDNN if available
if hasCudnn then
cudnn.convert(autoencoder, cudnn)
cudnn.convert(encoder, cudnn)
cudnn.convert(normalized_encoder, cudnn)
end
end
if opt.task == 'ddcrp' then
normalized_encoder:forward(XTrain)
feature_size = normalized_encoder.output:size(2)
torch.save('data/feature.t7', normalized_encoder.output:double())
torch.save('data/label.t7', yTrain)
end
-- Create tables and the relations between points
local belong = torch.range(1, n_points):int()
local tables = {}
tables[1] = {}
for i = 1, n_points do
table.insert(tables[1], i)
belong[i] = 1
end
local means = {}
local covs = {}
-- local n_tables = n_points
-- belong = torch.range(1, n_points):int()
-- for i = 1, n_points do
-- tables[i] = {}
-- table.insert(tables[i], i)
-- end
-- local connect = torch.range(1, n_points):int()
-- local connected = {}
-- for i = 1, n_points do
-- connected[i] = {}
-- table.insert(connected[i], i)
-- end
local mu_0 = torch.CudaTensor({-0.158365442515, 0.0377739193953, -0.0147440236072, 0.074388357756, -0.153201982234, -0.0842131485674, 0.201350941488, 0.0575697282466, 0.18518343795, -0.0174676928583, }):view(feature_size, 1)
local kappa_0 = 0.01
local nu_0 = feature_size
local lambda_0 = torch.eye(feature_size):cuda():mul(2)
-- torch.inverse(nu_0 *
-- torch.CudaTensor({
-- {0.0366284242442, 0.00655439824317, 0.00223428470026, 0.00512935709104, 0.00706118920457, 0.00127367072023, 0.00895389914584, -0.00374665113559, 0.00494345676178, -0.0108999683881, },
-- {0.00655439824317, 0.0390891765439, -0.00130038432964, 0.00267932826372, 7.76895533872e-05, -0.000670595539531, -0.000162156024855, -0.00624318767337, 0.00433524044539, -0.000619171853721, },
-- {0.00223428470026, -0.00130038432964, 0.0446884605404, 0.00548076846674, -0.00285376214203, -0.00796014366193, 0.00940989578467, -0.00493952206002, 0.00139216856423, -0.00234435190168, },
-- {0.00512935709104, 0.00267932826372, 0.00548076846674, 0.0321686199303, 0.00346165276327, -0.0038337789042, 0.00530248525576, -0.0054437993534, -0.00404586384196, -0.00123830146687, },
-- {0.00706118920457, 7.76895533872e-05, -0.00285376214203, 0.00346165276327, 0.0417464946152, 0.00352988995952, 0.0125444622185, 0.00155953790617, 0.00150808524191, -0.00460548496398, },
-- {0.00127367072023, -0.000670595539531, -0.00796014366193, -0.0038337789042, 0.00352988995952, 0.0403215362515, -0.000409462230569, 0.00135282730524, 0.00191234159114, -9.72654600904e-05, },
-- {0.00895389914584, -0.000162156024855, 0.00940989578467, 0.00530248525576, 0.0125444622185, -0.000409462230569, 0.0403591606515, -0.00650039728275, -0.00601142474037, -0.00608422171382, },
-- {-0.00374665113559, -0.00624318767337, -0.00493952206002, -0.0054437993534, 0.00155953790617, 0.00135282730524, -0.00650039728275, 0.0449720012599, -0.00673620989614, -0.00177772886742, },
-- {0.00494345676178, 0.00433524044539, 0.00139216856423, -0.00404586384196, 0.00150808524191, 0.00191234159114, -0.00601142474037, -0.00673620989614, 0.0415150176486, 0.00106010428521, },
-- {-0.0108999683881, -0.000619171853721, -0.00234435190168, -0.00123830146687, -0.00460548496398, -9.72654600904e-05, -0.00608422171382, -0.00177772886742, 0.00106010428521, 0.0305230968794, },
-- })
-- )
--torch.diag(torch.Tensor(feature_size):fill(opt.lambda)):cuda()
-- local tmp = torch.eig(lambda_0:double(), 'N')[{{},{1}}]
-- local det_lambda_0 = torch.prod(tmp)
-- print(tmp, math.log(det_lambda_0))
det_lambda_0 = distributions.util.logdet(lambda_0:double())
print(det_lambda_0)
-- Get parameters
local theta, gradTheta = autoencoder:getParameters()
-- Create loss
local criterion = nn.BCECriterion() -- nn.MSECriterion()--
if opt.criterion == 'mse' then
criterion = nn.MSECriterion()
end
if cuda then
criterion:cuda()
end
-- Create optimiser function evaluation
local x -- Minibatch
local feval = function(params)
if theta ~= params then
theta:copy(params)
end
-- Zero gradients
gradTheta:zero()
-- Reconstruction phase
-- Forward propagation
local xHat = autoencoder:forward(x) -- Reconstruction
local loss = criterion:forward(xHat, x)
-- Backpropagation
local gradLoss = criterion:backward(xHat, x)
autoencoder:backward(x, gradLoss)
return loss, gradTheta
end
local ddcrpFeval = function(params)
if theta ~= params then
theta:copy(params)
end
-- Zero gradients
gradTheta:zero()
local xHat = autoencoder:forward(x) -- Reconstruction
local loss = criterion:forward(xHat, x)
print(string.format(" [%s], ae-loss: %f", os.date("%c", os.time()), loss))
-- Backpropagation
local gradLoss = criterion:backward(xHat, x)
autoencoder:backward(x, gradLoss)
--encoder:evaluate()
local z = normalized_encoder:forward(x)
local z_d = z:double()
means = {}
covs = {}
crp_init(z, means, covs, tables, mu_0, kappa_0, lambda_0, nu_0)
-- print(z[{{1,5}}])
-- print(z:size())
--encoder:training()
for ite = 1, opt.sample_times do
--n_tables = gibbs_sample(z_d, belong, connect, tables, connected, n_tables, opt.alpha, mu_0, kappa_0, lambda_0, nu_0, det_lambda_0)
crp_gibbs_sample(z_d, means, covs, tables, belong, 1e-6, mu_0:double(), kappa_0, lambda_0:double(), nu_0)
end
for ite = 1, opt.K do
--n_tables = gibbs_sample(z_d, belong, connect, tables, connected, n_tables, opt.alpha, mu_0, kappa_0, lambda_0, nu_0, det_lambda_0)
crp_gibbs_sample(z_d, means, covs, tables, belong, 1e-6, mu_0:double(), kappa_0, lambda_0:double(), nu_0)
local l1_loss, l2_loss, S_loss, dz, S_dz = cal_gradient(z, connect, tables, opt.alpha, mu_0, kappa_0, lambda_0, nu_0, det_lambda_0)
dz = dz * opt.delta / opt.K / n_points
S_dz = S_dz * opt.gamma
loss = loss + (l1_loss + l2_loss) * opt.delta / opt.K / n_points + S_loss * opt.gamma
print(string.format(" [%s], loss1: %f, loss2: %f, S_loss: %f",
os.date("%c", os.time()),
l1_loss * opt.delta / opt.K / n_points,
l2_loss * opt.delta / opt.K / n_points,
S_loss * opt.gamma)
)
normalized_encoder:backward(x, dz + S_dz)
end
return loss, gradTheta
end
-- Train
print('Training')
autoencoder:training()
local optimParams = {learningRate = opt.learningRate}
local advOptimParams = {learningRate = opt.learningRate}
local __, loss
local losses, advLosses = {}, {}
for epoch = 1, opt.epochs do
print('Epoch ' .. epoch .. '/' .. opt.epochs)
for n = 1, n_points, opt.batchSize do
-- Get minibatch
x = XTrain:narrow(1, n, opt.batchSize)
-- Optimise
if opt.task == 'ddcrp' then
__, loss = optim[opt.optimiser](ddcrpFeval, theta, optimParams)
losses[#losses + 1] = loss[1]
else
__, loss = optim[opt.optimiser](feval, theta, optimParams)
losses[#losses + 1] = loss[1]
end
-- Train adversary
if opt.model == 'AAE' then
__, loss = optim[opt.optimiser](advFeval, thetaAdv, advOptimParams)
advLosses[#advLosses + 1] = loss[1]
end
end
if opt.task == 'ddcrp' then
evaluate_cluster(tables, yTrain, epoch, loss, n_points, #label_unique)
else
print(string.format(" loss: %4f", loss[1]))
end
-- Plot training curve(s)
local plots = {{'Autoencoder', torch.linspace(1, #losses, #losses), torch.Tensor(losses), '-'}}
gnuplot.pngfigure('train_20_news.png')
gnuplot.plot(table.unpack(plots))
gnuplot.ylabel('Loss')
gnuplot.xlabel('Batch #')
gnuplot.plotflush()
if epoch % 30 == 0 and opt.task == 'ddcrp' then
torch.save('trained/' .. opt.name .. string.format('_%d_ddcrp', epoch), Model)
torch.save(string.format("results/tables_at_epoch_%d", epoch), tables)
end
end
-- Test
print('Testing')
x = XTest:narrow(1, 1, 10)
autoencoder:evaluate()
local xHat = autoencoder:forward(x)
-- Plot reconstructions
if opt.dataset == 'mnist' then
image.save('Reconstructions.png', torch.cat(image.toDisplayTensor(x, 2, 10), image.toDisplayTensor(xHat, 2, 10), 1))
end
if opt.ddcrp == 'ddcrp' then
normalized_encoder:forward(XTrain)
torch.save(string.format('data/feature_learnt.t7'), normalized_encoder.output:double())
end
|
local M = {}
local luafmt = {
formatCommand = "luafmt -i 2 --stdin",
formatStdin = true,
}
local stylua = {
formatCommand = "stylua --config-path $HOME/.config/stylua/stylua.toml -",
formatStdin = true,
}
local flake8 = {
lintCommand = "flake8 --ignore=E501,W503 --stdin-display-name ${INPUT} -",
lintStdin = true,
prefix = "flake8",
lintIgnoreExitCode = true,
lintFormats = { "%f:%l:%c: %t%n %m" },
}
local isort = {
formatCommand = "isort --profile black -l 100 -",
formatStdin = true,
}
local autopep8 = {
formatCommand = "autopep8 --max-line-length 100 -",
formatStdin = true,
}
local yapf = {
formatCommand = "yapf",
formatStdin = true,
}
local black = {
formatCommand = "black --quiet -l 100 -",
formatStdin = true,
}
local mypy = {
lintCommand = "mypy --show-column-numbers --ignore-missing-imports --disable-error-code name-defined --cache-dir=/dev/null",
lintFormats = { "%f:%l:%c: %trror: %m", "%f:%l:%c: %tarning: %m", "%f:%l:%c: %tote: %m" },
prefix = "mypy",
}
local prettier = {
formatCommand = "prettier --stdin-filepath ${INPUT}",
formatStdin = true,
}
local shellcheck = {
lintCommand = "shellcheck -f gcc -x",
lintFormats = { "%f:%l:%c: %trror: %m", "%f:%l:%c: %tarning: %m", "%f:%l:%c: %tote: %m" },
}
M.languages = {
python = { isort, flake8, black, mypy },
lua = { stylua },
yaml = { prettier },
json = { prettier },
html = { prettier },
css = { prettier },
markdown = { prettier },
}
M.config = {
filetypes = vim.tbl_keys(M.languages),
init_options = {
documentFormatting = true,
},
settings = {
languages = M.languages,
},
}
return M
|
object_building_kashyyyk_poi_kash_rryatt_lvl4_tree_root_a3 = object_building_kashyyyk_shared_poi_kash_rryatt_lvl4_tree_root_a3:new {
}
ObjectTemplates:addTemplate(object_building_kashyyyk_poi_kash_rryatt_lvl4_tree_root_a3, "object/building/kashyyyk/poi_kash_rryatt_lvl4_tree_root_a3.iff")
|
return Def.ActorFrame{
Def.Quad{
InitCommand=cmd(FullScreen);
OnCommand=cmd(diffusealpha,0;sleep,2);
};
LoadActor(THEME:GetPathS("","_swoosh out.ogg"))..{
OnCommand=cmd(queuecommand,"Play");
PlayCommand=cmd(play)
};
StartTransitioningCommand=function(self) SOUND:DimMusic(0,math.huge) end,
}
|
local Types = require(script.Parent.Parent.Types)
type Record<K, V = K> = Types.Record<K, V>
local function override(target: Record<any>, source: Record<any>): Record<any>
local result = table.clone(target)
for key, value in source do
result[key] = if type(value) == "table" then if type(result[key]) == "table" then override(result[key], value) else table.clone(value) else value
end
return result
end
return override
|
return Def.Sprite{
--No Quest Mode BGA so we'll have to live with it
Texture=THEME:GetPathG("","_BGMovies/Arcade");
InitCommand=cmd(Cover;zoomx,1.02);
};
|
-- function reference
-- include
local newTable = require("toolkit.common").newTable
local utils = require("toolkit.utils")
local helper = newTable(0, 2)
helper.jsonSerialize = function(lData, pattern)
return pattern and (utils.json_encode(lData)..pattern) or utils.json_encode(lData)
end
helper.jsonDerialize = function(jData)
return utils.json_decode(jData)
end
return helper
|
module:set_global();
local measure = require"core.statsmanager".measure;
local valid_shows = {
available = true,
chat = true,
away = true,
dnd = true,
xa = true,
unavailable = true,
}
local counters = {
available = measure("amount", "client_presence.available"),
chat = measure("amount", "client_presence.chat"),
away = measure("amount", "client_presence.away"),
dnd = measure("amount", "client_presence.dnd"),
xa = measure("amount", "client_presence.xa"),
unavailable = measure("amount", "client_presence.unavailable"),
invalid = measure("amount", "client_presence.invalid");
};
module:hook("stats-update", function ()
local buckets = {
available = 0,
chat = 0,
away = 0,
dnd = 0,
xa = 0,
unavailable = 0,
invalid = 0,
};
for _, session in pairs(full_sessions) do
local status = "unavailable";
if session.presence then
status = session.presence:get_child_text("show") or "available";
end
if valid_shows[status] ~= nil then
buckets[status] = buckets[status] + 1;
else
buckets.invalid = buckets.invalid + 1;
end
end
for bucket, count in pairs(buckets) do
counters[bucket](count)
end
end)
|
function foo(a)
local x = 1/0
local y = 0/1
local w = a/0
local z = 0/a
print(x, y, w, z)
end
foo(7)
|
function factorial(n)
if n == 0.0 then
return 1.0
else
return n * factorial(n - 1.0)
end
end
|
module(..., package.seeall)
--;===========================================================
--; SOUND TEST MENU LOOP
--;===========================================================
t_soundMenu = {
{id = textImgNew(), text = 'CONTINUE?'},
{id = textImgNew(), text = 'GAME OVER'},
{id = textImgNew(), text = 'BACK'},
}
function f_soundMenu()
cmdInput()
local cursorPosY = 0
local moveTxt = 0
local soundMenu = 1
while true do
if esc() then
playBGM(bgmTitle)
sndPlay(sysSnd, 100, 2)
break
elseif commandGetState(p1Cmd, 'u') then
sndPlay(sysSnd, 100, 0)
soundMenu = soundMenu - 1
elseif commandGetState(p1Cmd, 'd') then
sndPlay(sysSnd, 100, 0)
soundMenu = soundMenu + 1
end
if soundMenu < 1 then
soundMenu = #t_soundMenu
if #t_soundMenu > 4 then
cursorPosY = 4
else
cursorPosY = #t_soundMenu-1
end
elseif soundMenu > #t_soundMenu then
soundMenu = 1
cursorPosY = 0
elseif commandGetState(p1Cmd, 'u') and cursorPosY > 0 then
cursorPosY = cursorPosY - 1
elseif commandGetState(p1Cmd, 'd') and cursorPosY < 4 then
cursorPosY = cursorPosY + 1
end
if cursorPosY == 4 then
moveTxt = (soundMenu - 5) * 13
elseif cursorPosY == 0 then
moveTxt = (soundMenu - 1) * 13
end
if btnPalNo(p1Cmd) > 0 then
f_default()
--TRACK LIST
if soundMenu == 1 then
playBGM('sound/CONTINUE.mp3')
elseif soundMenu == 2 then
playBGM('sound/GAME OVER.mp3')
--BACK
else
playBGM(bgmTitle)
sndPlay(sysSnd, 100, 2)
break
end
end
animDraw(f_animVelocity(titleBG0, -2.15, 0))
for i=1, #t_soundMenu do
if i == soundMenu then
bank = 5
else
bank = 0
end
textImgDraw(f_updateTextImg(t_soundMenu[i].id, jgFnt, bank, 0, t_soundMenu[i].text, 159, 144+i*13-moveTxt))
end
animSetWindow(cursorBox, 101,147+cursorPosY*13, 116,13)
f_dynamicAlpha(cursorBox, 20,100,5, 255,255,0)
animDraw(f_animVelocity(cursorBox, -1, -1))
animDraw(titleBG1)
animAddPos(titleBG2, -1, 0)
animUpdate(titleBG2)
animDraw(titleBG2)
animDraw(titleBG3)
animDraw(titleBG4)
animDraw(titleBG5)
animDraw(titleBG6)
textImgDraw(txt_titleFt)
textImgDraw(txt_titleFt2)
animDraw(arrowsD)
animUpdate(arrowsD)
animDraw(arrowsU)
animUpdate(arrowsU)
animDraw(data.fadeTitle)
animUpdate(data.fadeTitle)
cmdInput()
refresh()
end
end
|
if turn == 1 then
character_1:UseSkill(2)
character_1:UseSkill(3)
character_1:UseSkill(4)
character_2:UseSkill(1)
character_2:UseSkill(2)
character_2:OnPartyMember(3):UseSkill(3)
character_3:UseSkill(2)
character_3:UseSkill(1)
character_4:WithWaitTime(2000):UseSkill(2)
character_4:UseSkill(1)
EnableChargeAttack()
Summon(6)
end
if turn == 2 then
Summon(4)
character_3:UseSkill(3)
end
|
include "app.gameClass.item.Item"
include "app.gameClass.trigger.Need"
_ENV=namespace "game"
using_namespace "luaClass"
using_namespace "container"
class("Mission"){
CLASS_DEBUG(false);
}
function Mission:Mission(missionInfo)
self.name=missionInfo.missionName
self.limit=missionInfo.limit
self.desc=missionInfo.desc
self.needs=array()
self.costs=array()
self.tag=missionInfo.tag
self.place=missionInfo.belongMissionPlace
self.completeDesc=missionInfo.completeDesc
self.identifier=self.place..self.name
self.events=map()
self.isComplete=false
local needs=missionInfo.need
local costs=missionInfo.cost
if needs then
for _,need in pairs(needs) do
if need.type~="" then
self.needs:push_back(MissionNeed(self,need.type,need.value))
end
end
end
if costs then
for _,cost in pairs(costs) do
if cost.type~="" then
self.costs:push_back(
{
name=cost.type,
value=array(cost.value:split(","))
}
)
end
end
end
end
function Mission:cost()
for _,cost in self.costs:iter() do
if cost.name=="item" then
local name=cost.value:at(1)
local num= tonumber(cost.value:at(2)) or 0
local item=RuntimeData:getInstance():getItemByName(name)
if item then
RuntimeData:getInstance():removeItem(item.identifier,num)
else
print("error: can not find item ".. name.."please check excel mission")
end
end
end
end
function Mission:checkNeed()
for _,need in self.needs:iter() do
if not need:check() then
return false
end
end
RuntimeData:getInstance().tag:insert(self.tag)
RuntimeData:getInstance().missionsComplete:insert(self.identifier)
return true
end
function Mission:checkLimit()
return
(RuntimeData:getInstance().MissionLimit:get(self.identifier,0)<self.limit)
end
function Mission:hasMission()
return RuntimeData:getInstance().missions:has(self.identifier)
end
function Mission:acceptMission()
local value=RuntimeData:getInstance().MissionLimit:get(self.identifier,0)
RuntimeData:getInstance().MissionLimit:insert(self.identifier,1+value)
RuntimeData:getInstance().missions:insert(self.identifier,self)
self:register()
end
function Mission:complete()
self.isComplete=true
self:cost()
RuntimeData:getInstance().missionsComplete:insert(self.identifier)
end
function Mission:register()
for _,need in self.needs:iter() do
local name=need.name
if name=="meet" then
local event=self.events:get(ENUM.RUNTIME_EVENT.MEET_ROLE) or set()
self.events:insert(ENUM.RUNTIME_EVENT.MEET_ROLE,event)
elseif name=="kill" then
local event=self.events:get(ENUM.RUNTIME_EVENT.KILL_ROLE) or map()
event:insert(need.argvs:at(1),0)
self.events:insert(ENUM.RUNTIME_EVENT.KILL_ROLE,event)
end
end
end
function Mission:interest(eventEnum,data)
local event=self.events:get(eventEnum)
if event then
if eventEnum==ENUM.RUNTIME_EVENT.MEET_ROLE then
return true
elseif eventEnum==ENUM.RUNTIME_EVENT.KILL_ROLE then
if event:get(data) then
return true
end
end
end
return false
end
function Mission:record(eventEnum,data)
if eventEnum==ENUM.RUNTIME_EVENT.MEET_ROLE then
self.events:get(eventEnum):insert(data)
elseif eventEnum==ENUM.RUNTIME_EVENT.KILL_ROLE then
self.events:get(eventEnum):insert(data,1)
end
end
function Mission:toString(type)
type=type or "detail"
local str=""
if type=="simple" then
str=str..self.name.."\n"..
self.desc
elseif type=="detail" then
local strArr=array()
local hasMission=self:hasMission()
for _,need in self.needs:iter() do
strArr:push_back(
need:toString()
)
end
str=str..self.name.."\n"..
self.desc.."\n"..
"需求条件:\n"..
table.concat(strArr:getData(),"\n").."\n"..
"可接取次数: "..(self.limit-RuntimeData:getInstance().MissionLimit:get(self.identifier,0))..
((not hasMission) and "\n尚未接受任务\n" or "\n已接受任务\n")
elseif type=="check" then
local strArr=array()
for _,need in self.needs:iter() do
strArr:push_back(
need:toString("check")
)
end
str=str..self.name.."\n"..
self.desc.."\n"..
"需求完成:\n"..
table.concat(strArr:getData(),"\n").."\n"..
(self.isComplete and "已完成\n"..self.completeDesc or "未完成")
end
return str
end
|
function RcEncodeTrace(rec)
local longFmtCnt = 0
local buf = ''
for i, data in ipairs(rec) do
local dticks, model = tonumber(data[1]), tonumber(data[8])
local dx, dy, dz = tonumber(data[2]), tonumber(data[3]), tonumber(data[4])
local drx, dry, drz = tonumber(data[5]), tonumber(data[6]), tonumber(data[7])
if(not dticks or not dx or not dy or not dz or not drx or not dry or not drz) then
Debug.warn('Invalid rec')
return false
end
if(drx > 180) then drx = drx - 360
elseif(drx < -180) then drx = drx + 360 end
if(dry > 180) then dry = dry - 360
elseif(dry < -180) then dry = dry + 360 end
if(drz > 180) then drz = drz - 360
elseif(drz < -180) then drz = drz + 360 end
local longFmt = model or dticks > 65000 or
math.abs(dx) > 32000 or math.abs(dy) > 32000 or math.abs(dz) > 32000 or
math.abs(drx) > 127 or math.abs(dry) > 127 or math.abs(drz) > 127
if(longFmt) then
longFmtCnt = longFmtCnt + 1
buf = buf..'\1'..uintToBin(dticks, 4)..
intToBin(dx, 4)..intToBin(dy, 4)..intToBin(dz, 4)..
intToBin(drx, 2)..intToBin(dry, 2)..intToBin(drz, 2)..uintToBin(model or 0, 2)
else
buf = buf..'\0'..uintToBin(dticks, 2)..
intToBin(dx, 2)..intToBin(dy, 2)..intToBin(dz, 2)..
intToBin(drx, 1)..intToBin(dry, 1)..intToBin(drz, 1)
end
end
if(longFmtCnt*10 > #rec) then
Debug.warn('Too bad '..longFmtCnt..'/'..#rec)
end
return buf
end
function RcDecodeTrace(buf)
local rec = {}
local i = 1
while(i <= buf:len()) do
local flags = buf:byte(i)
assert(flags <= 1)
local data = {}
if(flags == 1) then -- long format
assert(i + 24 <= buf:len())
data[1] = binToUint(buf:sub(i + 1, i + 4)) -- dticks
data[2] = binToInt(buf:sub(i + 5, i + 8)) -- dx
data[3] = binToInt(buf:sub(i + 9, i + 12)) -- dy
data[4] = binToInt(buf:sub(i + 13, i + 16)) -- dz
data[5] = binToInt(buf:sub(i + 17, i + 18)) -- drx
data[6] = binToInt(buf:sub(i + 19, i + 20)) -- dry
data[7] = binToInt(buf:sub(i + 21, i + 22)) -- drz
data[8] = binToUint(buf:sub(i + 23, i + 24)) -- model
if(data[8] == 0) then data[8] = false end
i = i + 25
else
assert(i + 11 <= buf:len())
data[1] = binToUint(buf:sub(i + 1, i + 2)) -- dticks
data[2] = binToInt(buf:sub(i + 3, i + 4)) -- dx
data[3] = binToInt(buf:sub(i + 5, i + 6)) -- dy
data[4] = binToInt(buf:sub(i + 7, i + 8)) -- dz
data[5] = binToInt(buf:sub(i + 9, i + 9)) -- drx
data[6] = binToInt(buf:sub(i + 10, i + 10)) -- dry
data[7] = binToInt(buf:sub(i + 11, i + 11)) -- drz
i = i + 12
end
table.insert(rec, data)
end
return rec
end
|
require('bufferline').setup{
options = {
view = "multiwindow",
tab_size=5,
numbers="both",
separator_style="thin",
enforce_regular_tabs=false,
show_tab_indicators = true,
tab_indicator_style = function(tab)
if not tab.name or tab.name == "" then
return "裡"
end
local loaded, webdev_icons
if loaded == nil then
loaded, webdev_icons = pcall(require, "nvim-web-devicons")
end
if loaded then
local icon = webdev_icons.get_icon(tab.name, vim.fn.expand("#"..tab.mru_buf..":e"))
if not icon or icon == "" then
return vim.fn.fnamemodify(tab.name, ":t")
-- return tab.name:match("^.+/(.+)$") .. " 裡"
else
-- return tab.name:match("^.+/(.+)$") .. " " .. icon
return vim.fn.fnamemodify(tab.name, ':t') .. " " .. icon
end
end
end
}
}
local wk = require('which-key')
wk.register({
name = "+bufferline",
h = {"<cmd>BufferLineCyclePrev<CR>", "Previous buffer"},
l = {"<cmd>BufferLineCycleNext<CR>", "Next buffer"},
j = {"<cmd>BufferLineMovePrev<CR>", "Move buffer left"},
k = {"<cmd>BufferLineMoveNext<CR>", "Move buffer right"},
}, {
mode = 'n',
prefix = "<localleader>b"
})
-- offsets = {
--[[ {filetype="vista", text="vista"},
{filetype="coc-explorer", text="Project Drawer"}
} ]]
--[[ sort_by = function(buffer_a, buffer_b)
-- Automatically sort buffers by tabpage
local tabs = vim.fn.gettabinfo()
local buffer_a_tabnr = nil
local buffer_b_tabnr = nil
for _, tab in ipairs(tabs) do
local buffers = vim.fn.tabpagebuflist(tab.tabnr)
for _, buff in ipairs(buffers) do
if buff == buffer_a.id then
buffer_a_tabnr = tab.tabnr
elseif buff == buffer_b.id then
buffer_b_tabnr = tab.tabnr
end
if buffer_a_tabnr ~= nil and buffer_b_tabnr ~= nil then
return buffer_a_tabnr < buffer_b_tabnr
end
end
end
if buffer_a_tabnr == nil then
return true
end
if buffer_b_tabnr == nil then
return false
end
return buffer_a_tabnr < buffer_b_tabnr
end ]]
|
-- Verify that cross referencing and aligned ABC emission works correctly
abclua = require "abclua"
function get_crossrefs(tokens, refs)
-- return a table of all the cross references in the stream, as strings
for i,v in ipairs(tokens) do
if v.cross_ref then
table.insert(refs,v.cross_ref.tune..'-'..v.cross_ref.tune_line..'-'..v.cross_ref.line..'-'..v.cross_ref.at)
end
end
end
function verify_crossrefs(str, result, test)
-- verify that the pitches match the expected values
local songs = abclua.parse_abc_multisong(str, {cross_ref=true})
local refs = {}
for i,v in ipairs(songs) do
tokens = v.token_stream
get_crossrefs(tokens, refs)
end
-- table_print(refs)
for i, v in ipairs(result) do
assert(refs[i]==result[i], test)
end
print(test.." passed OK")
end
function test_crossrefs()
-- Test repeats and variant endings
verify_crossrefs([[
X:1
K:C
CDE
]], {
'1-1-1-1',
'1-2-2-1',
'1-3-3-1',
'1-3-3-2',
'1-3-3-3',
'1-3-3-4',
'1-3-3-4', -- newline
}, 'Simple notes cross refs')
verify_crossrefs([[
X:1
K:C
C[r:remark]DE
]], {
'1-1-1-1', '1-2-2-1',
'1-3-3-1',
'1-3-3-2',
'1-3-3-12',
'1-3-3-13',
'1-3-3-14',
'1-3-3-14', -- newline
}, 'Inline fields cross refs')
verify_crossrefs([[
X:1
K:C
C"r:remark"DE
]], {
'1-1-1-1', '1-2-2-1',
'1-3-3-1',
'1-3-3-2',
'1-3-3-13',
'1-3-3-14',
'1-3-3-14', -- newline
}, 'Annotations cross refs')
verify_crossrefs([[
X:1
K:C
CDE
X:1
K:C
CDE
]], {
'1-1-1-1',
'1-2-2-1',
'1-3-3-1',
'1-3-3-2',
'1-3-3-3',
'1-3-3-3',
'2-1-4-1',
'2-2-5-1',
'2-3-6-1',
'2-3-6-2',
'2-3-6-3',
'2-3-6-3',
}, 'Multiple song cross refs')
end
test_crossrefs()
|
--Stance state is basically a Walk controller
--Without any torso or feet update
--We share the leg joint generation / balancing code
--with walk controllers
local state = {}
state._NAME = ...
local Body = require'Body'
local vector = require'vector'
local moveleg = require'moveleg'
require'mcm'
-- Keep track of important times
local t_entry, t_update, t_last_step
local timeout = 10
-- Track the torso
local uTorso, uLeft, uRight
local zLeft, zRight
local side
function state.entry()
print(state._NAME..' Entry' )
-- Update the time of entry
local t_entry_prev = t_entry -- When entry was previously called
t_entry = Body.get_time()
t_update = t_entry
-- Shared variables
uTorso = mcm.get_status_uTorso()
uLeft = mcm.get_status_uLeft()
uRight = mcm.get_status_uRight()
zLeft, zRight = unpack(mcm.get_status_zLeg())
side = mcm.get_teach_sway()
-- Local variables
side = side=='none' and 'left' or side
--
print('Sway to the', side)
end
function state.update()
-- Get the time of update
local t = Body.get_time()
local dt = t - t_update
-- Save this at the last update time
t_update = t
if t - t_entry > timeout then return'timeout' end
local l_ft, r_ft = Body.get_lfoot(), Body.get_rfoot()
-- Check the CoM first
if side=='left' then
if l_ft[3] < 2*r_ft[3] then
uTorso = uTorso + vector.new{0,0.0005,0}
mcm.set_status_uTorso(uTorso)
else
side = 'right'
mcm.set_teach_sway(side)
--return'switch'
end
elseif side=='right' then
--print('L FT', l_ft)
--print('R FT', r_ft)
if r_ft[3] < 2*l_ft[3] then
uTorso = uTorso - vector.new{0,0.0005,0}
mcm.set_status_uTorso(uTorso)
else
side = 'left'
mcm.set_teach_sway(side)
--return'switch'
end
end
moveleg.set_leg_positions_slowly(uTorso, uLeft, uRight, zLeft, zRight, dt)
end
function state.exit()
print(state._NAME..' Exit')
end
return state
|
require("yalt/yalt")
image = love.graphics.newImage( "image.png" )
love.graphics.setBackgroundColor(114,159,207) -- Tango! Sky Blue 1
--YALT restores the graphics color and font to what it was originally.
love.graphics.setColor(46,52,54,255)-- Tango! Aluminium 6
speed = 1
function love.draw()
love.graphics.print( "\"YALT - Yet Another Love Terminal\" demo project.\nPress F1 to open YALT.", 100, 100)
love.graphics.draw( image, 400, 300, math.sin(r_term/speed)/2, 1,1,150,150)
yalt:draw()--Required
end
function love.keypressed(key,unicode)
yalt:keypressed(key,unicode)--Required
end
function love.keyreleased(key,unicode)
yalt:keyreleased(key,unicode)--Required
end
function yalt:callback(input)
ia = explode(" ",input)
if ia[1] == "hello" then
if ia[2] == "world" then
if ia[3] then
name = ia[3].."."
else
name = "friend."
end
yalt:push("Why, hello there!\nHow nice of you to stop by, "..name)
else
i_dunno(input)
end
else
i_dunno(input)
end
end
function i_dunno(input)
yalt:push("unknown command \""..input.."\".")
end
r_term = 0
function love.update(dt)
r_term = dt + r_term
end
function round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
function explode(div,str) -- credit: http://richard.warburton.it
if (div=='') then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider
return arr
end
|
--[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* client/admin_coroutines.lua
*
* Original File by lil_Toady
*
**************************************]]
local aCoroutines = {}
sourceCoroutine = nil
local _addEventHandler = addEventHandler
function addEventHandler ( event, element, handler, ... )
if ( not _addEventHandler ( event, element, corouteHandler ( handler ), ... ) ) then
local info = debug.getinfo ( 2, "nS" )
outputDebugString ( "addEventHandler call failed from: "..tostring ( info.name ).." ("..info.short_src..")" )
end
end
local _removeEventHandler = removeEventHandler
function removeEventHandler ( event, element, handler )
if ( aCoroutines[handler] ) then
for id, wrapper in ipairs ( aCoroutines[handler] ) do
_removeEventHandler ( event, element, wrapper )
end
aCoroutines[handler] = {}
else
_removeEventHandler ( event, element, handler )
end
end
function corouteHandler ( handler )
local wrapper = function ( ... )
local c = coroutine.create ( handler )
sourceCoroutine = c
local result, error = coroutine.resume ( c, ... )
if ( not result ) then
outputDebugString ( tostring ( error ) )
end
if ( sourceCoroutine == c ) then
sourceCoroutine = nil
end
end
if ( not aCoroutines[handler] ) then
aCoroutines[handler] = {}
end
table.insert ( aCoroutines[handler], wrapper )
return wrapper
end
function coroutineKill ( cr )
if ( coroutine.status ( c ) ~= 'dead' ) then
coroutine.resume ( c, nil )
end
end
|
local __exports = LibStub:NewLibrary("ovale/combat", 80300)
if not __exports then return end
local __class = LibStub:GetLibrary("tslib").newClass
local __State = LibStub:GetLibrary("ovale/State")
local States = __State.States
local aceEvent = LibStub:GetLibrary("AceEvent-3.0", true)
local GetTime = GetTime
local tonumber = tonumber
local __Condition = LibStub:GetLibrary("ovale/Condition")
local TestBoolean = __Condition.TestBoolean
local TestValue = __Condition.TestValue
local Compare = __Condition.Compare
local ReturnConstant = __Condition.ReturnConstant
local huge = math.huge
local __tools = LibStub:GetLibrary("ovale/tools")
local OneTimeMessage = __tools.OneTimeMessage
__exports.CombatState = __class(nil, {
constructor = function(self)
self.inCombat = false
self.combatStartTime = 0
end
})
__exports.Combat = __class(States, {
constructor = function(self, ovale, debug, ovaleSpellBook, requirement, condition)
self.ovale = ovale
self.ovaleSpellBook = ovaleSpellBook
self.requirement = requirement
self.onInitialize = function()
self.module:RegisterEvent("PLAYER_REGEN_DISABLED", self.handlePlayerRegenDisabled)
self.module:RegisterEvent("PLAYER_REGEN_ENABLED", self.handlePlayerRegenEnabled)
self.requirement:RegisterRequirement("combat", self.CombatRequirement)
end
self.onRelease = function()
self.module:UnregisterEvent("PLAYER_REGEN_DISABLED")
self.module:UnregisterEvent("PLAYER_REGEN_ENABLED")
self.requirement:UnregisterRequirement("combat")
end
self.handlePlayerRegenDisabled = function(event)
self.tracer:Debug(event, "Entering combat.")
local now = GetTime()
self.current.inCombat = true
self.current.combatStartTime = now
self.ovale:needRefresh()
self.module:SendMessage("Ovale_CombatStarted", now)
end
self.handlePlayerRegenEnabled = function(event)
self.tracer:Debug(event, "Leaving combat.")
local now = GetTime()
self.current.inCombat = false
self.ovale:needRefresh()
self.module:SendMessage("Ovale_CombatEnded", now)
end
self.CombatRequirement = function(spellId, atTime, requirement, tokens, index, targetGUID)
local verified = false
local combatFlag = tokens[index]
index = index + 1
if combatFlag then
combatFlag = tonumber(combatFlag)
if (combatFlag == 1 and self:isInCombat(atTime)) or (combatFlag ~= 1 and not self:isInCombat(atTime)) then
verified = true
end
local result = (verified and "passed") or "FAILED"
if combatFlag == 1 then
self.tracer:Log(" Require combat at time=%f: %s", atTime, result)
else
self.tracer:Log(" Require NOT combat at time=%f: %s", atTime, result)
end
else
OneTimeMessage("Warning: requirement '%s' is missing an argument.", requirement)
end
return verified, requirement, index
end
self.InCombat = function(positionalParams, namedParams, atTime)
local yesno = positionalParams[1]
local boolean = self:isInCombat(atTime)
return TestBoolean(boolean, yesno)
end
self.TimeInCombat = function(positionalParams, namedParams, atTime)
local comparator, limit = positionalParams[1], positionalParams[2]
if self:isInCombat(atTime) then
local start = self:GetState(atTime).combatStartTime
return TestValue(start, huge, 0, start, 1, comparator, limit)
end
return Compare(0, comparator, limit)
end
self.expectedCombatLength = function(positional, named, atTime)
return ReturnConstant(15 * 60)
end
self.fightRemains = function()
return ReturnConstant(15 * 60)
end
States.constructor(self, __exports.CombatState)
self.module = ovale:createModule("Combat", self.onInitialize, self.onRelease, aceEvent)
self.tracer = debug:create("Combat")
condition:RegisterCondition("incombat", false, self.InCombat)
condition:RegisterCondition("timeincombat", false, self.TimeInCombat)
condition:RegisterCondition("expectedcombatlength", false, self.expectedCombatLength)
condition:RegisterCondition("fightremains", false, self.fightRemains)
end,
isInCombat = function(self, atTime)
return self:GetState(atTime).inCombat
end,
InitializeState = function(self)
end,
ResetState = function(self)
self.next.inCombat = self.current.inCombat
self.next.combatStartTime = self.current.combatStartTime or 0
end,
CleanState = function(self)
end,
ApplySpellOnHit = function(self, spellId, targetGUID, startCast, endCast, channel)
if not self.next.inCombat and self.ovaleSpellBook:IsHarmfulSpell(spellId) then
self.next.inCombat = true
if channel then
self.next.combatStartTime = startCast
else
self.next.combatStartTime = endCast
end
end
end,
})
|
-- local dbg = require("debugger")
-- dbg.auto_where = 2
local elixir = require'cccomplete.elixir'()
local _ctxt
local function line(value)
_ctxt = {line = value}
end
local function subject()
return elixir.complete(_ctxt)
end
local function it_behaves_like(opts)
local result = subject()
it("has the correct completion", function()
assert.are.same(opts.lines, result.lines)
end)
it("has the correct offset", function()
assert.is_equal(opts.offset or 1, result.offset)
end)
it("has the correct col", function()
assert.is_equal(opts.col or 999, result.col)
end)
end
describe("elixir", function()
describe("starting a pipeline", function()
line(" some code >")
it_behaves_like{lines = {" some code", " |> "}}
end)
describe("continuing a pipeline", function()
line(" |> some_more(:code)")
it_behaves_like{lines = {_ctxt.line, " |> "}}
end)
describe("a docstring", function()
line(' @doc """')
it_behaves_like{lines = {_ctxt.line, ' ', ' """'}}
end)
describe("another docstring", function()
line(' @moduledoc """')
it_behaves_like{lines = {_ctxt.line, ' ', ' """'}}
end)
end)
describe("a docstring", function()
line(' @doc """')
it_behaves_like{lines = {_ctxt.line, ' ', ' """'}}
end)
|
--[[
@Author: Eoussama
@Version: v0.0.1
@Creation date: 6/12/2019 - 11:24PM
]]
local UtilText = require("core.utils.text")
local UtilAudio = require("core.utils.audio")
local UtilTimer = require("core.utils.timer")
local UtilBackground = require("core.utils.background")
local title = {
meta = {
id = 0,
name = "title",
active = false,
default = false
},
events = {
setActiveScene = function() end,
flickerTimerEnded = function() end
},
store = {
flicker = true
}
}
--[[
@description Title scene initialization
@param {Table} self: The table that invokes the function call
@param {Table} events: A table that holds outer event handlers
]]
function title.init(self, events)
-- Resets the game' state
global.over = false
global.paused = false
-- Recieving the event handlers
self.setActiveScene = events.setActiveScene
-- Playing ambient music
UtilAudio:play("ambient", "music", 0.2, true)
-- Starting a timer for flickering
UtilTimer:start("title_flicker", 200, true, flickerTimerEnded)
end
--[[
@description Title scene update
@param {Table} self: The table that invokes the function call
@param {Number} dt: Delta time
]]
function title.update(self, dt)
-- Checking of the 'space' key was pressed
if love.keyboard.isDown('space') and self.meta.active == true then
-- Navigating to the 'game' scene
self.setActiveScene(1)
end
end
--[[
@description Title scene drawing
@param {Table} self: The table that invokes the function call
]]
function title.draw(self)
-- Tiling the background
UtilBackground.tile(global.assets.gfx.bg.ground, 0, 0, "cover")
-- Printing 'Cöin' on the screen
UtilText.print("Cöin", "center", 200, { r = 252, g = 109, b = 25, a = 255, preserve = true }, { fnt = global.assets.fonts.huge, preserve = true })
-- Checking the visibility of the flicker
if self.store.flicker == true then
-- Printing the starting message on the screen
UtilText.print("Press SPACE to start!", "center", 300, { r = 255, g = 255, b = 255, a = 255 }, { fnt = global.assets.fonts.large, preserve = true })
end
end
--[[
@description Called when the scene is navigated away from
]]
function title:leave()
-- Stopping the active timers
UtilTimer:finish("title_flicker")
end
--[[
@description Flicker timer event handler
]]
function flickerTimerEnded()
-- Toggling the flicker status
title.store.flicker = not title.store.flicker
end
return title
|
--[[--------------------------------------------------------------------------
-- TomTom - A navigational assistant for World of Warcraft
--
-- This file contains the internal implementation of TomTom's waypoints.
-- None of these functions should be called directly by addons if they want
-- the waypoints to obey normal TomTom options and behavior. In otherwords
-- don't call TomTom:SetWaypoint() or TomTom:ClearWaypoint(), use the public
-- TomTom:AddWaypoint() and TomTom:RemoveWaypoint() instead.
----------------------------------------------------------------------------]]
local addon_name, addon = ...
local hbd = addon.hbd
local hbdp = LibStub("HereBeDragons-Pins-2.0")
-- Create a tooltip to be used when mousing over waypoints
local tooltip = CreateFrame("GameTooltip", "TomTomTooltip", UIParent, "GameTooltipTemplate")
do
-- Set the the tooltip's lines
local i = 1
tooltip.lines = {}
repeat
local line = getglobal("TomTomTooltipTextLeft"..i)
if line then
tooltip.lines[i] = line
end
i = i + 1
until not line
end
-- Store a reference to the minimap parent
local minimapParent = Minimap
-- Create a local table used as a frame pool
local pool = {}
local all_points = {}
-- Local declarations
local Minimap_OnEnter,Minimap_OnLeave,Minimap_OnUpdate,Minimap_OnClick,Minimap_OnEvent
local Arrow_OnUpdate
local World_OnEnter,World_OnLeave,World_OnClick
local square_half = math.sqrt(0.5)
local rad_135 = math.rad(135)
local function rotateArrow(self)
if self.disabled then return end
local angle = hbdp:GetVectorToIcon(self)
if not angle then return self:Hide() end
angle = angle + rad_135
if GetCVar("rotateMinimap") == "1" then
--local cring = MiniMapCompassRing:GetFacing()
local cring = GetPlayerFacing()
angle = angle - cring
end
local sin,cos = math.sin(angle) * square_half, math.cos(angle) * square_half
self.arrow:SetTexCoord(0.5-sin, 0.5+cos, 0.5+cos, 0.5+sin, 0.5-cos, 0.5-sin, 0.5+sin, 0.5-cos)
end
function TomTom:ReparentMinimap(minimap)
minimapParent = minimap
for idx, waypoint in ipairs(all_points) do
waypoint:SetParent(minimap)
end
end
local waypointMap = {}
function TomTom:SetWaypoint(waypoint, callbacks, show_minimap, show_world)
local m, x, y = unpack(waypoint)
local profile = self.profile
-- Try to acquire a waypoint from the frame pool
local point = table.remove(pool)
if not point then
point = {}
local minimap = CreateFrame("Button", nil, minimapParent)
minimap:SetHeight(20)
minimap:SetWidth(20)
minimap:RegisterForClicks("RightButtonUp")
-- Add to the "All points" table so we can reparent easily
table.insert(all_points, minimap)
minimap.icon = minimap:CreateTexture(nil,"OVERLAY")
minimap.icon:SetPoint("CENTER", 0, 0)
minimap.icon:SetBlendMode("BLEND") -- ADD/BLEND
minimap.arrow = minimap:CreateTexture(nil,"OVERLAY")
minimap.arrow:SetTexture("Interface\\AddOns\\TomTom\\Images\\MinimapArrow-Green")
minimap.arrow:SetPoint("CENTER", 0 ,0)
minimap.arrow:SetHeight(40)
minimap.arrow:SetWidth(40)
minimap.arrow:Hide()
-- Add the behavior scripts
minimap:SetScript("OnEnter", Minimap_OnEnter)
minimap:SetScript("OnLeave", Minimap_OnLeave)
minimap:SetScript("OnUpdate", Minimap_OnUpdate)
minimap:SetScript("OnClick", Minimap_OnClick)
minimap:RegisterEvent("PLAYER_ENTERING_WORLD")
minimap:SetScript("OnEvent", Minimap_OnEvent)
if not TomTomMapOverlay then
local overlay = CreateFrame("Frame", "TomTomMapOverlay", WorldMapFrame.BorderFrame)
overlay:SetFrameStrata("HIGH")
overlay:SetFrameLevel(9000)
overlay:SetAllPoints(true)
end
local worldmap = CreateFrame("Button", nil, TomTomMapOverlay)
worldmap:RegisterForClicks("RightButtonUp")
worldmap.icon = worldmap:CreateTexture(nil, "OVERLAY")
worldmap.icon:SetAllPoints()
worldmap.icon:SetBlendMode("BLEND")
worldmap:RegisterEvent("NEW_WMO_CHUNK")
worldmap:SetScript("OnEnter", World_OnEnter)
worldmap:SetScript("OnLeave", World_OnLeave)
worldmap:SetScript("OnClick", World_OnClick)
point.worldmap = worldmap
point.minimap = minimap
end
waypointMap[waypoint] = point
point.m = m
point.x = x
point.y = y
point.show_world = show_world
point.show_minimap = show_minimap
point.callbacks = callbacks
point.worldmap.callbacks = callbacks and callbacks.world
point.minimap.callbacks = callbacks and callbacks.minimap
-- Set up the minimap.icon
if waypoint.minimap_displayID then
SetPortraitTextureFromCreatureDisplayID(point.minimap.icon, waypoint.minimap_displayID)
else
point.minimap.icon:SetTexture(waypoint.minimap_icon or profile.minimap.default_icon)
end
point.minimap.icon:SetHeight(waypoint.minimap_icon_size or profile.minimap.default_iconsize)
point.minimap.icon:SetWidth(waypoint.minimap_icon_size or profile.minimap.default_iconsize)
-- Set up the worldmap.icon
if waypoint.worldmap_displayID then
SetPortraitTextureFromCreatureDisplayID(point.worldmap.icon, waypoint.worldmap_displayID)
else
point.worldmap.icon:SetTexture(waypoint.worldmap_icon or profile.worldmap.default_icon)
end
point.worldmap:SetHeight(waypoint.worldmap_icon_size or profile.worldmap.default_iconsize)
point.worldmap:SetWidth(waypoint.worldmap_icon_size or profile.worldmap.default_iconsize)
-- Process the callbacks table to put distances in a consumable format
if callbacks and callbacks.distance then
point.dlist = {}
for k,v in pairs(callbacks.distance) do
table.insert(point.dlist, k)
end
table.sort(point.dlist)
end
-- Clear the state for callbacks
point.state = nil
point.lastdist = nil
-- Link the actual frames back to the waypoint object
point.minimap.point = point
point.worldmap.point = point
point.uid = waypoint
-- Place the waypoint
-- AddMinimapIconMap(ref, icon, uiMapID, x, y, showInParentZone, floatOnEdge)
hbdp:AddMinimapIconMap(self, point.minimap, m, x, y, true, true)
if show_world then
-- show worldmap pin on its parent zone map (if any)
-- HBD_PINS_WORLDMAP_SHOW_PARENT = 1
-- show worldmap pin on the continent map
-- HBD_PINS_WORLDMAP_SHOW_CONTINENT = 2
-- show worldmap pin on the continent and world map
-- HBD_PINS_WORLDMAP_SHOW_WORLD = 3
hbdp:AddWorldMapIconMap(self, point.worldmap, m, x, y, 3)
else
point.worldmap.disabled = true
end
if not show_minimap then
-- Hide the minimap icon/arrow if minimap is off
point.minimap:EnableMouse(false)
point.minimap.icon:Hide()
point.minimap.arrow:Hide()
point.minimap.disabled = true
rotateArrow(point.minimap)
else
point.minimap:EnableMouse(true)
point.minimap.disabled = false
rotateArrow(point.minimap)
end
end
function TomTom:HideWaypoint(uid, minimap, worldmap)
local point = waypointMap[uid]
if point then
if minimap then
point.minimap.disabled = true
point.minimap:Hide()
end
if worldmap then
point.worldmap.disabled = true
point.worldmap:Hide()
end
end
end
function TomTom:ShowWaypoint(uid)
local point = waypointMap[uid]
if point then
point.minimap.disabled = not point.data.show_minimap
point.minimap:Show()
point.worldmap.disabled = not point.data.show_worldmap
point.worldmap:Show()
end
end
-- This function removes the waypoint from the active set
function TomTom:ClearWaypoint(uid)
local point = waypointMap[uid]
if point then
hbdp:RemoveMinimapIcon(self, point.minimap)
hbdp:RemoveWorldMapIcon(self, point.worldmap)
point.minimap:Hide()
point.worldmap:Hide()
-- Clear our handles to the callback tables
point.callbacks = nil
point.minimap.callbacks = nil
point.worldmap.callbacks = nil
-- Clear disabled flags
point.minimap.disabled = nil
point.worldmap.disabled = nil
point.dlist = nil
point.uid = nil
table.insert(pool, point)
waypointMap[uid] = nil
end
end
function TomTom:GetDistanceToWaypoint(uid)
local point = waypointMap[uid]
if point then
local angle, distance = hbdp:GetVectorToIcon(point.minimap)
return distance
end
end
function TomTom:GetDirectionToWaypoint(uid)
local point = waypointMap[uid]
return point and hbdp:GetVectorToIcon(point.minimap)
end
do
local tooltip_uid,tooltip_callbacks
local function tooltip_onupdate(self, elapsed)
if tooltip_callbacks and tooltip_callbacks.tooltip_update then
local dist,x,y = TomTom:GetDistanceToWaypoint(tooltip_uid)
tooltip_callbacks.tooltip_update("tooltip_update", tooltip, tooltip_uid, dist)
end
end
function Minimap_OnClick(self, button)
local data = self.callbacks
if data and data.onclick then
data.onclick("onclick", self.point.uid, self, button)
end
end
function Minimap_OnEnter(self, motion)
local data = self.callbacks
if data and data.tooltip_show then
local uid = self.point.uid
local dist,x,y = TomTom:GetDistanceToWaypoint(uid)
tooltip_uid = uid
tooltip_callbacks = data
-- Parent to UIParent, unless it's hidden
if UIParent:IsVisible() then
tooltip:SetParent(UIParent)
else
tooltip:SetParent(self)
end
tooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT")
data.tooltip_show("tooltip_show", tooltip, uid, dist)
tooltip:Show()
-- Set the update script if there is one
if data.tooltip_update then
tooltip:SetScript("OnUpdate", tooltip_onupdate)
else
tooltip:SetScript("OnUpdate", nil)
end
end
end
function Minimap_OnLeave(self, motion)
tooltip_uid,tooltip_callbacks = nil,nil
tooltip:Hide()
end
World_OnEnter = Minimap_OnEnter
World_OnLeave = Minimap_OnLeave
World_OnClick = Minimap_OnClick
local minimap_count = 0
function Minimap_OnUpdate(self, elapsed)
local angle, dist = hbdp:GetVectorToIcon(self)
local disabled = self.disabled
if not dist then
self:Hide()
return
end
minimap_count = minimap_count + elapsed
if minimap_count < 0.1 then return end
-- Reset the counter
minimap_count = 0
local edge = hbdp:IsMinimapIconOnEdge(self)
local data = self.point
local callbacks = data.callbacks
if edge then
-- Check to see if this is a transition
if not disabled then
self.icon:Hide()
self.arrow:Show()
-- Rotate the icon, as required
angle = angle + rad_135
if GetCVar("rotateMinimap") == "1" then
--local cring = MiniMapCompassRing:GetFacing()
local cring = GetPlayerFacing()
angle = angle - cring
end
local sin,cos = math.sin(angle) * square_half, math.cos(angle) * square_half
self.arrow:SetTexCoord(0.5-sin, 0.5+cos, 0.5+cos, 0.5+sin, 0.5-cos, 0.5-sin, 0.5+sin, 0.5-cos)
end
else
if not disabled then
self.icon:Show()
self.arrow:Hide()
end
end
if callbacks and callbacks.distance then
local list = data.dlist
local state = data.state
local newstate
-- Calculate the initial state
if not state then
for i=1,#list do
if dist <= list[i] then
state = i
break
end
end
-- Handle the case where we're outside the largest circle
if not state then state = -1 end
data.state = state
else
-- Calculate the new state
for i=1,#list do
if dist <= list[i] then
newstate = i
break
end
end
-- Handle the case where we're outside the largest circle
if not newstate then newstate = -1 end
end
-- If newstate is set, then this is a transition
-- If only state is set, this is the initial state
if state ~= newstate then
-- Handle the initial state
newstate = newstate or state
local distance = list[newstate]
local callback = callbacks.distance[distance]
if callback then
callback("distance", data.uid, distance, dist, data.lastdist)
end
data.state = newstate
end
-- Update the last distance with the current distance
data.lastdist = dist
end
end
function Minimap_OnEvent(self, event, ...)
if event == "PLAYER_ENTERING_WORLD" then
local data = self.point
if data and data.uid and waypointMap[data.uid] then
hbdp:AddMinimapIconMap(TomTom, self, data.m, data.x, data.y, true)
end
end
end
end
|
bhamuka_all_consuming_god_consume_souls = class({})
LinkLuaModifier( 'bhamuka_all_consuming_god_consume_souls_modifier', 'encounters/bhamuka_all_consuming_god/bhamuka_all_consuming_god_consume_souls_modifier', LUA_MODIFIER_MOTION_NONE )
function bhamuka_all_consuming_god_consume_souls:OnSpellStart()
--- Get Caster, Victim, Player, Point ---
local caster = self:GetCaster()
local caster_loc = caster:GetAbsOrigin()
local playerID = caster:GetPlayerOwnerID()
local player = PlayerResource:GetPlayer(playerID)
local team = caster:GetTeamNumber()
local victim = caster
local victim_loc = victim:GetAbsOrigin()
--- Get Special Values ---
local duration = self:GetSpecialValueFor("duration")
local damage = self:GetSpecialValueFor("damage")
local damage_interval = self:GetSpecialValueFor("damage_interval")
local delay = self:GetSpecialValueFor("delay")
local soul_consumed_per_second = self:GetSpecialValueFor("soul_consumed_per_second")
caster:AddNewModifier(caster, self, "casting_rooted_modifier", {duration=duration+delay})
DisableMotionControllers(caster, duration+delay)
EncounterUnitWarning(caster, delay, true, nil) --nil=yellow, "red", "orange", "green"
-- Sound --
local sound = {"outworld_destroyer_odest_ability_eclipse_02", "outworld_destroyer_odest_ability_eclipse_10",
"outworld_destroyer_odest_ability_eclipse_06", "outworld_destroyer_odest_ability_eclipse_07",
"outworld_destroyer_odest_ability_eclipse_08"}
EmitAnnouncerSound( sound[RandomInt(1, #sound)] )
local timer = Timers:CreateTimer(2.00, function()
local sound = {"outworld_destroyer_odest_laugh_01", "outworld_destroyer_odest_laugh_02",
"outworld_destroyer_odest_laugh_03", "outworld_destroyer_odest_laugh_04",
"outworld_destroyer_odest_laugh_05", "outworld_destroyer_odest_laugh_06",
"outworld_destroyer_odest_laugh_07", "outworld_destroyer_odest_laugh_08",
"outworld_destroyer_odest_laugh_09", "outworld_destroyer_odest_laugh_10",
"outworld_destroyer_odest_laugh_11", "outworld_destroyer_odest_laugh_12",}
EmitAnnouncerSound( sound[RandomInt(1, #sound)] )
end)
PersistentTimer_Add(timer)
self.timers = {}
local timer = Timers:CreateTimer(delay, function()
-- Animation --
StartAnimation(caster, {duration=duration, activity=ACT_DOTA_RUN, rate=0.75})
-- Sound --
caster:EmitSound("Hero_ObsidianDestroyer.SanityEclipse")
for _,victim in pairs(GetHeroesAliveEntities()) do
-- Modifier --
local modifier = victim:FindModifierByName("bhamuka_all_consuming_god_consume_souls_modifier")
if modifier == nil then
local modifier = victim:AddNewModifier(caster, self, "bhamuka_all_consuming_god_consume_souls_modifier", {})
PersistentModifier_Add(modifier)
modifier:SetStackCount(0)
end
self.timers[_] = Timers:CreateTimer(0, function()
local fear_angle = 150
local hero_angle = victim:GetAnglesAsVector().y
local origin_difference = victim:GetAbsOrigin() - caster_loc
local origin_difference_radian = math.atan2(origin_difference.y, origin_difference.x)
origin_difference_radian = origin_difference_radian * 180
local caster_angle = origin_difference_radian / math.pi
caster_angle = caster_angle + 180.0
local result_angle = caster_angle - hero_angle
result_angle = math.abs(result_angle)
if ( result_angle >= 0 and result_angle <= (fear_angle / 2) ) or
( result_angle >= (360 - (fear_angle / 2)) and result_angle <= 360 ) then
-- Particle --
local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_bane/bane_fiendsgrip_ground_rubble.vpcf", PATTACH_ABSORIGIN, victim)
ParticleManager:SetParticleControl( particle, 0, victim:GetAbsOrigin() )
ParticleManager:ReleaseParticleIndex( particle )
particle = nil
-- Modifier --
local modifier = victim:FindModifierByName("bhamuka_all_consuming_god_consume_souls_modifier")
modifier:SetStackCount( modifier:GetStackCount() + (soul_consumed_per_second * damage_interval) )
modifier:ForceRefresh()
-- Apply Damage --
EncounterApplyDamage(victim, caster, self, damage*damage_interval, DAMAGE_TYPE_MAGICAL, DOTA_DAMAGE_FLAG_NONE)
end
return damage_interval
end)
PersistentTimer_Add(self.timers[_])
end
end)
PersistentTimer_Add(timer)
local timer = Timers:CreateTimer(delay + duration, function()
for _,timer in pairs(self.timers) do
Timers:RemoveTimer(self.timers[_])
self.timers[_] = nil
end
end)
PersistentTimer_Add(timer)
end
function bhamuka_all_consuming_god_consume_souls:OnAbilityPhaseStart()
local caster = self:GetCaster()
local playerID = caster:GetPlayerOwnerID()
local player = PlayerResource:GetPlayer(playerID)
return true
end
function bhamuka_all_consuming_god_consume_souls:GetManaCost(abilitylevel)
return self.BaseClass.GetManaCost(self, abilitylevel)
end
function bhamuka_all_consuming_god_consume_souls:GetCooldown(abilitylevel)
return self.BaseClass.GetCooldown(self, abilitylevel)
end
|
--------------------------------------------------------------------------------
-- login.lua
--------------------------------------------------------------------------------
local string_format = string.format
local actor = tengine.actor
local ERROR_MSG = tengine.ERROR_MSG
local p = tengine.p
local account = require('framework.model.account')
local db = require "db"
local _M = {}
function _M.login_account(info)
-- 1. 查找玩家
local succ, ret = pcall(db.check_account, info.account)
if not succ then
ERROR_MSG("db check account failed !!! %s", succ)
return
end
-- 如果失败直接返回
if not ret then
return
end
return ret
end
-- 游客登陆
function _M.visitor_login(message)
p("visitor_login", message)
local _driver = db.driver()
message.account = "dotest"
local _account = account:with(_driver, "account", 'dotest')
if _account then
return
end
local id = assert(account:save(_driver, message))
_account = account:fetch(_driver, id)
return _account
end
return _M
|
data:extend({
{
type = "generator",
name = "biotech-wind-turbine",
icon = "__BioTech__/graphics/icons/wind_turbine_icon.png",
flags = {"placeable-neutral","player-creation"},
minable = {mining_time = 1, result = "biotech-wind-turbine"},
max_health = 50,
corpse = "big-remnants",
effectivity = 1.5,
fluid_usage_per_tick = 0.004,
resistances =
{
{
type = "physical",
percent = 10
}
},
collision_box = {{-0.6, -0.6}, {0.6, 0.6}},
selection_box = {{-0.8, -0.8}, {0.8, 0.8}},
drawing_box = {{-0.5, -3}, {3.2, 0.5}},
fluid_box =
{
base_area = 100,
pipe_connections =
{
--{ position = {-1, 2} },
--{ position = {-1,-2} },
},
},
energy_source =
{
type = "electric",
usage_priority = "primary-output"
},
horizontal_animation =
{
filename = "__BioTech__/graphics/entities/wind-turbine/wind_turbine_sheet_4.png",
width = 175,
height = 175,
frame_count = 20,
line_length = 5,
shift = {1.7,-1.4},
--run_mode="backward"
},
vertical_animation =
{
filename = "__BioTech__/graphics/entities/wind-turbine/wind_turbine_sheet_4.png",
width = 175,
height = 175,
frame_count = 20,
line_length = 5,
shift = {1.7,-1.4},
run_mode="backward"
},
smoke =
{
},
working_sound =
{
sound =
{
filename = "__base__/sound/train-wheels.ogg",
volume = 0.6
},
match_speed_to_activity = true,
},
min_perceived_performance = 0.25,
performance_to_sound_speedup = 0.2
},
{
type = "fluid",
name = "wind",
default_temperature = 0,
max_temperature = 100,
heat_capacity = "1KJ",
base_color = {r=0, g=0.34, b=0.6},
flow_color = {r=0.7, g=0.7, b=0.7},
icon = "__BioTech__/graphics/icons/wind_turbine_icon.png",
order = "a[fluid]-z[wind]",
pressure_to_speed_ratio = 0.4,
flow_to_energy_ratio = 0.59,
},
})
|
-- Copyright (c) 2015-present, 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.
local babi = require 'babi'
require 'babi.tasks.Counting'
local Listing, parent = torch.class('babi.Listing', 'babi.Counting', babi)
function Listing:generate_story(...)
local story, knowledge = parent:generate_story(...)
for i = 1, #story do
if torch.isTypeOf(story[i], 'babi.Question') then
story[i].kind = 'eval'
end
end
return story, knowledge
end
return Listing
|
print("toto")
local m = require("mod")
m.test()
test2()
local log = require('log')
log.info("Test")
local data = require('data')
print(data.toYaml({
toto = 'tata'
}))
local t = {}
t[1] = "toto"
t[2] = "titi"
t[3] = "tata"
t[4] = "tutu"
t[5] = "foo"
print(#t)
print(data.toJson(t))
print(data.toYaml(t))
|
--[[
-- log.lua
--
-- Copyright (c) 2016 rxi
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
-- Modefy by CandyMi In 2018.12.18
log的内部方法包括:
log.trace(...) 紫色
log.debug(...) 天蓝色
log.info(...) 绿色
log.warn(...) 黄色
log.error(...) 红色
log.fatal(...) 粉色
log.usecolor
默认情况下: 这个为true! 如果你的终端不支持ANSI颜色转义码, 请将它设置为false或者nil.
log.outfile
将log输出到outfile字符串指定的文件(路径).
log.level
请参考使用方法相关method
--]]
local debug_getinfo = debug.getinfo
local tostring = tostring
local select = select
local ipairs = ipairs
local type = type
local concat = table.concat
local date = os.date
local open = io.open
local ceil = math.ceil
local floor = math.floor
local toint = math.tointeger
local fmt = string.format
local log = { _version = "0.1.0" }
log.usecolor = true
log.outfile = nil
log.level = "trace"
local modes = {
{ name = "trace", color = "\27[34m", },
{ name = "debug", color = "\27[36m", },
{ name = "info", color = "\27[32m", },
{ name = "warn", color = "\27[33m", },
{ name = "error", color = "\27[31m", },
{ name = "fatal", color = "\27[35m", },
}
local levels = {}
for i, v in ipairs(modes) do
levels[v.name] = i
end
local round = function(x, increment)
if not toint(x) then
increment = increment or 1
x = x / increment
return (x > 0 and floor(x + .5) or ceil(x - .5)) * increment
end
return x
end
local _tostring = tostring
local tostring = function(...)
local t = {}
for i = 1, select('#', ...) do
local x = select(i, ...)
if type(x) == "number" then
x = round(x, .01)
end
t[#t + 1] = _tostring(x)
end
return concat(t, " ")
end
for i, x in ipairs(modes) do
local nameupper = x.name:upper()
log[x.name] = function(...)
-- Return early if we're below the log level
if i < levels[log.level] then
return
end
local msg = tostring(...)
local info = debug_getinfo(2, "Sl")
local lineinfo = "[C]:[-1]"
if info then
lineinfo = info.short_src .. ":" .. info.currentline
end
-- Output to console
print(fmt("%s[%s][%s]%s %s: %s",
log.usecolor and x.color or "",
nameupper,
date("%Y/%m/%d %H:%M:%S"),
log.usecolor and "\27[0m" or "",
lineinfo,
msg))
-- Output to log file
if log.outfile then
local fp = open(log.outfile, "a")
if not fp then
return log.warn("Cant't write info to "..(log.outfile or ""))
end
fp:write(fmt("[%s][%s] %s: %s\n", nameupper, date("%Y/%m/%d %H:%M:%S"), lineinfo, msg))
fp:close()
end
end
end
return log
|
local M = {}
M.setup = function()
local status_ok, cc = pcall(require, "virt-column")
if not status_ok then
return
end
cc.setup_buffer({ virtcolumn = "80,120", char = "▏" })
end
vim.cmd [[
augroup virtcolumn
autocmd!
autocmd FileType * if index(["netrw", "NvimTree", "neo-tree", "UltestAttach", "dap-float", "Trouble", "lspinfo", "qf", "harpoon", "toggleterm", "packer"], &ft) == -1 | lua require("windows.colorcolumn").setup()
augroup end
]]
return M
|
ENT.RenderGroup = RENDERGROUP_OPAQUE
ENT.Base = "fighter_base"
ENT.Type = "vehicle"
ENT.PrintName = "NTB-630 Bomber"
ENT.Author = "Liam0102, Jellyton"
ENT.Category = "Star Wars Vehicles: In Development";
list.Set("SWVehiclesEU", ENT.PrintName, ENT);
ENT.AutomaticFrameAdvance = true
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.EntModel = "models/sweaw/ships/rep_ntb630_servius.mdl"
ENT.Vehicle = "ntbbomber"
ENT.Allegiance = "Republic"
ENT.StartHealth = 1500
list.Set("SWVehicles", ENT.PrintName, ENT);
if SERVER then
ENT.FireSound = Sound("weapons/xwing_shoot.wav")
ENT.NextUse = {
Wings = CurTime(),
Use = CurTime(),
Fire = CurTime()
}
AddCSLuaFile()
function ENT:SpawnFunction(pl, tr)
local e = ents.Create("ntbbomber")
if not IsValid(e) then return end
e:SetPos(tr.HitPos + Vector(0, 0, 20))
e:SetModelScale( e:GetModelScale() * 0.75, 0 )
e:SetAngles(Angle(0, pl:EyeAngles().Yaw, 0))
e:Spawn()
e:Activate()
return e
end
function ENT:Initialize()
self:SetNWInt("Health", self.StartHealth)
self:SetNWBool("InShip", false)
self.WeaponLocations = {
Right = self:GetPos() + self:GetForward() * 520 + self:GetRight() * 25 + self:GetUp() * 40,
Left = self:GetPos() + self:GetForward() * 520 + self:GetRight() * -25 + self:GetUp() * 40
}
self.WeaponsTable = {}
self.BoostSpeed = 900
self.ForwardSpeed = 900
self.UpSpeed = 600
self.AccelSpeed = 7
self.CanBack = false
self.CanRoll = true
self.CanStrafe = false
self.CanStandby = true
self.CanShoot = true
self.FireDelay = 0.3
self.OverheatAmount = 20
self.DontOverheat = false
self.Cooldown = 2
self.NextBlast = 1;
self.Bullet = CreateBulletStructure(50, "blue")
self.ExitModifier = {
x = 0,
y = -400,
z = 0
}
self.BaseClass.Initialize(self)
end
function ENT:Enter(p)
self:SetNWBool("InShip", true)
self.BaseClass.Enter(self, p)
end
function ENT:Exit(kill)
self.IsFPV = false
self:SetNWBool("InShip", false)
self.BaseClass.Exit(self, kill)
end
function ENT:Think()
if(self.Inflight) then
if(IsValid(self.Pilot)) then
if(IsValid(self.Pilot)) then
if(self.Pilot:KeyDown(IN_ATTACK2) and self.NextUse.FireBlast < CurTime()) then
self.BlastPositions = {
self:GetPos() + self:GetForward() * -20 + self:GetRight() * 0 + self:GetUp() * -20, //1
self:GetPos() + self:GetForward() * -20 + self:GetRight() * 0 + self:GetUp() * -20, //2
self:GetPos() + self:GetForward() * -20 + self:GetRight() * 0 + self:GetUp() * -20, //3
self:GetPos() + self:GetForward() * -20 + self:GetRight() * 0 + self:GetUp() * -20, //4
self:GetPos() + self:GetForward() * -20 + self:GetRight() * 0 + self:GetUp() * -20, //5
self:GetPos() + self:GetForward() * -20 + self:GetRight() * 0 + self:GetUp() * -20, //6
}
self:FirentbbomberBlast(self.BlastPositions[self.NextBlast],true,0.9,600,false,20);
self.NextBlast = self.NextBlast + 1;
if(self.NextBlast == 7) then
self.NextUse.FireBlast = CurTime()+5;
self:SetNWBool("OutOfMissiles",true);
self:SetNWInt("FireBlast",self.NextUse.FireBlast)
self.NextBlast = 1;
end
end
end
end
if(self.NextUse.FireBlast < CurTime()) then
self:SetNWBool("OutOfMissiles",false);
end
self:SetNWInt("Overheat",self.Overheat);
self:SetNWBool("Overheated",self.Overheated);
end
self.BaseClass.Think(self);
end
function ENT:FirentbbomberBlast(pos,gravity,vel,dmg,white,size,snd)
if(self.NextUse.FireBlast < CurTime()) then
local e = ents.Create("cannon_blast");
e.Damage = dmg or 600;
e.IsWhite = white or false;
e.StartSize = 30;
e.EndSize = 5;
local sound = snd or Sound("weapons/ywing_bomb.wav");
e:SetPos(pos);
e:Spawn();
e:Activate();
e:Prepare(self,sound,gravity,vel);
e:SetColor(Color(255,255,255,1));
end
end
end
if CLIENT then
function ENT:SpawnCockpit()
self.Cockpit = ents.CreateClientProp()
self.Cockpit:SetModel("models/ywing/ywing_cockpit_b.mdl")
self.Cockpit:SetPos(self:GetPos())
self.Cockpit:SetAngles(self:GetAngles())
self.Cockpit:Spawn()
self.Cockpit:SetParent(self)
self.Cockpit:SetNoDraw(true)
end
function ENT:Remove()
if IsValid(self.Cockpit) then
self.Cockpit:Remove()
end
self.BaseClass.Remove(self)
end
function ENT:Draw()
if self.IsFPV and self:GetNWBool("InShip",false) then
if not IsValid(self.Cockpit) then
self:SpawnCockpit()
else
self.Cockpit:DrawModel()
end
else
self:DrawModel()
end
end
ENT.CanFPV = true
ENT.EnginePos = {}
ENT.ViewDistance = 800;
ENT.ViewHeight = 200;
ENT.FPVPos = Vector(245,0,88);
ENT.Sounds = {
Engine = Sound("vehicles/ywing_eng_loop.wav"),
}
function ENT:FlightEffects()
local normal = -self:GetForward()
local roll = math.Rand(-90, 90)
local id = self:EntIndex()
self.EnginePos = {self:GetPos() + self:GetForward() * -230 + self:GetRight() * 190 + self:GetUp() * 40, self:GetPos() + self:GetForward() * -230 + self:GetRight() * -190 + self:GetUp() * 40}
for k, v in pairs(self.EnginePos) do
local blue = self.FXEmitter:Add("sprites/bluecore", v)
blue:SetVelocity(normal)
blue:SetDieTime(0.1)
blue:SetStartAlpha(155)
blue:SetEndAlpha(5)
blue:SetStartSize(45)
blue:SetEndSize(15)
blue:SetRoll(roll)
blue:SetColor(250, 85, 247)
end
end
function ENT:Think()
self.BaseClass.Think(self)
local Flying = self:GetNWBool("Flying" .. self.Vehicle)
local TakeOff = self:GetNWBool("TakeOff")
local Land = self:GetNWBool("Land")
if Flying then
if not (TakeOff or Land) then
self:FlightEffects()
end
if LocalPlayer():KeyDown(IN_WALK) and self.NextView < CurTime() then
self.IsFPV = not self.IsFPV
self.NextView = CurTime() + 1
end
end
end
hook.Add("HUDPaint", "ntbbomberReticle", function()
local ship = LocalPlayer():GetNWEntity("ntbbomber")
if LocalPlayer():GetNWBool("Flyingntbbomber") and IsValid(ship) then
SW_HUD_DrawHull(1500)
SW_WeaponReticles(ship)
SW_HUD_DrawOverheating(ship)
SW_BlastIcon(ship,5)
SW_HUD_Compass(ship, ScrW() / 2, ScrH() * 0.775)
SW_HUD_DrawSpeedometer()
end
end)
end
|
---------------------------------------------------------------------------------------------------
---boss_hitbox_prefab.lua
---author: Karl
---date created: 2021.6.1
---desc: Defines the base objects for enemies that have hitboxes; a hitbox here has a disk shaped
--- collision box with some hp, the hitbox is killed when hp reaches or goes below 0
---------------------------------------------------------------------------------------------------
local Prefab = require("core.prefab")
local EnemyHitboxPrefab = require("BHElib.units.enemy.enemy_hitbox_prefab")
---@class Prefab.BossHitbox:Prefab.EnemyHitbox
local M = Prefab.NewX(EnemyHitboxPrefab, "Prefab.BossHitobx")
---------------------------------------------------------------------------------------------------
---init
---@param radius number
---@param hp number initial hp
---@param session AttackSession
function M:init(radius, hp, session)
EnemyHitboxPrefab.init(self, radius, hp, session)
self.session = session
session:addHitbox(self)
self.is_del = false
end
---------------------------------------------------------------------------------------------------
---deletion
function M:del()
if not self.is_del then
self.session:onHitboxDel(self)
end
self.is_del = true
end
function M:kill()
if not self.is_del then
self.session:onHitboxKill(self)
end
self.is_del = true
end
---------------------------------------------------------------------------------------------------
---collision events
---@param other Prefab.PlayerBullet
function M:onPlayerBulletCollision(other)
other:onEnemyCollision(self)
if self.hp < self.max_hp * 0.1 then
other:playLowHpHitSound()
else
other:playNormalHitSound()
end
end
Prefab.Register(M)
return M
|
--- Slice part of a table and return a new copy
---
--- Note : This methods does not check if tbl is a table, it does not check
--- if first and last are valid... it is the responsibility of the caller
--- to make sure all args are valid.
---
-- @param tbl the table to slice
-- @param first (optional) the starting index (default 1)
-- @param last (optional) the last index (default #tbl)
-- @param step (optinal) skip elements between first...last (default 1)
-- @return The table slice
function table.slice(tbl, first, last, step)
local sliced = {}
for i = first or 1, last or #tbl, step or 1 do
sliced[#sliced+1] = tbl[i]
end
return sliced
end
--- Return all the keys in the given table. The table is assume not to be
--- an array.
-- @param tbl the table
-- @return Table an array of all the keys in the given table
function table.keys(tbl)
local keys = {};
for k,v in pairs(tbl) do
table.insert(keys, k);
end
return keys;
end
--- Used to find out if the provided table contains the specified value.
-- @param tbl The table
-- @param value The value you're looking for
-- @return True if the value exists in the table, false if not
function table.contains(tbl, value)
local found = false;
for k,v in pairs(tbl) do
if v == value then
found = true;
break;
end
end
return found;
end
--- Used to insert all elements into the provided table. This function is like
--- table.insert(tbl, index, value) except that values is expected to be an array.
--- However, values may not need to be an array and the function will act just like
--- table.insert.
-- @param tbl The table
-- @param index The index from which insertion will start
-- @param values The value or values to insert.
function table.insertAll(tbl, index, values)
if type(index) == "table" or values == nil then
values = index;
index = #tbl + 1;
elseif type(index) ~= "number" then
index = nil;
end
index = math.max(index, 1);
if type(values) ~= "table" then
if index then
table.insert(tbl, index, values);
else
table.insert(tbl, values);
end
else
for i = 1, #values do;
table.insert(tbl, index + i - 1, values[i]);
end;
end
return tbl;
end
--- Used to remove all elements from the provided table matching a given value.
-- @param tbl The table
-- @param value The value you want to remove
-- @return The number of times value was removed from the array
function table.removeAll(tbl, value)
local n = #tbl;
local j = 0;
local removed = 0;
-- 1. Remove all values from array and/or table
for k,v in pairs(tbl) do
if v == value then
tbl[k] = nil;
removed = removed + 1;
end
end
-- 2. shifting elements
for i = 1, n do
if tbl[i] ~= nil then
j = j + 1;
tbl[j] = tbl[i];
end
end
-- 3. Compacting
for i = j + 1, n do
tbl[i] = nil;
end
return removed;
end
--- Pluck a value from each table elements and return them as an array.
--- If an element is not a table, or does not possess the specified key,
--- then it will be skipped. Otherwise, default will be used.
-- @param tbl The table
-- @param key The key's value to pluck from each element
-- @param default (optional) If plucked value is nil, or missing, the value to be used instead
-- @return The resulting table
function table.pluck(tbl, key, default)
local res = {};
for k,v in pairs(tbl) do
if type(v) == "table" and v[key] then
table.insert(res, v[key]);
elseif default ~= nil then
table.insert(res, default);
end
end
return res;
end
|
local Library = require "CoronaLibrary"
local sprite = Library:new{ name='sprite', publisherId='com.' }
local function toImageSheet( spriteSet )
assert( spriteSet.spriteSheet, "toImageSheet(): Bad spriteSet parameter: spriteSet.spriteSheet is nil" )
local options
local spriteSheet = spriteSet.spriteSheet
if spriteSheet.format == "simple" then
local w = spriteSheet.width
local h = spriteSheet.height
options =
{
width = w,
height = h,
numFrames = spriteSet.numFrames,
}
elseif spriteSheet.format == "complex" then
assert( spriteSheet.spriteSheetFrames, "spriteSheet.spriteSheetFrames is nil")
options =
{
spriteSheetFrames = spriteSheet.spriteSheetFrames
}
end
local filename = spriteSheet.filename
local baseDir = spriteSheet.baseDir
if baseDir then
return graphics.newImageSheet( filename, baseDir, options )
else
return graphics.newImageSheet( filename, options )
end
end
local function toSequenceData( spriteSet )
assert( spriteSet.spriteSheet, "toSequenceData(): Bad spriteSet parameter: spriteSet.spriteSheet is nil" )
local spriteSheet = spriteSet.spriteSheet
local default =
{
name = "default",
start = spriteSet.startFrame,
count = spriteSet.numFrames,
}
local sequenceData = spriteSet.sequences or {}
table.insert( sequenceData, default )
return sequenceData
end
sprite.newSprite = function( spriteSet )
assert( spriteSet, "spriteSet is nil", "sprite.newSprite(): spriteSet is nil." )
local s
if spriteSet.type == "newSpriteArgs" then
assert( type( spriteSet.args ) == "table", "sprite.newSprite(): 'spriteSet.args' is nil." )
s = display.newSprite( unpack( spriteSet.args ) )
else
assert( spriteSet.type == "spriteSet" or spriteSet.type == "spriteMultiSet", "sprite.newSprite(): incorrect 'spriteSet.type'." )
local imageSheet = toImageSheet( spriteSet )
local sequenceData = toSequenceData( spriteSet )
assert( sequenceData, "sprite.newSprite(): failed to create sequenceData" )
s = display.newSprite( imageSheet, sequenceData )
end
function s:prepare( name )
s:setSequence( name )
end
return s
end
-- sprite.add( spriteSet, sequenceName, startFrame, frameCount, time, [loopParam] )
sprite.add = function( spriteSet, sequenceName, startFrame, frameCount, time, loopParam )
assert( spriteSet, "spriteSet is nil", "sprite.addSprite(): spriteSet is nil." )
assert( spriteSet.type == "spriteSet", "sprite.addSprite(): incorrect 'spriteSet.type'.")
local sequences = spriteSet.sequences
if not sequences then
sequences = {}
spriteSet.sequences = sequences
end
table.insert( sequences, item )
local loopCount = 0
local loopDirection
if loopParam and 0 ~= loopParam then
loopCount = 1
if -1 == loopParam then
loopDirection = "bounce"
elseif -2 == loopParam then
loopCount = 0
loopDirection = "bounce"
end
end
local item =
{
name = sequenceName,
start = startFrame,
count = frameCount,
time = time,
loopCount = loopCount,
loopDirection = loopDirection,
}
table.insert( sequences, item )
end
local function spriteSheetToImageSheet( spriteSheet )
assert( false, "spriteSheetToImageSheet() is not implemented." )
return nil
end
-- sprite.newSpriteMultiSet()
sprite.newSpriteMultiSet = function( sequences )
assert( #sequences > 0, "sprite.newSpriteMultiSet(): sequences array is empty." )
-- Assume first element defines default sheet
local defaultSheet = spriteSheetToImageSheet( sequences[1].sheet )
assert( defaultSheet, "sprite.newSpriteMultiSet(): no sheet param." )
local sequenceData = {}
for i=1,#sequences do
local seq = sequences[i]
local imageSheet = spriteSheetToImageSheet( seq.sheet )
local data =
{
sheet = imageSheet,
frames = seq.frames,
}
table.insert( sequenceData, data )
end
local result =
{
type = "newSpriteArgs",
args = { defaultSheet, sequenceData, }
}
return sequences
end
-- sprite.newSpriteSet( spriteSheet, startFrame, frameCount )
sprite.newSpriteSet = function( spriteSheet, startFrame, frameCount )
assert( spriteSheet, "sprite.newSpriteSet(): spriteSheet is nil." )
assert( spriteSheet.type == "spriteSheet", "sprite.newSpriteSet(): spriteSheet is malformed." )
local result =
{
type = "spriteSet",
spriteSheet = spriteSheet,
numFrames = frameCount,
startFrame=startFrame,
}
return result
end
-- sprite.newSpriteSheet( spriteSheetFile, [baseDir,] frameWidth, frameHeight )
sprite.newSpriteSheet = function( ... )
local args = { ... }
local spriteSheetFile = args[1]
local nextArg = 2
local baseDir = args[nextArg]
if type(baseDir) ~= "userdata" then
baseDir = nil
else
nextArg = nextArg + 1
end
local frameWidth, frameHeight = args[nextArg], args[nextArg+1]
local result =
{
type = "spriteSheet",
format = "simple",
width = frameWidth, height = frameHeight,
filename = spriteSheetFile, baseDir = baseDir,
}
function result:dispose()
-- no-op
end
return result
end
-- sprite.newSpriteSheetFromData( spriteSheetFile, [baseDir,] coordinateData )
sprite.newSpriteSheetFromData = function( ... )
local args = { ... }
local spriteSheetFile = args[1]
local nextArg = 2
local baseDir = args[nextArg]
if type(baseDir) ~= "userdata" then
baseDir = nil
else
nextArg = nextArg + 1
end
local coordinateData = args[nextArg]
local result =
{
type = "spriteSheet",
format = "complex",
spriteSheetFrames = coordinateData.frames,
filename = spriteSheetFile, baseDir = baseDir,
}
function result:dispose()
-- no-op
end
return result
end
return sprite
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
module('QueryClientIpArg_pb')
QUERYCLIENTIPARG = protobuf.Descriptor();
local QUERYCLIENTIPARG_PARAM_FIELD = protobuf.FieldDescriptor();
QUERYCLIENTIPARG_PARAM_FIELD.name = "param"
QUERYCLIENTIPARG_PARAM_FIELD.full_name = ".KKSG.QueryClientIpArg.param"
QUERYCLIENTIPARG_PARAM_FIELD.number = 1
QUERYCLIENTIPARG_PARAM_FIELD.index = 0
QUERYCLIENTIPARG_PARAM_FIELD.label = 1
QUERYCLIENTIPARG_PARAM_FIELD.has_default_value = false
QUERYCLIENTIPARG_PARAM_FIELD.default_value = 0
QUERYCLIENTIPARG_PARAM_FIELD.type = 13
QUERYCLIENTIPARG_PARAM_FIELD.cpp_type = 3
QUERYCLIENTIPARG.name = "QueryClientIpArg"
QUERYCLIENTIPARG.full_name = ".KKSG.QueryClientIpArg"
QUERYCLIENTIPARG.nested_types = {}
QUERYCLIENTIPARG.enum_types = {}
QUERYCLIENTIPARG.fields = {QUERYCLIENTIPARG_PARAM_FIELD}
QUERYCLIENTIPARG.is_extendable = false
QUERYCLIENTIPARG.extensions = {}
QueryClientIpArg = protobuf.Message(QUERYCLIENTIPARG)
|
local mapa = {
ambient="0.1,0.1,0.1",
gravity="0 -9.8 0",
entities={
{
name="Sinbad",
id=1,
components={
transform={
position="0,0,0",
rotation="0,0,0",
scale="1,1,1",
parent="-1"
},
rigidbody={
shape="-1",
mass="10",
inertia="0,0,0",
restitution="0.2",
damping="0.2,0.2",
trigger="false",
kinematic="false"
},
camera={
near="0.1",
far="1000",
autoaspect="true",
aspect="1.78",
fov="50",
proyection="1",
viewport="0,0,1,1",
color="0,0,0"
},
renderer={
mesh="Sinbad.mesh",
material="",
visible="false"
},
playercontroller={
speed="175",
maxJump="2",
jumpStr="7200"
}
}
},
--{
-- name="Drone",
-- id=5,
-- components={
-- transform={
-- position="0,40,0",
-- rotation="0,90,0",
-- scale="1,1,1"
-- },
-- renderer={
-- mesh="Sinbad.mesh",
-- material="",
-- visible="true"
-- },
-- rigidbody={
-- shape="0",
-- mass="54",
-- inertia="0,0,0",
-- restitution="0.2",
-- damping="0.2,0.2",
-- trigger="false",
-- kinematic="true"
-- },
-- shotai={
-- objective="1",
-- proyectile="bala.prefab",
-- rof="3"
-- }
-- }
--},
{
name="Luz",
id=3,
components={
transform={
position="50,0,0",
rotation="290,145,0",
scale="1,1,1",
parent="-1"
},
light={
type="1",
attenuation="",
shadows="true",
diffuse="0.7,0.7,0,1",
specular="1,1,1,1",
spotinner="",
spotouter=""
}
}
},
{
name="Suelo",
id=4,
components={
transform={
position="0,-100,0",
rotation="0,0,0",
scale="0.75,0.1,0.75",
parent="-1"
},
renderer={
mesh="cube.mesh",
material="",
visible="true"
},
rigidbody={
shape="0",
mass="0",
inertia="0,0,0",
restitution="0.2",
damping="0.2,0.2",
trigger="false",
kinematic="false"
},
floor={
}
}
},
{
name="Plat1",
id=5,
components={
transform={
position="50,-98,-100",
rotation="0,0,0",
scale="0.7,0.1,0.7",
parent="-1"
},
renderer={
mesh="cube.mesh",
material="",
visible="true"
},
rigidbody={
shape="0",
mass="0",
inertia="0,0,0",
restitution="0.2",
damping="0.2,0.2",
trigger="false",
kinematic="false"
},
floor={
}
}
},
{
name="Plat2",
id=6,
components={
transform={
position="10,-97,-200",
rotation="90,0,0",
scale="0.7,0.1,0.7",
parent="-1"
},
renderer={
mesh="cube.mesh",
material="",
visible="true"
},
rigidbody={
shape="0",
mass="0",
inertia="0,0,0",
restitution="0.2",
damping="0.2,0.2",
trigger="false",
kinematic="false",
parent="-1"
},
floor={
}
}
}
}
}
function GetMapa ()
return mapa
end
|
local L = LibStub('AceLocale-3.0'):NewLocale('tdInspect', 'enUS', true)
if not L then
return
end
-- @localization(locale=""enUS", format="lua_additive_table", table-name="L", same-key-is-true=true)@
-- @debug@
-- @import@
L['Show Model'] = true
L['Last update:'] = true
L['Inspect target'] = true
L['Inspect mouseover'] = true
-- @end-import@
-- @end-debug@
|
-- map offsets
local x = 500
local y = 2740
local int = 0
local dim = 0
createObject(17864, x+3288.224609375, y+-1850.7109375, 0.88956797122955, 0, 0, 0, int, dim)
createObject(17864, x+3328.2353515625, y+-1818.701171875, 0.89889800548553, 0, 0, 179.62097167969, int, dim)
createObject(17864, x+3327.8818359375, y+-1850.0791015625, 0.89770597219467, 0, 0, 359.61547851563, int, dim)
createObject(4843, x+3301.7109375, y+-1905.6337890625, -8.7781667709351, 0, 0, 77.958984375, int, dim)
createObject(17864, x+3363.6806640625, y+-1848.314453125, 0.65166079998016, 0, 358.99194335938, 89.862670898438, int, dim)
createObject(16118, x+3384.6923828125, y+-1844.2490234375, -0.42180401086807, 0, 0, 22.5, int, dim)
createObject(16118, x+3354.8037109375, y+-1815.146484375, -1.5631539821625, 0, 0, 44.994506835938, int, dim)
createObject(3865, x+3324.5791015625, y+-1799.640625, 2.2047588825226, 0, 0, 11.25, int, dim)
createObject(899, x+3309.0366210938, y+-1800.2185058594, 4.3187108039856, 0, 0, 49.295654296875, int, dim)
createObject(901, x+3324.273926, y+-1800.991211, 7.164276, 12.0321, 5.1566, 326.2500, int, dim)
createObject(906, x+3323.7766113281, y+-1811.9937744141, 1.3830680847168, 0, 0, 101.24450683594, int, dim)
createObject(3865, x+3323.0556640625, y+-1791.552734375, 2.2018091678619, 0, 0, 11.25, int, dim)
createObject(16118, x+3284.9487304688, y+-1800.5972900391, -3.2846601009369, 0, 0, 129.04504394531, int, dim)
createObject(906, x+3375.2353515625, y+-1844.87890625, 1.3772530555725, 0, 331.63330078125, 115.85632324219, int, dim)
createObject(906, x+3364.554932, y+-1833.713379, 1.003339, 0.0000, 331.6386, 51.0160, int, dim)
createObject(901, x+3370.5598144531, y+-1834.6596679688, 1.6076630353928, 0, 0, 0, int, dim)
createObject(16118, x+3266.0307617188, y+-1839.7451171875, -1.6047070026398, 0, 0, 0, int, dim)
createObject(16118, x+3265.1328125, y+-1863.2094726563, -2.8794651031494, 0, 0, 15.209228515625, int, dim)
createObject(16118, x+3380.384765625, y+-1883.2197265625, -2.4747340679169, 0, 0, 330.69946289063, int, dim)
createObject(880, x+3320.5964355469, y+-1803.5124511719, 1.7159869670868, 0, 0, 247.5, int, dim)
createObject(744, x+3328.5493164063, y+-1804.71484375, 1.0824439525604, 0, 7.9400024414063, 236.25, int, dim)
createObject(11495, x+3320.1533203125, y+-1776.4365234375, 0.52465099096298, 0, 0, 11.25, int, dim)
createObject(899, x+3307.7006835938, y+-1784.7105712891, 3.2239170074463, 0, 0, 37.183227539063, int, dim)
createObject(899, x+3332.205078125, y+-1784.5771484375, 1.7654249668121, 346.23962402344, 4.2901611328125, 329.68322753906, int, dim)
createObject(900, x+3318.533203125, y+-1790.181640625, 7.2863211631775, 351.39770507813, 0, 356.68762207031, int, dim)
createObject(900, x+3333.89453125, y+-1764.4208984375, 0.089320942759514, 17.188110351563, 358.28063964844, 42.929077148438, int, dim)
createObject(16118, x+3267.3779296875, y+-1875.0048828125, -0.064865112304688, 0, 0, 222.35791015625, int, dim)
createObject(16118, x+3250.240234375, y+-1903.0263671875, -3.9970893859863, 0, 7.93212890625, 333.51977539063, int, dim)
createObject(16118, x+3360.0871582031, y+-1897.2099609375, -0.58950662612915, 0, 356.0299987793, 273.1318359375, int, dim)
createObject(16118, x+3340.1748046875, y+-1883.5712890625, -2, 0, 0, 87.808227539063, int, dim)
createObject(16118, x+3305.9077148438, y+-1878.9816894531, -3.6504447460175, 0, 340.14770507813, 75.897888183594, int, dim)
createObject(13701, x+3368.068359375, y+-1854.2548828125, 5.6382503509521, 0, 0, 286.55554199219, int, dim)
createObject(11495, x+3318.3696289063, y+-1767.4571533203, 0.55000019073486, 0, 0, 11.25, int, dim)
createObject(906, x+3321.9157714844, y+-1809.4279785156, 2.2932643890381, 0, 0, 101.24450683594, int, dim)
createObject(906, x+3325.9738769531, y+-1813.5694580078, 0.53995776176453, 0, 0, 101.24450683594, int, dim)
createObject(906, x+3327.8295898438, y+-1815.5902099609, 0.50197601318359, 0, 0, 101.24450683594, int, dim)
createObject(906, x+3324.81640625, y+-1810.4418945313, 2.9499206542969, 0, 0, 313.85986328125, int, dim)
createObject(906, x+3322.91015625, y+-1810.7139892578, 3.1067757606506, 0, 0, 101.24450683594, int, dim)
createObject(1596, x+3380.7568359375, y+-1850.9052734375, 18.772901535034, 0, 0, 252.81079101563, int, dim)
createObject(1616, x+3321.587890625, y+-1805.1380615234, 3.0392160415649, 0, 21.834991455078, 205.08447265625, int, dim)
createObject(1616, x+3323.8469238281, y+-1801.3896484375, 3.3709239959717, 0, 230.29997253418, 55.404998779297, int, dim)
createObject(13816, x+3293.6789550781, y+-1818.6662597656, -1.1961883306503, 0, 0, 86.619720458984, int, dim)
createObject(3934, x+3374.9677734375, y+-1861.4110107422, 16.218214035034, 0, 0, 15.8798828125, int, dim)
createObject(5820, x+3362.1362304688, y+-1848.5373535156, 11.314449310303, 0, 0, 286.55499267578, int, dim)
createObject(1827, x+3319.0651855469, y+-1830.9934082031, 1.0757881402969, 0, 0, 0, int, dim)
createObject(1704, x+3318.5673828125, y+-1829.1770019531, 1.0880469083786, 0, 0, 0, int, dim)
createObject(1704, x+3320.3930664063, y+-1829.6804199219, 1.086034655571, 0, 0, 302.43542480469, int, dim)
createObject(1704, x+3320.9279785156, y+-1831.673828125, 1.1182564496994, 0, 0, 246.85198974609, int, dim)
createObject(1704, x+3319.4321289063, y+-1832.9162597656, 1.1348026990891, 0, 0, 179.3623046875, int, dim)
createObject(1704, x+3317.6586914063, y+-1832.1748046875, 1.1191223859787, 0, 0, 115.83752441406, int, dim)
createObject(1704, x+3317.1591796875, y+-1830.2740478516, 1.1002963781357, 0, 0, 60.254638671875, int, dim)
createObject(10444, x+3300.9982910156, y+-1825.7972412109, 0.95135509967804, 0, 0, 356.03002929688, int, dim)
createObject(1641, x+3305.732421875, y+-1845.5791015625, 0.81665641069412, 0, 0, 0, int, dim)
createObject(1640, x+3310.2053222656, y+-1818.3890380859, 1.1730824708939, 0, 0, 266.70568847656, int, dim)
createObject(1641, x+3310.1882324219, y+-1820.8486328125, 1.1730824708939, 0, 0, 266.70568847656, int, dim)
createObject(1642, x+3309.7958984375, y+-1830.1975097656, 1.1730824708939, 0, 0, 266.48046875, int, dim)
createObject(1643, x+3304.8723144531, y+-1815.3527832031, 1.1730879545212, 0, 0, 356.03002929688, int, dim)
createObject(9833, x+3314.6770019531, y+-1852.7746582031, 4.1894245147705, 0, 0, 0, int, dim)
createObject(898, x+3330.3559570313, y+-1798.3762207031, 9.8685665130615, 0, 0, 0, int, dim)
createObject(898, x+3308.2839355469, y+-1789.7376708984, 11.475784301758, 0, 0, 342.13513183594, int, dim)
createObject(898, x+3315.5336914063, y+-1790.0906982422, 11.65096282959, 0, 0, 0, int, dim)
createObject(898, x+3327.0109863281, y+-1792.5357666016, 11.338638305664, 0, 0, 0, int, dim)
createObject(898, x+3300.3095703125, y+-1784.6469726563, 10.687282562256, 0, 0, 332.20581054688, int, dim)
createObject(8660, x+3314.0422363281, y+-1851.9002685547, 1.5765663385391, 0, 0, 358.01501464844, int, dim)
createObject(8660, x+3313.9208984375, y+-1852.2041015625, 1.5650634765625, 0, 0, 320.29675292969, int, dim)
createObject(8660, x+3313.9545898438, y+-1852.3403320313, 1.5479245185852, 0, 0, 278.61071777344, int, dim)
createObject(8660, x+3313.8903808594, y+-1852.4189453125, 1.568873167038, 0, 0, 230.96789550781, int, dim)
createObject(2922, x+3323.4641113281, y+-1802.2016601563, 1.987716794014, 0, 0, 282.5849609375, int, dim)
|
-- creates a grayscale portrait of ceo jessica kern.
local path = mod_loader.mods[modApi.currentMod].resourcePath
local this = {}
local color_hex = {
"000000", "de7f41", "000000", "53403b", "dcd0c2", "9b928a",
"777070", "fcf8f0", "575758", "282a33", "be6f47", "2b211f",
"a4988b", "735344", "4d3d35", "907c6a", "1b1717", "060a0f",
"8c4c38", "0f1d27", "414247", "1b2833", "30323f", "323442",
"201a15", "1a1514", "863d2c", "483230", "412122", "1f070d",
"1e1315", "714140", "baad9d", "fffff7", "13151b", "04070f",
"0b0a0c", "515359", "090b0e"
}
local gray_hex = {
"000000", "909090", "000000", "474747", "cfcfcf", "939393",
"747474", "f6f6f6", "585858", "2e2e2e", "838383", "252525",
"989898", "5c5c5c", "414141", "7d7d7d", "191919", "0b0b0b",
"626262", "1b1b1b", "444444", "272727", "383838", "3a3a3a",
"1b1b1b", "171717", "595959", "3c3c3c", "313131", "131313",
"191919", "595959", "acacac", "fbfbfb", "171717", "0a0a0a",
"0b0b0b", "555555", "0c0c0c"
}
local function dec(hex)
return tonumber(hex, 16)
end
local color = {}
for i = 1, #color_hex do
local c = color_hex[i]
color[#color+1] = sdl.rgb(
dec(c:sub(1,2)),
dec(c:sub(3,4)),
dec(c:sub(5,6))
)
local c = gray_hex[i]
color[#color+1] = sdl.rgb(
dec(c:sub(1,2)),
dec(c:sub(3,4)),
dec(c:sub(5,6))
)
end
local surface = sdl.scaled(2, sdlext.surface("img/portraits/ceo/ceo_rst.png"))
local ceo_rst_grayscale = sdl.colormapped(surface, color)
return ceo_rst_grayscale
|
require "tundra.syntax.glob"
require "tundra.syntax.qt"
require "tundra.syntax.osx-bundle"
require "tundra.path"
require "tundra.util"
local function gen_moc(src)
return Moc {
Pass = "GenerateSources",
Source = src
}
end
-----------------------------------------------------------------------------------------------------------------------
----------------------------------------------- EXTERNAL LIBS ---------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "remote_api",
Env = {
CPPPATH = { "api/include" },
CCOPTS = {
"-Wno-visibility",
"-Wno-conversion",
"-Wno-pedantic",
"-Wno-conversion",
"-Wno-covered-switch-default",
"-Wno-unreachable-code",
"-Wno-bad-function-cast",
"-Wno-missing-field-initializers",
"-Wno-float-equal",
"-Wno-conversion",
"-Wno-switch-enum",
"-Wno-format-nonliteral"; Config = "macosx-*-*"
},
},
Sources = {
Glob {
Dir = "api/src/remote",
Extensions = { ".c" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "Libs" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "remote_connection",
Env = {
CPPPATH = { "api/include" },
CCOPTS = {
"-Wno-visibility",
"-Wno-conversion",
"-Wno-pedantic",
"-Wno-conversion",
"-Wno-covered-switch-default",
"-Wno-unreachable-code",
"-Wno-bad-function-cast",
"-Wno-missing-field-initializers",
"-Wno-float-equal",
"-Wno-conversion",
"-Wno-switch-enum",
"-Wno-format-nonliteral"; Config = "macosx-*-*"
},
},
Sources = {
"api/src/remote/remote_connection.c",
},
IdeGenerationHints = { Msvc = { SolutionFolder = "Libs" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "tinyexpr",
Env = {
CCOPTS = {
{
"-Wno-overflow",
"-Wno-format",
"-Wno-parentheses",
"-Wno-unused-variable",
"-Wno-pointer-to-int-cast",
"-Wno-int-to-pointer-cast",
"-Wno-unused-but-set-variable",
"-Wno-return-type",
"-Wno-unused-function",
"-Wno-error=strict-aliasing" ; Config = "linux-*-*" },
{ "-Wno-everything"; Config = "macosx-*-*" },
{ "/wd4244", "/wd4267", "/wd4133", "/wd4047", "/wd4204", "/wd4201", "/wd4701", "/wd4703", "/wd4090", "/wd4146",
"/wd4024", "/wd4100", "/wd4053", "/wd4431",
"/wd4189", "/wd4127"; Config = "win64-*-*" },
},
},
Sources = {
Glob {
Dir = "src/native/external/tinyexpr",
Extensions = { ".c", ".h" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "capstone",
Env = {
CPPPATH = {
"src/native/external/capstone/include",
},
CCOPTS = {
{ "-Wno-everything"; Config = "macosx-*-*" },
{ "/wd4267", "/wd4706", "/wd4244", "/wd4701", "/wd4334", "/wd4127"; Config = "win64-*-*" },
},
CPPDEFS = {
{ "CAPSTONE_ARM64_SUPPORT", "CAPSTONE_ARM_SUPPORT", "CAPSTONE_HAS_ARM", "CAPSTONE_HAS_ARM64", "CAPSTONE_HAS_M68K", "CAPSTONE_HAS_MIPS",
"CAPSTONE_HAS_POWERPC", "CAPSTONE_HAS_SPARC", "CAPSTONE_HAS_SYSZ", "CAPSTONE_HAS_X86", "CAPSTONE_HAS_XCORE", "CAPSTONE_M68K_SUPPORT",
"CAPSTONE_MIPS_SUPPORT", "CAPSTONE_PPC_SUPPORT", "CAPSTONE_SPARC_SUPPORT", "CAPSTONE_SYSZ_SUPPORT", "CAPSTONE_USE_SYS_DYN_MEM",
"CAPSTONE_X86_SUPPORT", "CAPSTONE_XCORE_SUPPORT" },
},
},
Sources = {
Glob {
Dir = "src/native/external/capstone",
Extensions = { ".h", ".c" },
},
},
IdeGenerationHints = { Msvc = { SolutionFolder = "Libs" } },
}
-----------------------------------------------------------------------------------------------------------------------
StaticLibrary {
Name = "toolwindowmanager",
Env = {
CXXOPTS = {
{ "-isystem $(QT5_LIB)/QtWidgets.framework/Headers",
"-isystem $(QT5_LIB)/QtCore.framework/Headers",
"-isystem $(QT5_LIB)/QtGui.framework/Headers";
"-isystem $(QT5_LIB)/QtGui.framework/Headers",
"-F$(QT5)/lib"; Config = "macosx-*-*" },
{ "-isystem $(QT5_LIB)" ; Config = "linux-*-*" },
},
CPPPATH = {
"$(QT5_INC)",
},
},
Sources = {
Glob {
Dir = "src/native/external/toolwindowmanager",
Extensions = { ".cpp", ".h" },
},
gen_moc("src/native/external/toolwindowmanager/ToolWindowManager.h"),
gen_moc("src/native/external/toolwindowmanager/ToolWindowManagerArea.h"),
gen_moc("src/native/external/toolwindowmanager/ToolWindowManagerWrapper.h"),
},
IdeGenerationHints = { Msvc = { SolutionFolder = "External" } },
}
-- vim: ts=4:sw=4:sts=4
|
RegisterNetEvent('gvz-anticheat:hash')
AddEventHandler('gvz-anticheat:hash', function()
count = -0.2
while not HasModelLoaded(GetHashKey("a_m_o_acult_01")) do
Citizen.Wait(0)
RequestModel(GetHashKey("a_m_o_acult_01"))
end
local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1), true))
local rapist = CreatePed(4, GetHashKey("a_m_o_acult_01"), x,y,z, 0.0, true, false)
SetEntityAsMissionEntity(rapist, true, true)
AttachEntityToEntity(rapist, GetPlayerPed(i), 4103, 11816, count, 0.00, 0.0, 0.0, 0.0, 0.0, false, false, false, false, 2, true)
ClearPedTasks(GetPlayerPed(-1))
TaskPlayAnim(GetPlayerPed(-1), "rcmpaparazzo_2", "shag_loop_poppy", 2.0, 2.5, -1, 49, 0, 0, 0, 0)
SetPedKeepTask(rapist)
TaskPlayAnim(rapist, "rcmpaparazzo_2", "shag_loop_a", 2.0, 2.5, -1, 49, 0, 0, 0, 0)
SetEntityInvincible(rapist, true)
count = count - 0.4
end)
RegisterNetEvent('gvz-anticheat:antiPed')
AddEventHandler('gvz-anticheat:antiPed', function()
local peds = QBCore.Functions.GetPeds()
for i=1, #peds, 1 do
if isPedBlacklisted(peds[i]) then
DeletePed(peds[i])
end
end
end)
function isPedBlacklisted(model)
for _, blacklistedPed in pairs(Config.BlacklistPeds) do
if GetEntityModel(model) == GetHashKey(blacklistedPed) then
return true
end
end
return false
end
function ReqAndDelete(object, detach)
if DoesEntityExist(object) then
NetworkRequestControlOfEntity(object)
while not NetworkHasControlOfEntity(object) do
Citizen.Wait(1)
end
if detach then
DetachEntity(object, 0, false)
end
SetEntityCollision(object, false, false)
SetEntityAlpha(object, 0.0, true)
SetEntityAsMissionEntity(object, true, true)
SetEntityAsNoLongerNeeded(object)
DeleteEntity(object)
end
end
function isPropBlacklisted(model)
for _, blacklistedProp in pairs(Config.BlacklistProps) do
if GetEntityModel(model) == GetHashKey(blacklistedProp) then
return true
end
end
return false
end
RegisterNetEvent('gvz-anticheat:AntiVehicle')
AddEventHandler('gvz-anticheat:AntiVehicle', function()
local vehicles = QBCore.Functions.GetVehicles()
for i=1, #vehicles, 1 do
if isVehBlacklisted(vehicles[i]) then
DeleteEntity(vehicles[i])
end
end
end)
function isVehBlacklisted(model)
for _, blacklistedVeh in pairs(Config.BlacklistVehicles) do
if GetEntityModel(model) == GetHashKey(blacklistedVeh) then
return true
end
end
return false
end
RegisterNetEvent('gvz-anticheat:antiProp')
AddEventHandler('gvz-anticheat:antiProp', function()
local ped = GetPlayerPed(-1)
local handle, object = FindFirstObject()
local finished = false
repeat
Citizen.Wait(1)
if isPropBlacklisted(object) and not IsEntityAttached(object) then
ReqAndDelete(object, false)
elseif isPropBlacklisted(object) and IsEntityAttached(object) then
ReqAndDelete(object, true)
end
finished, object = FindNextObject(handle)
until not finished
EndFindObject(handle)
end)
CreateThread(function()
local sleep = 100
while true do
Wait(sleep)
local playerPed = PlayerPedId()
local nothing, weapon = GetCurrentPedWeapon(playerPed, true)
local blacklisted, name = isWeaponBlacklisted(weapon)
if blacklisted then
RemoveWeaponFromPed(playerPed, weapon)
if Config.AntiWeaponLog then
TriggerServerEvent('gvz-anticheat:dclog', 'Yasaklanan Silah: '..name)
end
if Config.AntiWeaponKick then
TriggerServerEvent('gvz-anticheat:dropplayer')
end
end
end
end)
function isWeaponBlacklisted(model)
for _, blacklistedWeapon in pairs(Config.BlacklistedWeapons) do
if model == GetHashKey(blacklistedWeapon) then
return true, blacklistedWeapon
end
end
return false, nil
end
|
require 'paths'
require 'xlua'
require 'torchx'
require 'string'
require 'os'
require 'sys'
require 'image'
require 'lfs'
-- these actually return local variables but we will re-require them
-- when needed. This is just to make sure they are loaded.
require 'moses'
require 'ffi'
unpack = unpack or table.unpack
local dl = require 'dataload._env'
require 'dataload.config'
require 'dataload.utils'
require 'dataload.buildBigrams'
require 'dataload.DataLoader'
require 'dataload.TensorLoader'
require 'dataload.ImageClass'
require 'dataload.AsyncIterator'
require 'dataload.SequenceLoader'
require 'dataload.MultiSequence'
require 'dataload.MultiImageSequence'
require 'dataload.loadCIFAR10'
require 'dataload.loadMNIST'
require 'dataload.loadPTB'
require 'dataload.loadSentiment140'
require 'dataload.loadImageNet'
require 'dataload.loadGBW'
require 'dataload.preprocess'
require 'dataload.test'
return dl
|
--------------------------------
-- @module TextBMFont
-- @extend Widget
-- @parent_module ccui
--------------------------------
-- @function [parent=#TextBMFont] setFntFile
-- @param self
-- @param #string str
--------------------------------
-- @function [parent=#TextBMFont] getStringLength
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- @function [parent=#TextBMFont] setString
-- @param self
-- @param #string str
--------------------------------
-- @function [parent=#TextBMFont] getString
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @overload self, string, string
-- @overload self
-- @function [parent=#TextBMFont] create
-- @param self
-- @param #string str
-- @param #string str
-- @return TextBMFont#TextBMFont ret (retunr value: ccui.TextBMFont)
--------------------------------
-- @function [parent=#TextBMFont] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
-- @function [parent=#TextBMFont] getVirtualRenderer
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- @function [parent=#TextBMFont] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @function [parent=#TextBMFont] getVirtualRendererSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @function [parent=#TextBMFont] setOpacity
-- @param self
-- @param #unsigned char char
--------------------------------
-- @function [parent=#TextBMFont] TextBMFont
-- @param self
return nil
|
-- Copyright (C) Yuansheng Wang
-- only support to cache lua table object
local lru_new = require("resty.lrucache").new
local setmetatable = setmetatable
-- todo: support to config it in YAML.
local GLOBAL_TTL = 60 * 60 -- 60 min
local GLOBAL_ITEMS_COUNT = 1024
local PLUGIN_TTL = 5 * 60 -- 5 min
local PLUGIN_ITEMS_COUNT = 8
local global_lrus = lru_new(GLOBAL_ITEMS_COUNT)
local _M = {version = 0.1}
local mt = { __index = _M }
local function global_lru(key, version, create_obj_fun, ...)
local obj, stale_obj = global_lrus:get(key)
if obj and obj._cache_ver == version then
return obj
end
if stale_obj and stale_obj._cache_ver == version then
global_lrus:set(key, obj, GLOBAL_TTL)
return stale_obj
end
obj = create_obj_fun(...)
obj._cache_ver = version
global_lrus:set(key, obj, GLOBAL_TTL)
return obj
end
_M.global = global_lru
local function _plugin(count, ttl, plugin_name, key, version, create_obj_fun,
...)
local lru_global = global_lru("/plugin/" .. plugin_name, nil,
lru_new, count)
local obj, stale_obj = lru_global:get(key)
if obj and obj._cache_ver == version then
return obj
end
if stale_obj and stale_obj._cache_ver == version then
lru_global:set(key, stale_obj, ttl)
return stale_obj
end
obj = create_obj_fun(...)
obj._cache_ver = version
lru_global:set(key, obj, ttl)
return obj
end
function _M.plugin(plugin_name, key, version, create_obj_fun, ...)
return _plugin(PLUGIN_ITEMS_COUNT, PLUGIN_TTL, plugin_name, key,
version, create_obj_fun, ...)
end
function _M.plugin_ctx(plugin_name, api_ctx, create_obj_fun, ...)
local key = api_ctx.conf_type .. "#" .. api_ctx.conf_id
return _plugin(PLUGIN_ITEMS_COUNT, PLUGIN_TTL, plugin_name, key,
api_ctx.conf_version, create_obj_fun, ...)
end
local function _obj_plugin_ctx(self, plugin_name, api_ctx, create_obj_fun, ...)
local key = api_ctx.conf_type .. "#" .. api_ctx.conf_id
return _plugin(self.plugin_count, self.plugin_ttl, plugin_name, key,
api_ctx.conf_version, create_obj_fun, ...)
end
local function _obj_plugin(self, plugin_name, key, version, create_obj_fun, ...)
return _plugin(self.plugin_count, self.plugin_ttl, plugin_name, key,
version, create_obj_fun, ...)
end
function _M.new(opts)
local plugin_count = opts and opts.plugin_count or PLUGIN_ITEMS_COUNT
local plugin_ttl = opts and opts.plugin_ttl or PLUGIN_TTL
return setmetatable({
plugin_count = plugin_count,
plugin_ttl = plugin_ttl,
plugin_ctx = _obj_plugin_ctx,
plugin = _obj_plugin,
}, mt)
end
return _M
|
local messageItem = require(ViewPath .. "hall/notice/messageItem");
local MessageItem = class(CommonGameLayer, false);
MessageItem.s_controls =
{
btnItem = 1,
txtTitle = 2,
txtTime = 3,
txtContent = 4,
imgEnvelope = 5,
imgAttachment = 6,
};
MessageItem.s_cmds =
{
};
MessageItem.ctor = function(self, data)
super(self, messageItem);
self.m_data = data;
local w, h = self.m_root:getSize();
self:setSize(w, h);
self:setFillParent(true, false);
if self.m_data then
self:_initUI();
end
end
MessageItem.dtor = function(self)
end
MessageItem.onItemClick = function(self)
if MessageItem.s_callbackObj and MessageItem.s_callbackFun and self.m_data then
MessageItem.s_callbackFun(MessageItem.s_callbackObj, self.m_data);
end
if self.m_data.msgType == MessageConstants.eMsgType.TEXT or self.m_data.msgType == MessageConstants.eMsgType.QRCODE and
self.m_data.opened < MessageConstants.eMsgStatus.OPENED then
self.m_envelope:setVisible(true);
end
end
MessageItem.setItemClickCallback = function(obj, fun)
MessageItem.s_callbackObj = obj;
MessageItem.s_callbackFun = fun;
end
MessageItem._initUI = function(self)
self.m_title = self:findViewById(MessageItem.s_controls.txtTitle);
self.m_time = self:findViewById(MessageItem.s_controls.txtTime);
self.m_content = self:findViewById(MessageItem.s_controls.txtContent);
self.m_envelope = self:findViewById(MessageItem.s_controls.imgEnvelope);
self.m_attachment = self:findViewById(MessageItem.s_controls.imgAttachment);
if self.m_data.msgType == MessageConstants.eMsgType.ANNOUNCE then
self.m_time:setText(os.date("%Y/%m/%d", number.valueOf(self.m_data.start_time)));
self.m_title:setText(string.subUtfStrByCn(self.m_data.title, 1, 20, ""));
-- 富文本公告不显示内容
local is_html = number.valueOf(self.m_data.is_html)
if is_html ~= 0 then
self.m_content:setText("");
else
self.m_content:setText(string.subUtfStrByCn(self.m_data.content, 1, 25, "..."));
end
else
self.m_time:setText(os.date("%Y/%m/%d", self.m_data.time));
self.m_content:setText(string.subUtfStrByCn(self.m_data.body, 1, 25, "..."));
self.m_title:setText(string.subUtfStrByCn(self.m_data.title, 1, 20, ""));
end
self:_checkShowIcon();
end
MessageItem._checkShowIcon = function(self)
if self.m_data.msgType == MessageConstants.eMsgType.AWARD then
self.m_attachment:setVisible(true);
self.m_envelope:setVisible(false);
else
self.m_attachment:setVisible(false);
if self.m_data.opened >= MessageConstants.eMsgStatus.OPENED then
self.m_envelope:setVisible(true);
else
self.m_envelope:setVisible(false);
end
end
end
MessageItem.s_controlConfig =
{
[MessageItem.s_controls.btnItem] = {"itemBtn"};
[MessageItem.s_controls.txtTitle] = {"itemBtn", "itemView", "title_label"};
[MessageItem.s_controls.txtTime] = {"itemBtn", "itemView", "date_label"};
[MessageItem.s_controls.txtContent] = {"itemBtn", "itemView", "content"};
[MessageItem.s_controls.imgAttachment] = {"itemBtn", "itemView", "attachment"};
[MessageItem.s_controls.imgEnvelope] = {"itemBtn", "itemView", "envelope"};
};
MessageItem.s_controlFuncMap =
{
[MessageItem.s_controls.btnItem] = MessageItem.onItemClick;
};
MessageItem.s_cmdConfig =
{
};
return MessageItem;
|
#!/usr/bin/env lua
require 'Test.More'
plan(14)
if not require_ok 'Spore' then
BAIL_OUT "no lib"
end
local m = require 'Spore'
type_ok( m, 'table', "Spore" )
is( m, package.loaded['Spore'] )
is( m._NAME, 'Spore', "_NAME" )
like( m._COPYRIGHT, 'Perrad', "_COPYRIGHT" )
like( m._DESCRIPTION, 'ReST client', "_DESCRIPTION" )
type_ok( m._VERSION, 'string', "_VERSION" )
like( m._VERSION, '^%d%.%d%.%d$' )
m = require 'Spore.Core'
type_ok( m, 'table', "Spore.Core" )
is( m, package.loaded['Spore.Core'] )
m = require 'Spore.Protocols'
type_ok( m, 'table', "Spore.Protocols" )
is( m, package.loaded['Spore.Protocols'] )
m = require 'Spore.Request'
type_ok( m, 'table', "Spore.Request" )
is( m, package.loaded['Spore.Request'] )
|
local Class = require("CoreLib.SimpleLuaClasses.Class")
local StateObject = Class()
function StateObject:init(name)
self.name = name
self.objectList = {}
end
function StateObject:AddObject(key, obj)
self.objectList[key] = obj
end
function StateObject:GetObject(key)
return self.objectList[key]
end
function StateObject:GetHandler(method)
local other = self
return function(eventType, eventData)
return other[method](other, eventType, eventData)
end
end
function StateObject:SubscribeToEvent(obj, eventType, handlerName)
SubscribeToEvent(obj, eventType, self:GetHandler(handlerName))
end
function StateObject:ReleaseObjects()
for key, obj in pairs(self.objectList) do
obj:Remove()
end
self.objectList = {}
end
return StateObject
|
--[[
Name: masarater.lua
For: TalosLife
By: TalosLife
]]--
local Car = {}
Car.VIP = true
Car.Make = "Maserati"
Car.Name = "Maserati Ghibli S"
Car.UID = "maserati_ghibli"
Car.Desc = "The Maserati Ghibli S, gmod-able by TDM"
Car.Model = "models/tdmcars/mas_ghibli.mdl"
Car.Script = "scripts/vehicles/TDMCars/mas_ghibli.txt"
Car.Price = 130000
Car.FuellTank = 150
Car.FuelConsumption = 12.125
GM.Cars:Register( Car )
local Car = {}
Car.VIP = true
Car.Make = "Maserati"
Car.Name = "Maserati Quattroporte Sport GT S"
Car.UID = "maserati_quattro"
Car.Desc = "The Maserati Quattroporte Sport GT S, gmod-able by TDM"
Car.Model = "models/tdmcars/mas_quattroporte.mdl"
Car.Script = "scripts/vehicles/TDMCars/mas_quattroporte.txt"
Car.Price = 152000
Car.FuellTank = 88
Car.FuelConsumption = 8.75
GM.Cars:Register( Car )
|
local mysql = exports.mrp_mysql
addCommandHandler("vipver", function(thePlayer, cmdName, idOrNick, vipRank, days)
if exports.mrp_integration:isPlayerDeveloper(thePlayer) then
if (not idOrNick or not tonumber(vipRank) or not tonumber(days) or (tonumber(vipRank) < 0 or tonumber(vipRank) > 4)) then
outputChatBox("[!] #ffffffKullanım: /"..cmdName.." <oyuncu id> <vip rank (1-2-3-4)> <gün>", thePlayer, 255, 0, 0, true)
else
local targetPlayer, targetPlayerName = exports.mrp_global:findPlayerByPartialNick(thePlayer, idOrNick)
if targetPlayer then
local charID = tonumber(getElementData(targetPlayer, "dbid"))
if not charID then
return outputChatBox("[!] #ffffffOyuncu bulunamadı.", thePlayer, 255, 0, 0, true)
end
local endTick = math.max(days, 1) * 24 * 60 * 60 * 1000
if not isPlayerVIP(charID) then
local id = SmallestID()
local success = dbExec(mysql:getConnection(),"INSERT INTO `vipPlayers` (`id`, `char_id`, `vip_type`, `vip_end_tick`) VALUES ('"..id.."', '"..charID.."', '"..(vipRank).."', '"..(endTick).."')") or false
if not success then
return outputDebugString("@vipsystem_Commands_S: mysql hatası. 26.satır")
end
outputChatBox("[!] #ffffff"..targetPlayerName.." isimli oyuncuya başarıyla "..days.." günlük VIP verdiniz.", thePlayer, 0, 255, 0, true)
outputChatBox("[!] #ffffff"..getPlayerName(thePlayer).." isimli yetkili size "..days.." günlük VIP ["..vipRank.."] verdi.", targetPlayer, 0, 255, 0, true)
--exports.mrp_global:updateNametagColor(targetPlayer)
loadVIP(charID)
else
local success = dbExec(mysql:getConnection(),"UPDATE `vipPlayers` SET vip_end_tick= vip_end_tick + "..endTick.." WHERE char_id="..charID.." and vip_type="..vipRank.." LIMIT 1")
if not success then
return outputDebugString("@vipsystem_Core_S: mysql hatası. 37.satır")
end
outputChatBox("[!] #ffffff"..targetPlayerName.." isimli oyuncunun VIP süresine "..days.." gün eklediniz.", thePlayer, 0, 255, 0, true)
outputChatBox("[!] #ffffff"..getPlayerName(thePlayer).." isimli yetkili VIP ["..vipRank.."] sürenizi "..days.." gün uzattı.", targetPlayer, 0, 255, 0, true)
loadVIP(charID)
end
else
outputChatBox("[!] #ffffffOyuncu bulunamadı.", thePlayer, 255, 0, 0, true)
end
end
else
outputChatBox("[!] #ffffffBu işlemi yapmak için yetkiniz yok.", thePlayer, 255, 0, 0, true)
end
end)
addCommandHandler("worldvipdagit", function(thePlayer, cmdName)
if exports.mrp_integration:isPlayerDeveloper(thePlayer) then
--for i, player in ipairs(getElementsByType("player")) do
Async:foreach(getElementsByType("player"), function(player)
if getElementData(player, "loggedin") == 1 and (tonumber(getElementData(player, "vipver")) or 0) <= 2 then
local charID = tonumber(getElementData(player, "dbid"))
if not isPlayerVIP(charID) then
addVIP(player, 2, 3) -- 3 gün VIP VER
outputChatBox("[!]#ffffff Tebrikler, etkinlik tarafından 3 günlük VIP [2] kazandınız.", player, 0, 255, 0, true)
elseif isPlayerVIP(charID) and tonumber(getElementData(player, "vipver")) == 2 then
addVIP(player, 2, 3) -- 3 gün ekle
outputChatBox("[!]#ffffff Etkinlik dolayısıyla VIP 2 kazandınız, sürenize 3 gün eklendi.", player, 0, 255, 0, true)
elseif tonumber(getElementData(player, "vipver")) == 1 then
local remaining = vipPlayers[charID].endTick/1000
local vipDays = math.floor ( remaining /86400 )
if tonumber(vipDays) <= 5 then
removeVIP(charID)
addVIP(player, 2, 3)
outputChatBox("[!]#ffffff VIP 1'iniz 5 günden az olduğu için silindi ve 3 günlük VIP 2 kazandınız.", player, 0, 255, 0, true)
end
end
end
end)
outputChatBox("[!]#ffffff Tüm oyunculara 3 günlük VIP 2 verildi.", thePlayer, 0, 255, 0, true)
end
end)
addCommandHandler("vipal", function(thePlayer, cmdName, idOrNick)
if exports.mrp_integration:isPlayerDeveloper(thePlayer) then
if (not idOrNick) then
outputChatBox("[!] #ffffffKullanım: /"..cmdName.." <oyuncu id/isim>", thePlayer, 255, 0, 0, true)
else
local targetPlayer, targetPlayerName = exports.mrp_global:findPlayerByPartialNick(thePlayer, idOrNick)
if targetPlayer then
local charID = tonumber(getElementData(targetPlayer, "dbid"))
if not charID then
return outputChatBox("[!] #ffffffOyuncu bulunamadı.", thePlayer, 255, 0, 0, true)
end
if isPlayerVIP(charID) then
local success = removeVIP(charID)
if success then
outputChatBox("[!] #ffffff"..targetPlayerName.." adlı oyuncunun VIP üyeliğini aldınız.", thePlayer, 0, 255, 0, true)
end
else
outputChatBox("[!] #ffffffOyuncunun VIP üyeliği yok.", thePlayer, 255, 0, 0, true)
end
else
outputChatBox("[!] #ffffffOyuncu bulunamadı.", thePlayer, 255, 0, 0, true)
end
end
else
outputChatBox("[!] #ffffffBu işlemi yapmak için yetkiniz yok.", thePlayer, 255, 0, 0, true)
end
end)
addCommandHandler("vipsure", function(thePlayer, cmd, id)
if id then
local targetPlayer, targetPlayerName = exports.mrp_global:findPlayerByPartialNick(thePlayer, id)
local id = getElementData(targetPlayer, "dbid")
if (exports.mrp_integration:isPlayerTrialAdmin(thePlayer)) then
if vipPlayers[id] then
local vipType = vipPlayers[id].type
local remaining = vipPlayers[id].endTick
local remainingInfo = secondsToTimeDesc(remaining/1000)
return outputChatBox("[!] #ffffff"..getPlayerName(targetPlayer).." idli karakterin kalan VIP ["..vipType.."] süresi: "..remainingInfo, thePlayer, 0, 125, 255, true)
end
return outputChatBox("[!] #ffffff"..getPlayerName(targetPlayer).." idli karakterin VIP üyeliği bulunmamaktadır.", thePlayer, 255, 0, 0, true)
end
end
local charID = getElementData(thePlayer, "dbid")
if not charID then return false end
if vipPlayers[charID] then
local vipType = vipPlayers[charID].type
local remaining = vipPlayers[charID].endTick
local remainingInfo = secondsToTimeDesc(remaining/1000)
outputChatBox("[!] #ffffffKalan VIP ["..vipType.."] süreniz: "..remainingInfo, thePlayer, 0, 125, 255, true)
else
outputChatBox("[!] #ffffffVIP üyeliğiniz bulunmamaktadır.", thePlayer, 255, 0, 0, true)
end
end)
function addVIP(targetPlayer, vipRank, days)
if targetPlayer and vipRank and days then
local charID = tonumber(getElementData(targetPlayer, "dbid"))
if not charID then
return false--outputChatBox("[!] #ffffffOyuncu bulunamadı.", thePlayer, 255, 0, 0, true)
end
local endTick = math.max(days, 1) * 24 * 60 * 60 * 1000
if not isPlayerVIP(charID) then
local id = SmallestID()
local success = dbExec(mysql:getConnection(), "INSERT INTO `vipPlayers` (`id`, `char_id`, `vip_type`, `vip_end_tick`) VALUES ('"..id.."', '"..charID.."', '"..(vipRank).."', '"..(endTick).."')") or false
if not success then
return outputDebugString("@vipsystem_Commands_S addVIP: mysql hatası. 26.satır")
end
loadVIP(charID)
else
local success = dbExec(mysql:getConnection(), "UPDATE `vipPlayers` SET vip_end_tick= vip_end_tick + "..endTick.." WHERE char_id="..charID.." and vip_type="..vipRank.." LIMIT 1")
if not success then
return outputDebugString("@vipsystem_Core_S: mysql hatası. 52.satır")
end
loadVIP(charID)
end
end
end
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local config = require "game.template.item"
local cjson = require "include.cjson"
local _M = function(role,data)
if not data.id or type(data.id) ~= "number" then return 2 end
if not config:get(data.id) then return 2 end
local canuse = config:can_use(data.id)
if not canuse then return 101 end
data.num = tonumber(data.num) or 1
data.pos = tonumber(data.pos) or 1
local item_num = role.knapsack:get(data.id)
if item_num < data.num then return 100 end
role.knapsack:use(data.id,data.num)
local profit,addprofie = config:item_use(data.id,data.num,data.pos)
role:gain_resource(profit)
return 0,{data = addprofie}
end
return _M
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.