Useful Functions
#1

Useful Functions
Because the old topic was deleted, i got permission to create a new 'Useful Functions'-topic.
In this topic you can post selfmade functions.

Rules:
  • DO NOT POST UNTESTED CODE!
  • Do not spam
  • Do not go offtopic
  • If you post a function which is not created by yourself, you have to give the original author credits
  • And also if you use a function in your gamemode that you copied from this topic, don't forget to give the original author credits


Reply
#2

CagePlayer(playerid);
this is function does the same as my /cage command in V-Admin (puts a player in a cage :P).

pawn Code:
// Top of script
new cage[MAX_PLAYERS], cage2[MAX_PLAYERS], cage3[MAX_PLAYERS], cage4[MAX_PLAYERS], caged[MAX_PLAYERS];

// new function
stock CagePlayer(playerid)
{
      if(IsPlayerConnected(playerid))
      {
      new Float:X, Float:Y, Float:Z;
      GetPlayerPos(playerid, X, Y, Z);
      cage[playerid] = CreateObject(985, X, Y+4, Z, 0.0, 0.0, 0.0);
      cage2[playerid] = CreateObject(985, X+4, Y, Z, 0.0, 0.0, 90.0);
      cage3[playerid] = CreateObject(985, X-4, Y, Z, 0.0, 0.0, 270.0);
      cage4[playerid] = CreateObject(985, X, Y-4, Z, 0.0, 0.0, 180.0);
      caged[playerid] = 1; // Use this in a /cage command to prevent being caged twice and causing the cage to be unremovable.
      PlayerPlaySound(playerid, 1137, X, Y, Z);
      }
}
UnCagePlayer(playerid);
This will remove the cage

pawn Code:
stock UnCagePlayer(playerid)
{
      cage[playerid] = DestroyObject(cage[playerid]);
      cage2[playerid] = DestroyObject(cage2[playerid]);
      cage3[playerid] = DestroyObject(cage3[playerid]);
      cage4[playerid] = DestroyObject(cage4[playerid]);
      caged[playerid] = 0;
}
Reply
#3

DisableBadWord(word[])
word[] - word which will be disabled
pawn Code:
#define DisableBadword(%1) for(new i=0; i<strlen(text); i++) if(strfind(text[i], %1, true) == 0) for(new a=0; a<256; a++) if (a >= i && a < i+strlen(%1)) text[a]='*'
Reply
#4

Quote:
Originally Posted by Andre9977
PS: It's "Useful Functions", not "Usefull functions".
Thanks, i fixed typo now

SendClientMessageToAllEx(exception, color, const message[])
This function sends a message to all players, except for 1 player. (exception)

Code:
stock SendClientMessageToAllEx(exception, color, const message[])
{
  for(new i; i<MAX_PLAYERS; i++)
  {
    if(IsPlayerConnected(i))
 	{
	  if(i != exception)
	  {
	    SendClientMessage(i, color, message);
	  }
	}
  }
}
GetVehicleDriver(vehicleid)
Returns the ID of the player driving in the vehicle. Returns '-1' if nobody is driving in the vehicle.
Code:
stock GetVehicleDriver(vehicleid)
{
  for(new i; i<MAX_PLAYERS; i++)
  {
    if (IsPlayerInVehicle(i, vehicleid))
    {
      if(GetPlayerState(i) == 2)
      {
    		return i;
      }
	}
  }
  return -1;
}
Reply
#5

Quote:
Originally Posted by =>Sandra<=
SendClientMessageToAllEx(exception, color, const message[])
This function sends a message to all players, except for 1 player. (exception)

Code:
stock SendClientMessageToAllEx(exception, color, const message[])
{
  for(new i; i<MAX_PLAYERS; i++)
  {
    if(IsPlayerConnected(i))
 	{
	  if(i != exeption)
	  {
	    SendClientMessage(i, color, message);
	  }
	}
  }
}
Need a 'c' in "if(i != ex©eption)"

