[Funciones] Postea tus funciones aqui!
#21

Una invenciуn que se me ha ocurrido

їHas creado tus propios interiores y al entrar, a causa del lag, te has caido al vacio hasta morir?
ЎSe acabу gracias a la funciуn retardo!

Esta SIIIIIIIIIMPLE funciуn harб que al entrar en un interior creado por ti, espere a dejar moverse al jugador hasta que se cargue los objetos

їComo funciona?
Simplemente aсade
pawn Код:
Retardo(playerid);
En tu comando/funciуn de teletransporte

Ejemplo:
pawn Код:
if (strcmp("/comando", cmdtext, true, 10) == 0)
    {
        SetPlayerPos(playerid,312.121948,220.038497,882.79730);
        Retardo(playerid);
        return 1;
    }
/*-------------------------*/
    else if(PRESSED(KEY_WALK) && IsPlayerInRangeOfPoint(playerid, 5.0, 1772.2819,-1548.3059,9.9063))//Gente fuera dentro
    {
        SetPlayerPos(playerid,416.2079,158.9610,895.9077);
        SetPlayerInterior(playerid, 1);
        Retardo(playerid);
    }
La funciуn (aсadela fuera de ninguna funciуn en tu script)
pawn Код:
forward Retardo2(playerid);
stock Retardo(playerid)
{
    TogglePlayerControllable(playerid,0); //Congelamos jugador
    SetTimerEx("Retardo2",4000,false,"d",playerid); //Ponemos la espera
    GameTextForPlayer(playerid, "~y~Espera mientras      ~r~ se cargan los objetos", 2000, 6); //Avisamos
    return 1;
}
public Retardo2(playerid) //Se acaba la espera
{
    TogglePlayerControllable(playerid,1); //Descongelamos
    SendClientMessage(playerid, 0xFFFFFFFF, " Objetos cargados correctamente."); //Avisamos
    return 1;
}
Reply
#22

Muy bien hecho Mario!
En un servidor en el que juego, utilizan la misma funcion, te hace esperar a que se cargue todo para no caer al vacio.
Funcion mas que utilizable.
Reply
#23

Me alegro que os guste, ha sido improvisaciуn de 5 minutos XD
Reply
#24

La funciуn 'Retardo' puede ser stock ya que no se llama mediante un timer, la excepciуn es Retardo2.
La siguiente funciуn dara un enorme lag al servidor, el FPS de los jugadores bajarб mucho y el server dejara de responder.
pawn Код:
stock Lag()
{
    new v;
    do
    {
        if (v > 1) { v --; }
        else if (v < 0) { v ++; }
    }
    while(v != 3);
    return true;
}
Saludos.
Reply
#25

Quote:
Originally Posted by admantis
Посмотреть сообщение
La funciуn 'Retardo' puede ser stock ya que no se llama mediante un timer, la excepciуn es Retardo2.
La siguiente funciуn dara un enorme lag al servidor, el FPS de los jugadores bajarб mucho y el server dejara de responder.
pawn Код:
stock Lag()
{
    new v;
    do
    {
        if (v > 1) { v --; }
        else if (v < 0) { v ++; }
    }
    while(v != 3);
    return true;
}
Saludos.
en realidad no va a bajar los fps de los jugadores.
Reply
#26

Tu funciуn sуlo funciona para el id 0, SuperMarioRol.

Tendrнas que usar SetTimerEx.
Reply
#27

Quote:
Originally Posted by MrDeath537
Посмотреть сообщение
Tu funciуn sуlo funciona para el id 0, SuperMarioRol.

Tendrнas que usar SetTimerEx.
Cуmo sabes eso? O:!?
Reply
#28

Quote:
Originally Posted by the_chaoz
Посмотреть сообщение
en realidad no va a bajar los fps de los jugadores.
Bueno, a mi me los bajo.. Pero quizб sea porque el server al no responder ocupу mas memoria, y lo probй en localhost.

Disculpen.
Reply
#29

Quote:
Originally Posted by admantis
Посмотреть сообщение
Bueno, a mi me los bajo.. Pero quizб sea porque el server al no responder ocupу mas memoria, y lo probй en localhost.

Disculpen.
no hace falta que pidas disculpas por algo asi bro.
Reply
#30

Quote:
Originally Posted by MrDeath537
Посмотреть сообщение
Si bueno pero no importa XD, posteen comandos y funciones...
Bueno xd

Les postearй un comando mio (No tengo idea como se escriba) Modificado por the_chaoz, y publicado por mн xd (cuanto trabajo ._.)

