Receitas
Respostas curtas e completas para tarefas comuns. Cada receita é um main.luau inteiro ou um trecho que você pode colar em um. Os nomes são explicados na referência da API.
Comandos e configurações
Um comando com argumentos e uma configuração
local reward = cs.cvar("bounty_reward", "500", { help = "Money for the bounty", min = 0, max = 16000 })
cs.command("bounty", function(player, args)
local amount = tonumber(args[1]) or reward:int()
cs.reply(player, "The bounty is $" .. amount)
end, { help = "bounty [amount]" })
Um comando de administrador que mira um jogador
-- Finds one connected player whose name holds the text (any case).
local function find(text: string): Player?
local found = nil
for _, p in cs.players() do
if p.name:lower():find(text:lower(), 1, true) then
if found then
return nil -- more than one: be precise
end
found = p
end
end
return found
end
cs.command("freeze", function(admin, args)
local p = args[1] and find(args[1])
if not p then
cs.reply(admin, "freeze <name>: no single player matches")
return
end
if admin and not admin:can_target(p) then
cs.reply(admin, "You cannot target " .. p.name)
return
end
p:freeze(true)
cs.after(5, function()
if p.connected then
p:freeze(false)
end
end)
cs.chat(nil, "{red}" .. p.name .. "{default} is frozen for 5 seconds")
end, { admin = true, help = "freeze <name>" })
admin = true deixa executá-lo só os administradores cuja entrada em admins.toml permite freeze. Player:slay, Player:slap, Player:kick e Player:ban funcionam do mesmo jeito.
Uma tecla atribuída
Comandos que começam com + e - são o pressionar e o soltar de uma tecla: os jogadores os atribuem (bind mouse3 +hook).
cs.command("+hook", function(player) if player then player:data().hooking = true end end)
cs.command("-hook", function(player) if player then player:data().hooking = false end end)
Jogadores
Dar armas quando os jogadores renascem
cs.on("player_equip", function(ev)
ev:block() -- no knife and pistol from the game
end, { before = true })
cs.on("player_spawn", function(ev)
local p = ev.player
p:give("weapon_knife")
p:give("weapon_deagle", { ammo = 35 })
p:give("item_assaultsuit")
end)
Renascer os mortos depois de um momento
cs.on("player_killed", function(ev)
local p = ev.player
cs.after(2, function()
if p.connected and not p.alive and (p.team == "t" or p.team == "ct") then
p:respawn()
end
end, { player = p })
end)
Para um modo inteiro com renascimentos, cs.register_mode com respawn = 2 faz isso por você (veja Modos).
Dinheiro por abate
cs.on("player_killed", function(ev)
local killer = ev.attacker and ev.attacker.player
if killer and killer ~= ev.player then
killer.money = math.min(16000, killer.money + 300)
cs.chat(killer, "{green}+$300{default} for killing " .. ev.player.name)
end
end)
Gravidade baixa, velocidade e bunny hop automático
cs.command("moon", function(player)
if not player then return end
player.gravity = 0.4
player:set_movement({ auto_bhop = true, bhop_cap = 0 })
end)
As configurações de movimento viajam para o jogo do jogador, então a previsão dele continua exata. player:reset_movement() devolve as configurações do servidor.
Deslizes que não param nas emendas de uma rampa
cs.on("player_spawn", function(ev)
ev.player:set_movement({ ramp_fix = true })
end)
Em mapas cujas rampas de deslize são feitas de vários brushes, um deslize rápido pode parar de repente em uma emenda. ramp_fix deixa o jogador continuar deslizando; paredes, pisos e pixel surf não mudam.
Lembrar algo sobre um jogador durante a partida
cs.on("player_killed", function(ev)
local killer = ev.attacker and ev.attacker.player
if killer then
local d = killer:data()
d.streak = (d.streak or 0) + 1
if d.streak == 5 then
cs.chat(nil, "{green}" .. killer.name .. "{default} is on a rampage!")
end
end
ev.player:data().streak = 0
end)
player:data() some quando o jogador sai ou o mapa muda.
Guardar para sempre uma preferência do jogador
local prefs = cs.store("prefs") -- plugin_data/<plugin>/prefs.store
cs.command("sounds", function(player, args)
if not player then return end
local on = args[1] ~= "off"
prefs:set(player.id .. ":sounds", on)
cs.reply(player, "Sounds " .. (if on then "on" else "off"))
end)
local function wants_sounds(p: Player): boolean
return prefs:get(p.id .. ":sounds") ~= false -- on unless turned off
end
Use como chave player.id, o ID permanente do jogador; um nome pode mudar.
O HUD
Um aviso
cs.notify(nil, "The bomb zone is closed", {
title = "Warning", kind = "warning", position = "top_right", duration = 6,
})
Uma contagem regressiva e uma barra que ficam na tela
cs.hud_widget(nil, "round_clock", { kind = "timer", seconds = 60, label = "Escape", x = 0.5, y = 0.08, align = "center" })
local function show_power(p: Player, power: number)
cs.hud_widget(p, "power", { kind = "bar", x = 0.02, y = 0.9, w = 200, h = 12, value = power, max = 100,
color = "#e8a33a", back = "#00000080", label = "Power" })
end
-- later: cs.hud_remove(nil, "round_clock")
Um widget com o mesmo id muda o existente.
Um menu
cs.command("guns", function(player)
if not player then return end
cs.menu(player, "Choose a weapon", { "AK-47", "M4A1", "AWP" }, function(p, key)
local guns = { "weapon_ak47", "weapon_m4a1", "weapon_awp" }
if guns[key] and p.alive then
p:give(guns[key])
end
end)
end)
Uma janela com botões
cs.command("vote", function(player)
if not player then return end
cs.window(player, "vote", {
title = "Next map?",
size = { 420, 180 },
body = { kind = "row", gap = 12, children = {
{ kind = "button", id = "de_dust2", text = "Dust 2", key = 1, grow = 1 },
{ kind = "button", id = "de_inferno", text = "Inferno", key = 2, grow = 1 },
} },
})
end)
cs.on_window("vote", function(p, ev)
if ev.kind == "click" then
cs.chat(nil, p.name .. " votes for " .. ev.id)
cs.window_close(p, "vote")
end
end)
(docs/plugin_windows.md tem todos os elementos. cs_plugin new shop --template shop cria uma loja completa para começar.)
Imagens na tela de carregamento
As imagens vão na pasta content/ do plugin (PNG ou JPG, de até 1920x1080):
cs.loading_screen({ images = { "myserver/welcome.jpg", "myserver/rules.jpg" }, seconds = 8 })
Textos nos idiomas dos jogadores
lang/en.toml:
welcome = "Welcome, {name}!"
lang/es.toml:
welcome = "¡Bienvenido, {name}!"
cs.on("player_join", function(ev)
cs.chat(ev.player, ev.player:t("welcome", { name = ev.player.name }))
end)
Efeitos e sons
Uma explosão que causa dano
local function blast(at: vector, by: Player?)
cs.explosion(nil, at, { scale = 3 })
cs.decal(nil, at - vector.create(0, 0, 8), "{scorch1")
cs.radius_damage(at, 120, 300, { attacker = by and by.entity })
for _, p in cs.players() do
if p.alive and vector.magnitude(p.origin - at) < 600 then
p:shake({ amplitude = 8, duration = 1 })
end
end
end
Um feixe entre dois jogadores
cs.beam(nil, alice.entity, bob.entity, { color = "#00aaff", width = 20, life = 2 })
Música quando uma rodada começa
cs.on("map_start", function()
cs.precache("media/round.mp3")
end)
cs.on("round_start", function()
for _, p in cs.players() do
p:play_music("media/round.mp3")
end
end)
Coloque media/round.mp3 na pasta content/ do plugin: os jogadores baixam.
Rodadas e regras
Só tiros na cabeça
cs.on("player_trace_attack", function(ev)
if ev.hit_group ~= 1 then
ev:block()
end
end, { before = true })
Dano dobrado com facas
cs.on("player_damage", function(ev)
local attacker = ev.attacker and ev.attacker.player
if attacker and attacker.weapon == "weapon_knife" then
ev.damage *= 2
end
end, { before = true })
Mudar quem vence uma rodada
-- When time runs out on a bomb map, call it a draw instead of a CT win.
cs.on("round_end", function(ev)
if ev.reason == "target_saved" then
ev.reason = "draw"
end
end, { before = true })
Mudar o menu de compra
Os itens vão pelo id que os jogadores digitam para comprar (awp, hegren, vesthelm; cs.buy_items() lista todos).
cs.set_buy_item("awp", { enabled = false })
cs.set_buy_item("hegren", { price = 150 })
cs.register_buy_item("medkit", {
name = "Medkit", price = 800, group = "equipment",
buy = function(p) p.health = math.min(100, p.health + 50) end,
})
Uma janela de loja no lugar do menu de compra
cs.on("buy_menu", function(ev)
if ev.menu ~= "buy" then return end
ev:block()
cs.window(ev.player, "shop", {
title = "Shop",
body = { kind = "grid", columns = 2, children = {
{ kind = "slot", id = "weapon_ak47", name = "AK-47", price = 2700, key = 1 },
{ kind = "slot", id = "weapon_m4a1", name = "M4A1", price = 3100, key = 2 },
} },
})
end, { before = true })
cs.on_window("shop", function(p, ev)
local prices = { weapon_ak47 = 2700, weapon_m4a1 = 3100 }
local price = prices[ev.id]
if ev.kind == "click" and price and p.can_buy and p.money >= price then
p.money -= price
p:give(ev.id)
cs.window_close(p, "shop")
end
end)
Um modo de jogo
cs.register_mode("arena", {
title = "Knife arena",
off = { "buying" },
respawn = 1,
objectives = false,
start = function() cs.chat(nil, "{green}Knife arena!{default} Knives only.") end,
})
cs.on("player_equip", function(ev)
if cs.game.mode == "arena" then
ev:block()
ev.player:give("weapon_knife")
end
end, { before = true })
cs.on("plugin_start", function()
cs.set_mode("arena")
end)
O tutorial constrói um modo completo passo a passo.
Uma votação de mapa
cs.command("rtv", function()
if cs.vote_running() then return end
local maps = { "de_dust2", "de_inferno", "de_nuke" }
cs.vote("Next map", maps, function(results)
if results.option then
cs.chat(nil, "Next map: {green}" .. results.option)
cs.change_map(results.option, 5)
end
end)
end)
Bots
Encher o servidor com os bots do jogo
cs.on("map_start", function()
cs.after(5, function()
for _ = 1, 3 do
cs.add_game_bot({ team = "t", difficulty = "hard" })
cs.add_game_bot({ team = "ct", difficulty = "hard" })
end
end)
end)
cs.add_bot cria outro tipo de bot: um que o seu plugin move (replays, bonecos), sem IA.
O mundo
Um item que cura
cs.register_entity("health_pack", {
model = "models/health_pack.mdl", -- in the plugin's content/ folder
mins = vector.create(-8, -8, 0), maxs = vector.create(8, 8, 16),
solid = "trigger",
touch = function(self: Entity, other: Entity)
local p = other.player
if p and p.alive and p.health < 100 then
p.health = math.min(100, p.health + 25)
self:remove()
end
end,
})
-- Maps may place it (classname "health_pack"); code too:
-- cs.create_entity("health_pack", { origin = somewhere })
Encontrar entidades
cs.command("doors", function(player)
for _, door in cs.find_entities({ class = "func_door" }) do
door:use() -- toggles it
end
if player then
local near = cs.find_entities({ near = player.origin, radius = 200 })
cs.reply(player, #near .. " entities within 200 units of you")
end
end, { admin = true })
Mudar as entidades de um mapa ao carregar
-- No weapons lying on the floor, on every map.
cs.patch_map(function(map: string, entities: { { [string]: string } })
for i = #entities, 2, -1 do -- (the first is the world)
if entities[i].classname == "armoury_entity" then
table.remove(entities, i)
end
end
end)
Dados e serviços
Estatísticas em SQLite
local db = cs.database("kills")
db:query_now("CREATE TABLE IF NOT EXISTS kills (id TEXT PRIMARY KEY, name TEXT, n INTEGER NOT NULL DEFAULT 0)")
cs.on("player_killed", function(ev)
local k = ev.attacker and ev.attacker.player
if k and not k.bot then
db:query("INSERT INTO kills (id, name, n) VALUES (?, ?, 1) ON CONFLICT(id) DO UPDATE SET n = n + 1, name = excluded.name",
{ k.id, k.name })
end
end)
cs.command("top", function(player)
db:query("SELECT name, n FROM kills ORDER BY n DESC LIMIT 5", nil, function(r)
if not r.ok then return end
for i, row in r.rows do
cs.reply(player, i .. ". " .. row.name .. " " .. row.n)
end
end)
end)
As consultas rodam em uma thread de fundo, então um disco lento nunca trava o jogo.
Publicar em um web hook
In plugin.toml: hosts = ["discord.com"].
local url = cs.cvar("report_webhook", "", { help = "The web hook URL for reports" })
cs.command("report", function(player, args)
if not player or url.value == "" then return end
cs.http(url.value, {
method = "POST",
headers = { ["content-type"] = "application/json" },
body = cs.json_encode({ content = player.name .. " reports: " .. args.line }),
}, function(res)
cs.reply(player, if res.ok then "Report sent" else "Could not send the report")
end)
end)
Plugins trabalhando juntos
Oferecer uma função e usá-la em outro lugar
economy/main.luau:
local balance: { [string]: number } = {}
cs.export("add", function(id: string, amount: number): number
balance[id] = (balance[id] or 0) + amount
return balance[id]
end)
shop/plugin.toml: depends = ["economy"]. shop/main.luau:
local add = cs.import("economy", "add")
cs.command("daily", function(player)
if player then
cs.reply(player, "You now have " .. add(player.id, 100) .. " coins")
end
end)
Eventos próprios
-- in "races": tell everyone who listens
cs.emit("finished", player.id, seconds)
-- in any other plugin:
cs.on("races:finished", function(id: string, seconds: number)
cs.log(id .. " finished in " .. seconds)
end)
Testes
Um teste com jogadores e bots
local test = require("test")
test.case("a kill is announced to the killer", function(t)
local alice = t:client("Alice", { team = "t" })
local bot = t:bots(1, "ct")[1]
bot.entity:damage(500, { attacker = alice.player.entity })
alice:expect_text("for killing " .. bot.name)
end)
Execute com cs_plugin test <folder>; Ferramentas lista tudo o que o contexto de testes oferece.