EDIT: Please delete this post when noted.
Reply
#6

Gotta love Kye deleting my account and thus all the topics that went with it. Anyway, some of my useful functions I've made over the years have been ported to YSI and put in the YSI_misc.own file. The file can be found:

here

Functions include:

swap(var1, var2) - Swap two variables without a third variable.
xor:==xor: - Do a logical xor check on two variables.
ceildiv - Divide two integers and round up.
isnull - Used for empty strings passed via CallRemoteFunction.
iseven - Obvious.
isodd - Obvious.
floordiv - Rounded down integer division.
chrfind - Find a single character in a string, faster than strfind for single characters.
chrnfind - Find the end of a set of characters in a string (for example to skip a set of spaces).
strcpy - Copy a string.
bernstein - Like Adler32 hash but faster and less collisions.
bernstein_copy - Mix of strcpy and bernstein for speed.
StripNL - Similar to PHP's rtrim.
strconcat - Stick two strings together.
QuickSort - Call wrapper for QSort, sorts an array into newmerical order.
QSort - Workhorse recursive function for QuickSort.
chrtolower - Convert a character to lowercase.
strtolower - Convert a string to lowercase.
hexstr - strval for hex strings.
binstr - Checks if a string is "0" or "false".
ReturnPlayerName - Obvious.
ishex - Checks if a string is hexadecimal.
numstr - Converts a number to a string, should use valstr but doesn't.
chrtoupper - Convert a character to upper case.
strtoupper - Convert a string to upper case.
timestamp - Get the unix timestamp for the current time.
mktime - Get the unix timestamp for a given time.
GetIP - Return a player's IP as a 32bit integer.
getintpar - Gets a number from a string apparently.
IsConnected - Like IsPlayerConnected but uses YSI's internal foreach system.
KickDelay - Kick a player after a given amount of time. Used to ensure they get the message sent.
KickDelayCall - public function KickDelay calls.
BanDelay - Like KickDelay but ban.
BanDelayCall - Like KickDelayCall but ban.
endofline - Checks if the current position is the end of non-whitespace data.
isnumeric - Checks if a string is numeric.
abs - Returns the absolute (positive) value of a number.
sscanf - Deserves (and has) it's own tutorial on use.
explode - Like PHP's explode function.
IsPlayerInRangeOfPoint - Checks if a player is near a point without calling floatsqroot for speed.

The library also has a couple of useful variables:

TRUE - Always true, used for infinate loops.
FALSE - Always false, used for large code macros.
NULL - The string passed instead of an empty string by CallRemoteFunction due to the way the PAWN VM works.
Reply
#7


Quote:
Originally Posted by =>Sandra<=
SendClientMessageToAllEx(exception, color, const message[])
This function sends a message to all players, except for 1 player. (exception)
Isn't this the same as Yom's "SendClientMessageToAllOthers"?
Reply
#8

Quote:
Originally Posted by Andre9977
GetName()
playerid - the player who's name we're getting
The name will be stored in "PlayerName" variable!
pawn Code:
stock GetName(playerid)
{
  new PlayerName;
  GetPlayerName(playerid, PlayerName, sizeof(PlayerName));
  return PlayerName;
}
Have you tried compiling that?

Also:
pawn Code:
printf("KickEx(): %s(%i) kicked, reason: %s", PlayerName, playerid);
Should be
pawn Code:
printf("KickEx(): %s(%i) kicked, reason: %s", PlayerName, playerid, reason);
right?

And also, it seems you are using your own GetName function wrongly, you say its GetName(playerid, variable) in the NameCheck() thing, yet it is actually GetName(playerid).
Reply
#9