Antes de todo, se que muchos buscan el comando pero no lo encuentran, asн que les facilito el mio (':

El comando es [quote]/advertir [ID] [Razуn]

pawn Код:
new Advertido[MAX_PLAYERS];
public OnPlayerDisconnect(playerid, reason)
{
    Advertido[playerid] = 0; //Seteamos la variable a 0
    return 1;
}

public OnPlayerCommandText(playerid, cmdtext[])
{
        if(!strcmp(cmd, "/ad", true)){
        tmp[0] = strtok(cmdtext, idx);
        tmp[1] = strtok(cmdtext, idx);
        if(!strlen(tmp[0]) || !strlen(tmp[1]))return SendClientMessage(playerid, COLOR_ROJO, "Usa: /ad [ID] [Razon].");
        new id;
        new str[128];
        id = strval(tmp[0]);
        if(IsPlayerConnected(id)){
        new name[2][MAX_PLAYER_NAME];
        GetPlayerName(playerid, name[0], MAX_PLAYER_NAME);
        GetPlayerName(id, name[1], MAX_PLAYER_NAME);
        Advertido[id]++;
        format(str, 128, "%s ha sido advertido (Razon: %s)(%i/3)", name[1], cmdtext[5+strlen(tmp[0])], Advertido[id]);
        SendClientMessage(playerid, COLOR_AZUL, str);
        format(str, 128, "Has sido advertido por %s. (Razon: %s.)(%i/3)", name[0], cmdtext[5+strlen(tmp[0])], Advertido[id]);
        SendClientMessage(id, COLOR_VERDE_CLARO, str);
        format(str, 128, "%s ha sido advertido por %s. (Razon: %s.) (%i/3)", name[1], name[0], cmdtext[5+strlen(tmp[0])], Advertido[id]);
        SendClientMessageToAll(COLOR_NARANJA, str);
        PlayerPlaySound(playerid, 1057, 0.0, 0.0, 0.0);
        PlayerPlaySound(id, 1057, 0.0, 0.0, 0.0);
        if(Advertido[id] >= 3)Kick(id);
        return 1;
        }
        return SendClientMessage(playerid, COLOR_ROJO, "El jugador no se encuentra conectado.");
}

//la definiciуn de Strtok
strtok(const string[], &index)
{
    new length = strlen(string);
    while ((index < length) && (string[index] <= ' '))
    {
        index++;
    }

    new offset = index;
    new result[20];
    while ((index < length) && (string[index] > ' ') && ((index - offset) < (sizeof(result) - 1)))
    {
        result[index - offset] = string[index];
        index++;
    }
    result[index - offset] = EOS;
    return result;
}
Ya ustedes usan los colores que quieran xD

Saludos n_n'!
Reply
#31

Eliminar la ultima coma ->

PHP Code:
stock FoundCharacter(str[], character[])
{
    for(new 
strlen(str); 0i--)
    {
          if(
strfind(strcharacterfalsei) != -1)
          {
            return 
i;
        }
    }
    return -
1;

////
Ejemplo

PHP Code:
new
    
str[64];
    
new 
Frutas[] = {
    
"Manzana",
    
"Pera",
    
"Banana",
    
"Uvas",
    
"Fresas"
};
for(new 
isizeof(Frutas); i++)
{
    
format(strsizeof str,"%s%s,"strFrutas[i]);
}
/* Print -> Manzana,Pera,Banana,Uvas,Fresas,
    Se pretende eliminar la ultma coma. */
    
new
    
pos FoundCharacter(str","); // Ahora que tenemos la posicion de la ultima coma.
    
strdel(strpossizeof(str));
// Print -> Manzana,Pera,Banana,Uvas,Fresas 
///////////////////////////////////////

PHP Code:
stock RGBAtoARGB(source)
{
    return
        ((
source 0xFF000000) >> 24) |     // Transparencia [A]
        
((source 0x00FF0000) >>  8) |     // Rojo          [R]
        
((source 0x0000FF00) <<  8) |     // Verde         [G]
        
((source 0x000000FF) << 24);      // Azul          [B]

Aquн una funciуn que me sirve mucho, cambia el formato de RGBA a ARGB

PHP Code:
main()
{
    
printf("%x %x"0x66EEAEAARGBAtoARGB(0x66EEAEAA));

Un uso muy ъtil viene en https://sampwiki.blast.hk/wiki/SetObjectMaterial que para el color del objeto se debe de usar ARGB y la mayorнa siempre se usa RGBA.

---

Hay una mбs simple que acabo de encontrar al buscar si ya existнa una funciуn para tal en el foro.

PHP Code:
stock RGBAToARGBrgba )
    return 
rgba >>> rgba << 24
http://forum.sa-mp.com/showpost.php?...31&postcount=5
Reply
#32

No si esta funciуn ya la postearon en los anteriores mensajes de este post, pero esta funciуn es buena para los servidores roleplay, siempre pedirб la inicial en mayъscula. Quien la creo lo desconozco un amigo que esta usando el gamemode scrp me lo paso me dijo que es bueno y quisiera agradecer a quien creo la funciуn.

Si saben de quien es dнganme!

Code:
stock NombreValido(const name[])
{
	if(!name[0] || strfind(name, "_") == -1)
		return 0;
	else for(new i = 0, len = strlen(name); i != len; i ++)
	{
	    if((i == 0) && (name[i] < 'A' || name[i] > 'Z'))
			return 0;
		else if((i != 0 && i < len  && name[i] == '_') && (name[i + 1] < 'A' || name[i + 1] > 'Z'))
			return 0;
		else if ((name[i] < 'A' || name[i] > 'Z') && (name[i] < 'a' || name[i] > 'z') && name[i] != '_' && name[i] != '.')
			return 0;
	}
	return 1;
}
Reply
#33

Quote:
Originally Posted by wharlos
View Post
No si esta funciуn ya la postearon en los anteriores mensajes de este post, pero esta funciуn es buena para los servidores roleplay, siempre pedirб la inicial en mayъscula. Quien la creo lo desconozco un amigo que esta usando el gamemode scrp me lo paso me dijo que es bueno y quisiera agradecer a quien creo la funciуn.

Si saben de quien es dнganme!

Code:
stock NombreValido(const name[])
{
	if(!name[0] || strfind(name, "_") == -1)
		return 0;
	else for(new i = 0, len = strlen(name); i != len; i ++)
	{
	    if((i == 0) && (name[i] < 'A' || name[i] > 'Z'))
			return 0;
		else if((i != 0 && i < len  && name[i] == '_') && (name[i + 1] < 'A' || name[i + 1] > 'Z'))
			return 0;
		else if ((name[i] < 'A' || name[i] > 'Z') && (name[i] < 'a' || name[i] > 'z') && name[i] != '_' && name[i] != '.')
			return 0;
	}
	return 1;
}
Code:
// ** INCLUDES

#include <a_samp>

// ** DEFINES

// *** ROLEPLAY NAME TYPES

#define ROLEPLAY_NAME_FALSE 0
#define ROLEPLAY_NAME_TRUE 1
#define ROLEPLAY_NAME_UNCAPPED 2
#define ROLEPLAY_NAME_CONTAINS_NUMBERS 3

// ** MAIN

main()
{
	print("Loaded \"rp_name_detector.amx\".");

	switch(IsRoleplayName("Test_Test"))
	{
		case ROLEPLAY_NAME_FALSE:
		{
			print("Name is not a roleplay name.");
		}
		case ROLEPLAY_NAME_TRUE:
		{
			print("Name is a roleplay name.");
		}
		case ROLEPLAY_NAME_UNCAPPED:
		{
			print("Name is uncapped.");
		}
		case ROLEPLAY_NAME_CONTAINS_NUMBERS:
		{
			print("Name can't contain numbers.");
		}
	}
}

// ** CALLBACKS

public OnGameModeInit()
{	
	return 1;
}

public OnGameModeExit()
{
	return 1;
}

// ** FUNCTIONS

stock IsRoleplayName(player_name[])
{
	for(new i = 0, j = strlen(player_name); i < j; i ++)
	{
		switch(player_name[i])
		{
			case '0'..'9':
			{
				return ROLEPLAY_NAME_CONTAINS_NUMBERS;
			}
		}
	}

	if(65 <= player_name[0] <= 90)
	{
		new underscore_1 = strfind(player_name, "_");
		if(underscore_1 >= 3)
		{
			if(65 <= player_name[underscore_1 + 1] <= 90)
			{
				if(strfind(player_name, "_", false, (underscore_1 + 1)) == -1)
				{
					if(((strlen(player_name) - underscore_1) - 1) >= 3)
					{
						return ROLEPLAY_NAME_TRUE;
					}
				}
			}
			else
			{
				if(((strlen(player_name) - underscore_1) - 1) <= 2)
				{
					return ROLEPLAY_NAME_FALSE;
				}
				else
				{
					return ROLEPLAY_NAME_UNCAPPED;
				}
			}
		}
	}
	else
	{
		if(strfind(player_name, "_") <= 3)
		{
			return ROLEPLAY_NAME_FALSE;
		}
		else
		{
			return ROLEPLAY_NAME_UNCAPPED;
		}
	}
	return ROLEPLAY_NAME_FALSE;
}
Reply
#34

Gerar palabra aleatoria
PHP Code:
#define MAX_WORDS                       15

stock GenerateRandomWord(){
    new
        
iKey[MAX_WORDS]
    ;

    for(new 
i!= MAX_WORDS; ++i){
        
iKey[i] = (random('Z'-'A')+'A' random('x'-'a')+'a');
    }
    
    return 
iKey;

Reply
#35

PHP Code:
stock ValidateRoleplayName(playerid)
{
    new
        
name[MAX_PLAYER_NAME]
    ;
    
GetPlayerName(playeridnamesizeof(name));
    
    new
        
new_name[MAX_PLAYER_NAME];
    
    
format(new_namesizeof(new_name), ConvertNameToRoleplay(name));
    
    if(
isnull(new_name))
    {
        return -
1;
    }
    else
    {
        new 
tempName[MAX_PLAYER_NAME];
        
format(tempNamesizeof(tempName), "player_%i"playerid);
        
SetPlayerName(playeridtempName);
        
        
SetPlayerName(playeridnew_name);
    }
    return 
1;
}
stock ConvertNameToRoleplay(name[])
{
    new
        
pos strfind(name"_"true),
        
new_name[MAX_PLAYER_NAME]
    ;
    
    if(
pos == -1)
    {
        
// his name not is roleplay
        
return new_name;
    }
    new
        
firstChar GetASCIIDec(name),
        
firstCharID 0,
        
changeFirstChar = -1,
        
changeSecondChar = -1
    
;
        
    if(!
charIsLetter(firstChar))
    {
        
// his name not is roleplay
        
return new_name;
    }
    else{
        if(
charIsLetterLowercase(firstChar))
        {
            
// Su inicial es minuscula
            
changeFirstChar firstChar;
        }
    }
    new 
secondCharID pos+1;
    
    if(
name[secondCharID] == '\0')
    {
        
// his name not is roleplay
        
return new_name;
    }
    else{
        new 
secoundChar GetASCIIDec(name[secondCharID]);
        if(!
charIsLetter(secoundChar))
        {
            
// his name not is roleplay
            
return new_name;
        }
        else
        {
            if(
charIsLetterLowercase(secoundChar))
            {
                
changeSecondChar secoundChar;
            }
        }
    }
    
format(new_namesizeof(new_name), name);
    if(
changeFirstChar != -1)
        
new_name[firstCharID] = GetMayusASCII(changeFirstChar);
    if(
changeSecondChar != -1)
        
new_name[secondCharID] = GetMayusASCII(changeSecondChar);
    return 
new_name;
}
stock GetMayusASCII(charid)
{
    if(!
charIsLetterLowercase(charid))
        return 
charid;
        
    return 
charid-32;
}
stock GetASCIIDec(str[])
{
    new
        
s[4]
    ;
    
format(ssizeof(s), "%c"str);
    
format(ssizeof(s), "%i"s);
    return 
strval(s);
}
stock charIsLetter(decimal)
    return 
decimal >= 65 && decimal <= 90 || decimal >= 97 && decimal <= 122;
stock charIsLetterLowercase(decimal)
    return 
decimal >= 97 && decimal <= 122
Ejemplo de uso:

PHP Code:
public OnPlayerConnect(playerid)
{
    if(
ValidateRoleplayName(playerid) == -1)
    {
        
// Nombre no es Ropleay
        
Kick(playerid);
    }
    
// No es necesario un else, pues si es valido pero no cumple con las mayusculas lo va a kickear nada mas.

Mбs bien es una mezcla de funciones, permite expulsar al jugador si su nombre no cumple con el formato Nombre_Apellido, y en caso de tener nombre_Apellido, Nombre_apellido a Nombre_Apellido, pronto le arreglarй mбs funciones a la funciуn xD la tenнa ahн y puede resultar interesante.
Reply
#36

Una funciуn que cambie el clima automбticamente cada cierto tiempo -> Supongamos que la usaremos dentro de un filterscript -

PHP Code:
enum weather_info
{
    
weather_id,
    
weather_text[39]
};
static 
WeatherIDS[][weather_info] =
{
    {
0,"Blue Sky"},
    {
1,"Blue Sky"},
    {
2,"Blue Sky"},
    {
3,"Blue Sky"},
    {
4,"Blue Sky"},
    {
5,"Blue Sky"},
    {
6,"Blue Sky"},
    {
7,"Blue Sky"},
    {
08,"Stormy"},
    {
09,"Cloudy and Foggy"},
    {
10,"Clear Blue Sky"},
    {
11,"Heatwave"},
    {
17,"Heatwave"},
    {
18,"Heatwave"},
    {
12,"Dull, Colourless"},
    {
13,"Dull, Colourless"},
    {
14,"Dull, Colourless"},
    {
15,"Dull, Colourless"}, 
    {
16,"Dull, Cloudy, Rainy"},
    {
19,"Sandstorm"},
    {
20,"Foggy, Greenish"},
    {
21,"Very Dark, Gradiented Skyline, Purple"},
    {
22,"Very Dark, Gradiented Skyline, Purple"},
    {
23,"Pale Orange"},
    {
24,"Pale Orange"},
    {
25,"Pale Orange"},
    {
26,"Pale Orange"},
    {
27,"Fresh Blue"},
    {
28,"Fresh Blue"},
    {
29,"Fresh Blue"},
    {
30,"Dark, Cloudy, Teal"},
    {
31,"Dark, Cloudy, Teal"},
    {
32,"Dark, Cloudy, Teal"},
    {
33,"Dark, Cloudy, Brown"},
    {
34,"Blue/Purple, Regular"},
    {
35,"Dull Brown"},
    {
36,"Bright, Foggy, Orange"},
    {
37,"Bright, Foggy, Orange"},
    {
38,"Bright, Foggy, Orange"},
    {
39,"Very Bright"},
    {
40,"Blue/Purple, Cloudy"},
    {
41,"Blue/Purple, Cloudy"},
    {
42,"Blue/Purple, Cloudy"},
    {
43,"Toxic Clouds"},
    {
44,"Black/White Sky"},
    {
700,"Stormy with Pink Sky and Crystal Water"},
    {
150,"Darkest Weather Ever"}
}; 
Ahн declaramos todas las ids de los diferentes climas como static ya que se usarб en todo momento (global static)

PHP Code:
forward RandomWeather();
public 
RandomWeather()
{
    new 
rand random(sizeof(WeatherIDS));
    new 
message[51];
    
format(messagesizeof(message), "Weather changed to %s"WeatherIDS[rand][weather_text]);
    
SetWeather(WeatherIDS[rand][weather_id]);
    
SendClientMessageToAll(-1,message);
    print(
message);

Luego creamos la funciуn del temporizador (timer) la cual cambiarб automбticamente los climas y se enviarб un mensaje en el chat del jugador y en la consola indicando que el clima ha cambiado

PHP Code:
public OnFilterScriptInit()
{
    
SetTimer("RandomWeather"3600 10001);

Luego cuando el filterscript cargue correctamente se aplicara el timer que se repetirб cada X cantidad de tiempo (en el ejemplo de arriba serian 3 horas) y se verнa de esta forma dentro del servidor

Reply
#37

IsFreePath: verifica si el recorrido hasta cierta distancia estб libre (mediante las coordenadas y el бngulo especificado). Retorna 1 si el camino estб libre, caso contrario retorna 0.
Code:
stock IsFreePath(Float:fX, Float:fY, Float:fZ, const Float:angle, const Float:max_dist, const Float:z_dif = 1.5)
{
    new Float:i, Float:Z, Float:sin = floatsin(-angle, degrees), Float:cos = floatcos(-angle, degrees);
    for(i = 0.0; i < max_dist; i += 0.25)
    {
        MapAndreas_FindZ_For2DCoord(fX + (i * sin), fY + (i * cos), Z);
        if(Z - fZ < z_dif) continue;
        return 0;
    }
    return 1;
}
GetFreePath: es como la funciуn anterior, pero йsta buscarб un camino que estй libre.
Code:
stock GetFreePath(Float:fX, Float:fY, Float:fZ, Float:angle, const Float:z_dif = 2.0)
{
    new Float:i, Float:Z;
    for(i = angle; i < 360.0; i += 30.0)
    {
        MapAndreas_FindZ_For2DCoord(fX + (5.0 * floatsin(-i, degrees)), fY + (5.0 * floatcos(-i, degrees)), Z);

        if(Z - fZ < z_dif)
        {
            fX += 5.0 * floatsin(-i, degrees);
            fY += 5.0 * floatcos(-i, degrees);
            fZ = Z + 0.9;
            return 1;
        }
    }

    for(new Float:i = 0.0; i < angle; i += 30.0)
    {
        MapAndreas_FindZ_For2DCoord(fX + (5.0 * floatsin(-i, degrees)), fY + (5.0 * floatcos(-i, degrees)), Z);

        if(Z - fZ < z_dif)
        {
            fX += 5.0 * floatsin(-i, degrees);
            fY += 5.0 * floatcos(-i, degrees);
            fZ = Z + 0.9;
            return 1;
        }
    }
    return 0;
}
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)