Español
Iniciar sesión

Recetario

Respuestas breves y completas a tareas comunes. Cada receta es un main.luau entero o una parte que puedes pegar en uno. Los nombres se explican en la referencia de la API.

Comandos y ajustes

Un comando con argumentos y un ajuste

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]" })

Un comando de administrador dirigido a un jugador

-- 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 deja ejecutarlo solo a los administradores cuya entrada de admins.toml permite freeze. Player:slay, Player:slap, Player:kick y Player:ban funcionan igual.

Una tecla asignada

Los comandos que empiezan con + y - son la pulsación y la liberación de una tecla: los jugadores los asignan (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)

Jugadores

Dar armas cuando aparecen los jugadores

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)

Hacer reaparecer a los muertos tras un 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 un modo entero con reapariciones, cs.register_mode con respawn = 2 lo hace por ti (mira Modos).

Dinero por cada baja

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)

Gravedad baja, velocidad y 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)

Los ajustes de movimiento viajan al juego del jugador, así que su predicción sigue siendo exacta. player:reset_movement() devuelve los ajustes del servidor.

Deslizamientos que no se detienen en las uniones de una rampa

cs.on("player_spawn", function(ev)
	ev.player:set_movement({ ramp_fix = true })
end)

En mapas cuyas rampas de deslizamiento están hechas de varios brushes, un deslizamiento rápido puede frenar en seco en una unión. ramp_fix deja seguir deslizando al jugador; paredes, suelos y pixel surf no cambian.

Recordar algo de un jugador durante la 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() desaparece cuando el jugador se va o cambia el mapa.

Conservar para siempre una preferencia del jugador

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

Usa como clave player.id, el ID permanente del jugador; un nombre puede cambiar.

El HUD

Un aviso

cs.notify(nil, "The bomb zone is closed", {
	title = "Warning", kind = "warning", position = "top_right", duration = 6,
})

Una cuenta atrás y una barra que siguen en pantalla

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")

Un widget con el mismo id cambia el existente.

Un menú

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)

Una ventana con botones

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 tiene todos los elementos. cs_plugin new shop --template shop arma una tienda completa para empezar.)

Imágenes en la pantalla de carga

Las imágenes van en la carpeta content/ del plugin (PNG o JPG, de hasta 1920x1080):

cs.loading_screen({ images = { "myserver/welcome.jpg", "myserver/rules.jpg" }, seconds = 8 })

Textos en los idiomas de los jugadores

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)

Efectos y sonidos

Una explosión que hace daño

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

Un rayo entre dos jugadores

cs.beam(nil, alice.entity, bob.entity, { color = "#00aaff", width = 20, life = 2 })

Música cuando empieza una ronda

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)

Pon media/round.mp3 en la carpeta content/ del plugin: los jugadores lo descargan.

Rondas y reglas

Solo disparos a la cabeza

cs.on("player_trace_attack", function(ev)
	if ev.hit_group ~= 1 then
		ev:block()
	end
end, { before = true })

Doble daño con cuchillos

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 })

Cambiar quién gana una ronda

-- 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 })

Cambiar el menú de compra

Los artículos van por el id que los jugadores escriben para comprarlos (awp, hegren, vesthelm; cs.buy_items() los lista).

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,
})

Una ventana de tienda en lugar del menú 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)

Un modo de juego

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)

El tutorial construye un modo completo paso a paso.

Una votación 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

Llenar el servidor con los bots del juego

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 crea otro tipo de bot: uno que mueve tu propio plugin (repeticiones, maniquíes), sin IA.

El mundo

Un objeto 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 })

Buscar 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 })

Cambiar las entidades de un mapa al cargarlo

-- 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)

Datos y servicios

Estadísticas en 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)

Las consultas se ejecutan en un hilo de fondo, así que un disco lento nunca frena el juego.

Publicar en un 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 que trabajan juntos

Ofrecer una función y usarla en otro lado

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 propios

-- 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)

Pruebas

Una prueba con jugadores y 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)

Ejecútala con cs_plugin test <folder>; Herramientas lista todo lo que ofrece el contexto de pruebas.