Admin(msg) - Sends a message to the online rcon admins!
Code:
stock Admin(msg[])
{
  for(new i 0; i<GetMaxPlayers(); i++
  {
    if(IsPlayerConnected(i) && IsPlayerAdmin(i)) SendClientMessage(i,white,msg);
  }
}
Quote:
Originally Posted by Y_Leѕѕ
Gotta love Kye deleting my account and thus all the topics that went with it.
Sorry to go offtopic, but why did he do that?



Reply
#10

Quote:
Originally Posted by Andre9977
Quote:
Originally Posted by DragSta
< shizzle >
Yes, fixed now.

About the cells I forgot - I was about to write MAX_PLAYER_NAME instead of 24, but then something went... wrong.
Ok, well your half way there. But it still wont work, GetName(playerid) directly returns the players name, so it could be used like:
pawn Code:
printf("Name: %s", GetName(playerid));
It wont work because you just call it so it gets the players name (yet you dont catch what it returns), then you try and read the NON Global variable...
Reply
#11

In addition to Andre:
NOTE! this is not made by me, i dont take any credits!

use this in your script:
pawn Code:
if(!IsPlayerInInvalidNosVehicle(playerid, vehicleid) //notice the "!"
pawn Code:
//----------[ IsPlayerInValidNosVehicle made by [fackin']luke]---------------------
IsPlayerInInvalidNosVehicle(playerid,vehicleid)
{
  #define MAX_INVALID_NOS_VEHICLES 29

  new InvalidNosVehicles[MAX_INVALID_NOS_VEHICLES] =
  {
    581,523,462,521,463,522,461,448,468,586,
    509,481,510,472,473,493,595,484,430,453,
    452,446,454,590,569,537,538,570,449
  };

  vehicleid = GetPlayerVehicleID(playerid);

  if(IsPlayerInVehicle(playerid,vehicleid))
  {
        for(new i = 0; i < MAX_INVALID_NOS_VEHICLES; i++)
        {
          if(GetVehicleModel(vehicleid) == InvalidNosVehicles[i])
          {
            return true;
          }
        }
  }
  return false;
}
// end of it!
Reply
#12

CheckPlayerName - checks a string to ensure it follows the traditional Firstname_Lastname roleplay name format

Returns:
0 - Invalid roleplay name
1 - Valid roleplay name

pawn Code:
CheckPlayerName(const name[]) // by Luk0r
{
    if (strlen(name) < 6) return 0;
    if (strfind(name, "_", true) == -1) return 0;
    new underscorecount, expectinguppercase = 1;
    for (new i = 0, j = strlen(name); i < j; i++)
    {
        if (expectinguppercase == 1)
        {
            if (name[i] < 'A' || name[i] > 'Z') return 0;
            expectinguppercase = 0;
            continue;
        }
        switch (name[i])
        {
            case '_':
            {
                if (underscorecount == 1) return 0;
                else
                {
                    underscorecount = 1;
                    expectinguppercase = 1;
                }
                continue;
            }
            case 'A' .. 'Z': continue;
            case 'a' .. 'z': continue;
            default: return 0;
        }
    }
    return 1;
}
Reply
#13

Again: to complete andre's list: IsABoat

IsABoat(carid)
carid - Vehicle ID that we check
pawn Code:
stock IsABoat(carid)
{
  new Operative[] = { 472, 473, 493, 495, 484, 430, 454, 453, 452, 446 };
  for(new i = 0; i < sizeof(Operative); i++)
  {
    if(GetVehicleModel(carid) == i) return 1;
  }
  return 0;
}

Reply
#14

Quote:
Originally Posted by Andre9977
Quote:
Originally Posted by [ЯЈ®†
$!7ЈС©!Х™ ]
Again: to complete andre's list: IsABoat
Thank you.
I hope you don't mind - I added to my post with your credit and link to your account of course.
no problem, you could clearly see i used your layout!
Reply
#15

RPName
Returns first and last name of an RP style name (e.g. John_Bortch will return John and Bortch). It returns 0 if the RP Name isnt valid

Code:
RPName(name[],ret_first[],ret_last[])
{
	new len = strlen(name),
		point = -1,
		bool:done = false;
	for(new i = 0; i < len; i++)
	{
	  if(name[i] == '_')
	  {
	    if(point != -1) return 0;
	    else {
				if(i == 0) return 0;
				point = i + 1;
			}
	  } else if(point == -1) ret_first[i] = name[i];
	  else {
			ret_last[i - point] = name[i];
			done = true;
		}
	}
	if(!done) return 0;
	return 1;
}
Usage:
Code:
public OnPlayerConnect(playerid)
{
	new name[MAX_PLAYER_NAME], first[MAX_PLAYER_NAME], last[MAX_PLAYER_NAME], ret;
	GetPlayerName(playerid,name,sizeof(name));
	if(RPName(name,first,last))
	{
		// Valid name, player is called first_last
	} else {
	  // Invalid name, deal accordingly
	}
	return 1;
}
strtok
Code:
strtok(string[],&idx,seperator = ' ')
{
	new ret[128], i = 0, len = strlen(string);
	while(string[idx] == seperator && idx < len) idx++;
	while(string[idx] != seperator && idx < len)
	{
	  ret[i] = string[idx];
	  i++;
		idx++;
	}
	while(string[idx] == seperator && idx < len) idx++;
	return ret;
}
rand
An exact copy of the function "rand" in PHP.

pawn Code:
rand(minnum = cellmin,maxnum = cellmax) return random(maxnum - minnum + 1) + minnum;
GetVehicleName
Returns the vehicle name from a modelid.
http://boylett.pastebin.com/f3a9a059c

Float:GetPointDistanceToPoint
pawn Code:
Float:GetPointDistanceToPoint(Float:x1,Float:y1,Float:x2,Float:y2)
{
  new Float:x, Float:y;
  x = x1-x2;
  y = y1-y2;
  return floatsqroot(x*x+y*y);
}
Float:GetPointDistanceToPointEx
pawn Code:
Float:GetPointDistanceToPointEx(Float:x1,Float:y1,Float:z1,Float:x2,Float:y2,Float:z2)
{
  new Float:x, Float:y, Float:z;
  x = x1-x2;
  y = y1-y2;
  z = z1-z2;
  return floatsqroot(x*x+y*y+z*z);
}
Reply
#16

Quote:
Originally Posted by DragSta
It also wont work
pawn Code:
GetPlayerScore(playerid);
AHHH! stupid me! well here's one that does work!

GivePlayerVehicle(playerid, vehicleid);
pawn Code:
stock GivePlayerVehicle(playerid, vehicleid)
{
    if(!IsPlayerInAnyVehicle(playerid) && vehicleid > 399 && vehicleid < 612)
    {
        new Float:x, Float:y, Float:z, Float:a, vehicle;
        GetPlayerPos(playerid, x, y, z);
        GetPlayerFacingAngle(playerid, a);
        vehicle = CreateVehicle(vehicleid, x, y, z, a, -1, -1, 50000);
        PutPlayerInVehicle(playerid, vehicle, 0);
    }
}
saves a lot of time when u need to to do this eveytime you want to spawn a vehicle!

Reply
#17

Not all is made by me, but some!



GetObjectToPlayerDistance(playerid, objectid);
pawn Code:
stock GetObjectToPlayerDistance(playerid, objectid) //By me, Credits: Whoever made GetDistanceBetweenPlayers
{
    new Float:ox, Float:oy, Float:oz, Float:px, Float:py, Float:pz;
    new Float:distance;
    GetObjectPos(objectid, ox, oy, oz);
    GetPlayerPos(playerid, px, py, pz);
    distance = floatsqroot(floatpower(floatabs(floatsub(ox, px)),2)+floatpower(floatabs(floatsub(oy, py)),2)+floatpower(floatabs(floatsub(oz, pz)),2));
    return floatround(distance);
}
GetDistanceFromPlayerToVehicle(playerid, vehicleid);
pawn Code:
stock GetDistanceFromPlayerToVehicle(playerid, vehicleid)
{
    new Float:x1,Float:y1,Float:z1,Float:x2,Float:y2,Float:z2;
    new Float:tmpdis;
    GetPlayerPos(playerid,x1,y1,z1);
    GetVehiclePos(vehicleid2,x2,y2,z2);
    tmpdis = floatsqroot(floatpower(floatabs(floatsub(x2,x1)),2)+floatpower(floatabs(floatsub(y2,y1)),2)+floatpower(floatabs(floatsub(z2,z1)),2));
    return floatround(tmpdis);
}
GetVehiclePlayerID(vehicleid);
pawn Code:
stock GetVehiclePlayerID(vehicleid)
{
    for(new i=0; i<MAX_PLAYERS; i++)
    {
        if(vehicleid == GetPlayerVehicleID(i))
        {
            return vehicleid;
        }
    }
    return INVALID_PLAYER_ID;
}
GetDistanceBetweenVehicles(vehicleid, vehicleid2);
pawn Code:
stock GetDistanceBetweenVehicles(vehicleid, vehicleid2)
{
    new Float:x1,Float:y1,Float:z1,Float:x2,Float:y2,Float:z2;
    new Float:tmpdis;
    GetVehiclePos(vehicleid,x1,y1,z1);
    GetVehiclePos(vehicleid2,x2,y2,z2);
    tmpdis = floatsqroot(floatpower(floatabs(floatsub(x2,x1)),2)+floatpower(floatabs(floatsub(y2,y1)),2)+floatpower(floatabs(floatsub(z2,z1)),2));
    return floatround(tmpdis);
}
GetDistanceBetweenPlayers(playerid, playerid2)
pawn Code:
stock GetDistanceBetweenPlayers(playerid, playerid2)
{
    new Float:x1,Float:y1,Float:z1,Float:x2,Float:y2,Float:z2;
    new Float:tmpdis;
    GetPlayerPos(playerid,x1,y1,z1);
    GetPlayerPos(playerid2,x2,y2,z2);
    tmpdis = floatsqroot(floatpower(floatabs(floatsub(x2,x1)),2)+floatpower(floatabs(floatsub(y2,y1)),2)+floatpower(floatabs(floatsub(z2,z1)),2));
    return floatround(tmpdis);
}
GetPlayerVehicleModel(playerid);
pawn Code:
stock GetPlayerVehicleModel(playerid)
{
    new vehicleid = GetPlayerVehicleID(playerid);
    new model = GetVehicleModel(vehicleid);
    return model;
}
Reply
#18

SafeKill(playerid);
Makes you spawn without losing weapons
pawn Code:
stock SafeKill(playerid)
{
  new Weapons[MAX_PLAYERS][11], Ammo[MAX_PLAYERS][11]; // news
  for(new j=0; j<11; j++)   GetPlayerWeaponData(playerid, j, Weapons[playerid][j], Ammo[playerid][j]);// loop through all weapon slots + ammo
  SpawnPlayer(playerid); //respawn the player
  for(new j=0; j<11; j++)   GivePlayerWeapon(playerid, Weapons[playerid][j], Ammo[playerid][j]);// loop through all weapon slots + ammo
}
yes, i know this can be abused, but i made this keeping in mind how stupid it is to somehow be stuck, do /kill, and have to start all over...
Reply
#19

Quote:
Originally Posted by LarzI aka. GloZzy
GetVehiclePlayerID(vehicleid);
pawn Code:
stock GetVehiclePlayerID(vehicleid)
{
    for(new i=0; i<MAX_PLAYERS; i++)
    {
        if(vehicleid == GetPlayerVehicleID(i))
        {
            return vehicleid;
        }
    }
    return INVALID_PLAYER_ID;
}
Shouldn't it be:
Code:
return i;
instead of
Code:
return vehicleid;
??
Reply
#20

http://web.archive.org/web/200702250...hp?topic=638.0

Latest archive of the usefull functions topic. I suggest you add to the first post.

WeeDarr
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)