Write a Sourcemod plugin for CSS that gives players an AK47 when they spawn. Add error…
- User
Write a Sourcemod plugin for CSS that gives players an AK47 when they spawn. Add error checking.
- Assistant
Write a Sourcemod plugin for CSS that gives players an AK47 when they spawn. Add error checking.
Certainly! Below is a complete SourceMod plugin for Counter-Strike: Source (CSS) that equips players with an AK-47 every time they spawn. The plugin includes comprehensive error checking to ensure reliability and ease of debugging.
player_spawn event, which is triggered every time a player spawns.weapon_ak47)./**
* @file ak47_giver.sp
* @brief SourceMod plugin to give players an AK-47 upon spawn in Counter-Strike: Source.
* @author
* @version 1.0
* @date 2023-04-27
*/
#include <sourcemod>
#include <sdkhooks>
// Plugin Information
#define PLUGIN_NAME "AK47 Giver"
#define PLUGIN_AUTHOR "YourName"
#define PLUGIN_VERSION "1.0"
#define PLUGIN_DESCRIPTION "Gives players an AK-47 upon spawn with error checking."
// Initialization and De-initialization
public void OnPluginStart()
{
// Hook the "player_spawn" event in post phase to ensure the player is fully spawned
HookEvent("player_spawn", Event_PlayerSpawned, EventHookMode_Post);
// Log that the plugin has been loaded
PrintToServer("[%s] v%s loaded by %s.", PLUGIN_NAME, PLUGIN_VERSION, PLUGIN_AUTHOR);
}
public void OnPluginEnd()
{
// Log that the plugin is being unloaded
PrintToServer("[%s] v%s unloaded.", PLUGIN_NAME, PLUGIN_VERSION);
}
/**
* @brief Event handler for player spawn.
* @param event Event name.
* @param clientnum Array index of the client.
* @param args Event arguments.
* @return Action to take after event.
*/
public Action Event_PlayerSpawned(Event event, const char[] name, bool dontBroadcast)
{
int client = GetClientOfUserId(event.GetInt("userid"));
// Validate client index
if (!IsClientInGame(client))
{
// Client is not in game, possibly disconnected
PrintToServer("[%s] Error: Client %d is not in game.", PLUGIN_NAME, client);
return Action_Continue;
}
// Attempt to give the AK-47 to the player
int result = GivePlayerItem(client, "weapon_ak47", true);
if (result == 1)
{
// Successfully gave the weapon
// Optionally, notify the player
// client may not have had weapons yet, so no need to drop existing ones
// Uncomment the next line if you want to notify players
// PrintToChat(client, "You have been given an AK-47!");
}
else
{
// Failed to give the weapon
// Log the error with relevant details
int userid = GetClientUserId(client);
char namebuf[64];
GetClientName(client, namebuf, sizeof(namebuf));
PrintToServer("[%s] Error: Failed to give AK-47 to Player [%d] %s.", PLUGIN_NAME, userid, namebuf);
}
return Action_Continue;
}
/**
* @brief Overrides the default item giving to include error checking.
* @param client The client index to give the item to.
* @param weapon The weapon entity name to give.
* @param giveAmmo Whether to also give ammo for the weapon.
* @return 1 on success, 0 on failure.
*/
int GivePlayerItem(int client, const char[] weapon, bool giveAmmo)
{
// Sanitize input
if (!IsClientInGame(client))
{
PrintToServer("[%s] Error: Invalid client index %d.", PLUGIN_NAME, client);
return 0;
}
// Attempt to give the weapon using the "give" command
char command[64];
bool useCommand = false;
// Alternatively, use the native API function if available
// For CS:S, using the command is more reliable
// Format the command to give the weapon
Format(command, sizeof(command), "give %s", weapon);
// Execute the command as the client
// Using ExecuteCommand with client as admin command
// This requires the client to have appropriate permissions
// To ensure the admin doesn't need permissions, use 'sm_give' if available
// Alternatively, spawn the weapon directly using SDKHooks or SDK functions
// Here, we'll use the native GivePlayerItem function from SDKHooks
// which handles giving items more reliably
// Initialize the weapon handle
Handle hWeapon = GetWeaponEnt(client, weapon);
if (hWeapon == INVALID_HANDLE)
{
// Weapon handle could not be created
PrintToServer("[%s] Error: Unable to create weapon handle for %s.", PLUGIN_NAME, weapon);
return 0;
}
// Give the weapon to the player
bool success = SDKGiveWeapon(client, hWeapon);
// Close the handle after use
CloseHandle(hWeapon);
if (success)
{
if (giveAmmo)
{
// Optionally, give ammo based on weapon type
// This can be customized as needed
// For simplicity, we'll just give full ammo
int ammoType = GetWeaponAmmoType(weapon);
if (ammoType != -1)
{
GiveAmmo(client, ammoType, 999);
}
else
{
PrintToServer("[%s] Warning: Unknown ammo type for %s.", PLUGIN_NAME, weapon);
}
}
return 1;
}
else
{
// Failed to give the weapon via SDKHooks
// Fallback: try executing the give command
ExecuteClientCommand(client, command);
// Optionally, add a delay or retry mechanism
// For now, assume failure
PrintToServer("[%s] Error: SDKGiveWeapon failed for %s.", PLUGIN_NAME, weapon);
return 0;
}
}
/**
* @brief Retrieves the weapon entity handle.
* @param client The client index.
* @param weapon The weapon entity name.
* @return Handle to the weapon entity, or INVALID_HANDLE on failure.
*/
Handle GetWeaponEnt(int client, const char[] weapon)
{
// Create the weapon entity
int ent = CreateEntityByName(weapon);
if (ent == -1)
{
PrintToServer("[%s] Error: CreateEntityByName failed for %s.", PLUGIN_NAME, weapon);
return INVALID_HANDLE;
}
// Attach the weapon to the player
DispatchSpawn(ent);
TeleportEntity(ent, 0.0, 0.0, 0.0); // Position is irrelevant as it's attached to the player
SetEntPropEnt(ent, Prop_Data, "m_hOwner", client);
// Return the entity handle
return GetHandleOfEnt(ent);
}
/**
* @brief Retrieves the ammo type based on weapon name.
* @param weapon The weapon entity name.
* @return Ammo type ID, or -1 if unknown.
*/
int GetWeaponAmmoType(const char[] weapon)
{
// Define ammo types based on common CS:S weapons
if (StrEqual(weapon, "weapon_ak47", false))
{
return GetAmmoIndex("762_mmbox"); // Example ammo type
}
// Add more weapons and their ammo types as needed
// Unknown weapon
return -1;
}
Plugin Metadata:
1.0 authored by YourName. You can replace YourName with your actual name or nickname.Initialization (OnPluginStart):
player_spawn event using HookEvent. The handler Event_PlayerSpawned is set to trigger after the player has fully spawned (EventHookMode_Post).De-initialization (OnPluginEnd):
Event Handler (Event_PlayerSpawned):
IsClientInGame.GivePlayerItem function.Giving the Weapon (GivePlayerItem):
GetWeaponEnt.SDKGiveWeapon from sdkhooks to equip the weapon to the player.giveAmmo is true, it calls GiveAmmo to provide the player with ammunition. The ammo type is determined by GetWeaponAmmoType.Helper Functions:
GetWeaponEnt: Creates and returns a handle to the weapon entity.GetWeaponAmmoType: Maps weapon names to their corresponding ammo types. You may need to adjust ammo type names based on the server's configuration.Prerequisites:
spcomp) which typically comes with the SourceMod installation.Compilation:
ak47_giver.sp.ak47_giver.sp.spcomp ak47_giver.sp
ak47_giver.smx file.Installation:
ak47_giver.smx to your server's addons/sourcemod/plugins/ directory.Verification:
Weapon and Ammo Names: Ensure that the weapon and ammo names used (weapon_ak47 and 762_mmbox in the example) match those defined on your server. You may need to adjust these based on the specific weapon configurations or custom content.
Permissions: The method used to give weapons should not require players to have elevated permissions. However, depending on your server's configuration, additional permission settings might be necessary.
Extensibility: This plugin can be easily extended to give different weapons based on player roles, server settings, or other conditions by modifying the Event_PlayerSpawned handler.
Feel free to customize and enhance this plugin further to suit your server's specific needs!
Not yet included in a published release.