Useful Functions

Function name: generateRandomString
Use: Generates a random string according to length, and stores it at destination. Used commonly for reaction tests filtercsripts.

Code:
pawn Код:
static const
        validChars[ 77 ] = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!@#$%^&*()-_+=";
       
stock generateRandomString( dest[ ], len = 6 )
{
    for ( new i = 0; i < len; ++ i )
        dest[ i ] = validChars[ random( sizeof ( validChars ) - 1 ) ];
}
Test code:
pawn Код:
#include < a_samp >

static const
        validChars[ 77 ] = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!@#$%^&*()-_+=";
       
stock generateRandomString( dest[ ], len = 6 )
{
    for ( new i = 0; i < len; ++ i )
        dest[ i ] = validChars[ random( sizeof ( validChars ) - 1 ) ];
}

public OnFilterScriptInit( )
{
    new
        str[ 20 ][ 12 ];
    for ( new i; i < 20; ++ i )
    {
        generateRandomString( str[ i ], 12 );
        print( str[ i ] );
    }
    return 1;
}
Output from test code:
Код:
[01:25:11] %DqD2Q+I@SF$
[01:25:11] M(d1A9hE#&DC
[01:25:11] DP8&wkH#=Goo
[01:25:11] R4xMVp#ujhbx
[01:25:11] _eZ+SD4L+VU6
[01:25:11] &xDMyG0vW53c
[01:25:11] %b#fv3Mvo3rB
[01:25:11] b&ITEfwX7tH*
[01:25:11] 26NW$zy2n2_D
[01:25:11] 86_T9347m8g-
[01:25:11] z7YL37TFLNEq
[01:25:11] gDi8d1!Zw-l!
[01:25:11] *y4FoGu_Cz3u
[01:25:11] EaRrvpS$&!l(
[01:25:11] GMD#t_Y=#&^q
[01:25:11] &_M$pTA-9Xnm
[01:25:11] tvE_5Z7srHRG
[01:25:11] XQ6Oz+w-2COD
[01:25:11] #P+5n%Q=b03A
[01:25:11] mY%=xk=CkdMw
Additional Info: If you are planning to use it in reaction tests, remove char '%' and change validChars size to 76. (because in game % shows as #)
Reply

pawn Код:
stock InsertWildcardsIntoIp(ip[], count, asterisk = 1, checkvalid = 0)
{
    new
        j,
        nip[16],
        dotCount,
        ipLen = strlen(ip),
        bool:skipOctet = false,
        wc = (asterisk) ? '*' : '%',
        bool:inWCOctet = (count == 4) ? true : false;

    if (ipLen >= 16 || ipLen < 7 || count > 4 || count < 1)
        return 0;
       
    if (checkValid) {
        for (new i = 0; i < ipLen; i++)
            if (ip[i] == '.')
                dotCount++;
        if (dotCount != 3)
            return 0;
        dotCount = 0;
    }
   
    for (new i = 0; i < ipLen; i++) {
        if (ip[i] != '.') {
            if (inWCOctet) {
                if (!skipOctet) {
                    nip[j] = wc;
                    j++;
                    skipOctet = true;
                }
            } else {
                if ('0' <= ip[i] <= '9') {
                    // numeric
                    nip[j] = ip[i];
                    j++;
                } else
                    return 0;
            }
        } else {
            // dot
            dotCount++;
            nip[j] = '.';
            j++;
            skipOctet = false;
            inWCOctet = (count >= 4 - dotCount) ? true : false;
        }
        ip[i] = 0;
    }
       
    memcpy(ip, nip, 0, j * 4, j * 4);
       
    return 1;
}
Useful for replacing 'count' number of octets of an IP Address (ip[]) with wildcards (either '%'s or '*'s depending on the 'asterisk' parameter), starting from last octet to first octet. Can be used with BlockIpAddress.
Reply

Quote:
Originally Posted by Corekt
Посмотреть сообщение
pawn Код:
stock InsertWildcardsIntoIp(ip[], count, asterisk = 1, checkvalid = 0)
{
    // ...
}
Useful for replacing 'count' number of octets of an IP Address (ip[]) with wildcards (either '%'s or '*'s depending on the 'asterisk' parameter), starting from last octet to first octet. Can be used with BlockIpAddress.
Quite a lot of overkill there, since it can be accomplished in about three lines with sscanf.

pawn Код:
new ipParts[4], output[16];
sscanf(ip, "p<.>a<i>[4]", ipParts);
format(output, sizeof(output), "%d.%d.*.*", ipParts[0], ipParts[1]);
Reply

Quote:
Originally Posted by greentarch
Посмотреть сообщение
Function name: generateRandomString
Use: Generates a random string according to length, and stores it at destination. Used commonly for reaction tests filtercsripts.

Code:
pawn Код:
static const
        validChars[ 77 ] = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!@#$%^&*()-_+=";
       
stock generateRandomString( dest[ ], len = 6 )
{
    for ( new i = 0; i < len; ++ i )
        dest[ i ] = validChars[ random( sizeof ( validChars ) - 1 ) ];
}
This could also be done like this:
Код:
stock generateRandomString(dest[ ], len = 6)
{
    for (new i = 0; i < len; ++i)
        dest[i] = (random(2) ? (random(26) + (random(2) ? 'a' : 'A')) : (random(31) + '!'));
}
I did not test if it's faster, though it's less code and covers more symbols. Just in case some don't know about ASCII characters and numbers.
Reply

Quote:
Originally Posted by Majd
Посмотреть сообщение
Can someone create
ReplaceObject(objectid, object, x, y, z);

It would be great, Thanks.
You could simply do:
pawn Код:
stock ReplaceObject(objectid, destmodel)
{
    new Float:X, Float:Y, Float:Z;
    GetObjectPos(objectid, X, Y, Z);
    DestroyObject(objectid);
    CreateObject(destmodel, X, Y, Z, 0.0, 0.0, 0.0);
    return 1;
}
Reply

@ThePhenix :

pawn Код:
stock ReplaceObject(objectid, newmodel)
{
      new Float:data[6];
      GetObjectPos(objectid, data[0], data[1], data[2]);
      GetObjectRot(objectid, data[3], data[4], data[5]);
      DestroyObject(objectid);
      objectid = CreateObject(newmodel, data[0], data[1], data[2], data[3], data[4], data[5]);
      return;
}
Reply

Quote:
Originally Posted by S4t3K
Посмотреть сообщение
@ThePhenix :

pawn Код:
stock ReplaceObject(objectid, newmodel)
{
      new Float:data[6];
      GetObjectPos(objectid, data[0], data[1], data[2]);
      GetObjectRot(objectid, data[3], data[4], data[5]);
      DestroyObject(objectid);
      objectid = CreateObject(newmodel, data[0], data[1], data[2], data[3], data[4], data[5]);
      return;
}
Basically, you just added the rotation.
Reply

Basically, if you wanna replace the model of an object, you don't have to modify the rotation (in this case, to reset it). So even if it doesn't look as so, it's important.
Reply

Thank you both !
Reply

One issue with "ReplaceObject":

For instance, I create two objects:

pawn Код:
new object1 = CreateObject(3095, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
new object2 = CreateObject(9000, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
Then, I destroy "object1":

pawn Код:
DestroyObject(object1);
And I replace "object2" with another model:

pawn Код:
ReplaceObject(object2, 3089);
In the "ReplaceObject" code, you have this:

pawn Код:
DestroyObject(objectid);
objectid = CreateObject(newmodel, data[0], data[1], data[2], data[3], data[4], data[5]);
Since "object1" was deleted, any object created afterwards will use the first free object ID, which would be the old ID from "object1". This would render "object2" useless because "objectid" now has a different ID.

My version:

pawn Код:
ReplaceObject(objectid, modelid)
{
    new
        Float:fX,
        Float:fY,
        Float:fZ,
        Float:fRotX,
        Float:fRotY,
        Float:fRotZ;

    if (GetObjectPos(objectid, fX, fY, fZ) && GetObjectRot(objectid, fRotX, fRotY, fRotZ))
    {
        DestroyObject(objectid);
        return CreateObject(modelid, fX, fY, fZ, fRotX, fRotY, fRotZ);
    }
    return INVALID_OBJECT_ID;
}
So then you could do this:

pawn Код:
new object;

main()
{
    object = CreateObject(3095, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0);

    // ...

    object = ReplaceObject(object, 3000);
}
Reply

You just could pass the objectid variable by reference than there shouldn't be a problem with the first version although Emmet_'s version is better because it checks if the object even exist
Reply

I'm trying to code a "strfloat" function which will transform a floating point number in a string (without having to use format of course).
Though, I'm blocked here :

pawn Код:
strfloat(Float:nbr, dest[22])
{
    new rtn = floatround(nbr);
    new pos;
    do
    {
        dest[pos++] = '0' + rtn % 10;
        rtn /= 10;
    }
    while(rtn);
   
    new i;
    for(i = 1; i < 1000000000; i*=10)
    {
        if(rtn % (i)) continue;
        break;
    }
    // how to check how much zeros has "i" and then reassigning the checked value to "i" ?
    new str[22];
    strcat(string, dest[i+1]);
    dest[i+1] = '.';
    dest[i+2] = str;  
}
Reply

Well, since I just do it to improve my pawn skills, I can't stick to format.

I've read about the IEEE 754 standard that the floats are stored using this schema :

sign exposant mantissa
1 bit...8 bits.....23 bits

But I'm still stuck with a problem : do the pawn stores the floats in bytes or in cells ?
I haven't took a look to the pawn implementation in c so I absolutely don't know.

The only thing I've looked about and which is related to this topic is the format function that SA-MP uses (or at least seems using).
I looked closer at the %f specifier and so at the AddFloat function, but it's still blurred to me.
Reply

Okay, I'll look closer at the pdf files tomorrow. Thanks a lot.
Reply

CountWord

This function will return the number of times the given word has been repeated in a string.
pawn Код:
stock CountWord(string[], word[], bool:ignorecase = false)
{
    new
        temp_Counts = 0,
        temp_Pos = -1;
    temp_Pos = strfind(string, word, ignorecase, 0);
    while(temp_Pos != -1)
    {
        temp_Counts++;
        temp_Pos = strfind(string, word, ignorecase, temp_Pos + strlen(word) - 1);
    }
    return temp_Counts;
}
Example:
pawn Код:
new
        string[] = {"This is a string, this string contains something. This is something and this will be found!"};
printf("%d times", CountWord(string, "This", false);
The above code will print "2 times" because ignorecase is set to false. If it was set to true, it would've printed "4 times".
Reply

currency_format

This function returns a number to it's currency format (as a string).

Code:
pawn Код:
stock currency_format(number, delim[2] = ",")
{
    new
        temp_Str[32],
        temp_Len = 0;
    valstr(temp_Str, number, false);
    temp_Len = strlen(temp_Str);
    strins(temp_Str, "$", 0, sizeof(temp_Str));

    if(temp_Len > 3)
    {
        for(new i = 3; i< temp_Len; i += 3)
        {
            strins(temp_Str, delim, temp_Len - i+1, sizeof(temp_Str));
        }
    }
    return temp_Str;
}
delim - An optional parameter, it is the character to be used for separating.
Example:
pawn Код:
for(new i = 100; i<= 10000000; i*=10)
{
    print(currency_format(i, ",")); //is same as currency_format(i)
}
Output:
Код:
$100
$1,000
$10,000
$100,000
$1,000,000
$10,000,000
Reply

1) GetWeaponSlot

This function returns the slot ID of the weapon. If it's an invalid weapon ID, then it will return -1 value.

Code:
pawn Код:
new
    g_WeaponSlots[47] =
    {
        0, //Fist,
        0, //Brass,
        1, //Golf,
        1, //Night,
        1, //Knife,
        1, //Baseball bat,
        1, //Shovel,
        1, //Pool,
        1, //Katana,
        1, //Chainsaw,
        10, //P Dildo,
        10, //Dildo,
        10, //Vibrator,
        10, //Silver Vib,
        10, //Flowers,
        10, //Cane,
        8, //Grenade,
        8, //Tear gas
        8, //Moltov,
        -1, //Invalid,
        -1, //Invalid,
        -1, //Invalid,
        2, //Colt,
        2, //Silenced,
        2, //Deagle,
        3, //Shotgun,
        3, //Sawnoff
        3, //Spas
        4, //Uzi,
        4, //Mp5,
        5, //AK47,
        5, //M4,
        4, //Tec9,
        6, //Rifle,
        6, //Sniper,
        7, //Rocket launcher,
        7, //Heat seeker,
        7, //Flame thrower,
        7, //Minigun,
        8, //Satchel,
        12, //Detonator,
        9, //Spray can,
        9, //Extinguisher,
        9, //Camera
        11, //Night vision,
        11, //Thermal vision,
        11}; //Parachute
       
stock GetWeaponSlot(weaponid)
{
    if(weaponid >= 0 && weaponid <= 46)
        return g_WeaponSlots[weaponid];
    else return -1;
}
Use:
pawn Код:
printf("Desert Eagle's weapon slot : %d", GetWeaponSlot(24));
printf("Sawnoff's weapon slot : %d", GetWeaponSlot(26));


2) RemoveWeapons

This function allows you to remove multiple weapons at a time.

Code:
pawn Код:
stock RemoveWeapons(playerid, ...)
{
    for(new i = 1, j = numargs(); i< j; i++)
    {
        SetPlayerAmmo(playerid, getarg(i), 0);
    }
    return 1;
}
Use:
pawn Код:
RemoveWeapons(playerid, 38, 24, 26);
//Weapons such as Minigun(38), Desert Eagle(24) and Sawnoff(26) will be removed from player's inventory.
Reply

Thanks for pointing that out, edited.
Reply

GetVehicleWheelPos(vehicleid, wheel, &Float, &Float:y, &Float:z)
This function does include an optional macro for wheel types, but you can put it the integer values if you prefer it...
pawn Код:
#define WHEELSFRONT_LEFT    0
#define WHEELSFRONT_RIGHT   1
#define WHEELSMID_LEFT      2
#define WHEELSMID_RIGHT     3
#define WHEELSREAR_LEFT     4
#define WHEELSREAR_RIGHT    5
The macros are quite self-explanatory and are easier to identify compared to the numbers themselves.

pawn Код:
GetVehicleWheelPos(vehicleid, wheel, &Float:x, &Float:y, &Float:z)
{
    new Float:rot, Float:x2, Float:y2, Float:z2, Float:div;
    GetVehicleZAngle(vehicleid, rot);
    rot = 360 - rot;
    GetVehiclePos(vehicleid, x2, y2, z2);
    switch(wheel)
    {
        case WHEELSFRONT_LEFT .. WHEELSFRONT_RIGHT: //Front Tyres
           GetVehicleModelInfo(GetVehicleModel(vehicleid), VEHICLE_MODEL_INFO_WHEELSFRONT, x, y, z);
        case WHEELSMID_LEFT .. WHEELSMID_RIGHT: //Middle Tyres
            GetVehicleModelInfo(GetVehicleModel(vehicleid), VEHICLE_MODEL_INFO_WHEELSMID, x, y, z);
        case WHEELSREAR_LEFT .. WHEELSREAR_RIGHT: //Rear Tyres
            GetVehicleModelInfo(GetVehicleModel(vehicleid), VEHICLE_MODEL_INFO_WHEELSREAR, x, y, z);
        default: return 0;
    }
    div = (wheel % 2) ? (x) : (-x);
    x = floatsin(rot, degrees) * y + floatcos(rot, degrees) * div + x2;
    y = floatcos(rot, degrees) * y - floatsin(rot, degrees) * div + y2;
    z += z2;
    return 1;
}
Considering that the values of the wheel type are not changed, this function will work.

Example of it's usage:
pawn Код:
CMD:fixtyre(playerid, params[])
{
    new vehicleid = GetPlayerVehicleID(playerid);
    if(!vehicleid) return 0;
    new Float:x, Float:y, Float:z;
    if(!GetVehicleWheelPos(vehicleid, WHEELSREAR_LEFT, x, y, z)) return print("Invalid wheel type");
    //Get the tyre position of the rear left tyre.
    SetPlayerCheckpoint(playerid, x, y, z, 1.0);
    //Sets a checkpoint on the player's rear left tyre.
    SendClientMessage(playerid, -1, "A checkpoint has been placed on your back tyre.");
    return 1;
}
Reply

pawn Код:
stock LastIndexOf(string[], character, size = sizeof string)
{
    for(new i = size - 1; i > 0; i--)
    {
        if(string[i] == character)
            return i;
    }
    return -1;
}
pawn Код:
new string[] = "f.oo.ba.r";
new index = LastIndexOf(string, '.'); // index = 7
Reply


Forum Jump:


Users browsing this thread: 19 Guest(s)