Portal SAMP
Fixado: Códigos Úteis - Versão de Impressão

+- Portal SAMP (https://portalsamp.com)
+-- Fórum: SA-MP (https://portalsamp.com/forumdisplay.php?fid=5)
+--- Fórum: Área de suporte (https://portalsamp.com/forumdisplay.php?fid=6)
+--- Tópico: Fixado: Códigos Úteis (/showthread.php?tid=73)

Páginas: 1 2 3 4 5


RE: Códigos Úteis - White_Blue - 12/05/2022

Script para detecção de players com IP estrangeiro( ANTI-VPN )
Lembrando que só funcionará caso a gamemode estiver conectada em uma host.

Código:

Código PHP:
// Topo do script
#define MAX_COUNTRY_NAME 64

public OnPlayerConnect(playerid) {
    if(strcmp("127.0.0.1"GetPlayerIPEx(playerid), true) != 0) {
    
format(STRX128"ip-api.com/json/%s"GetPlayerIPEx(playerid));
    
HTTP(playeridHTTP_GETSTRX"""HTTP_Connect");
    }
    return 1;
}

forward HTTP_Connect(playeridresponse_codecdata[]);
public 
HTTP_Connect(playeridresponse_codecdata[]) {
    if(
response_codec != 200) {
        
SetPVarString(playerid"Pais""Desconhecido"), SetPVarString(playerid"Estado""Desconhecido"), SetPVarString(playerid"Cidade""Desconhecida");
        return 
1;
    }

       new string[128], pos;
       if(strfind(data"Reserved"true) == -&& strlen(data) >= 15) {
        if((
pos strfind(data"\"country\":")) != -1)
        {
        
    pos += 11;
            
strmid(stringdataposstrfind(data"\""truepos));
            
SetPVarString(playerid"Pais"string);
        }
        if((
pos strfind(data"\"regionName\":")) != -1)
        {
            pos += 14;
            
strmid(stringdataposstrfind(data"\""truepos));
            
SetPVarString(playerid"Estado"string);
        }
        if((
pos strfind(data"\"city\":")) != -1)
        {
        
    pos += 8;
            
strmid(stringdataposstrfind(data"\""truepos));
            
SetPVarString(playerid"Cidade"string);
        }
    }

    
GetPVarString(playerid"Pais"stringMAX_COUNTRY_NAME);
    if(
strfind(string"Brazil"true) == -&& strfind(string"Portugal"true) == -&& strfind(string"France"true) == -&&  strfind(string"Desconhecido"true) == -1)
    {
    
        SendClientMessage(playerid0xFF0000AA"A entrada de seu IP não é permitida.");
             
Kick(playerid);
    }
    return 
0;
}

stock GetPlayerCountry(playerid)
{
    new 
string[MAX_COUNTRY_NAME];
    
GetPVarString(playerid"Pais"stringMAX_COUNTRY_NAME);
    return 
string;
}

stock GetPlayerRegion(playerid)
{
    new 
string[MAX_COUNTRY_NAME];
    
GetPVarString(playerid"Estado"stringMAX_COUNTRY_NAME);
    return 
string;
}
stock GetPlayerCity(playerid)
{
    new 
string[MAX_COUNTRY_NAME];
        GetPVarString(playerid"Cidade"stringMAX_COUNTRY_NAME);
    return 
string;




RE: Códigos Úteis - Dr Editor - 13/07/2022

Função simples que retorna probabilidade. Retorna 1 para provável ou 0 para não.

Código:
stock GetProbability(chance)
{
    if(chance < 1)
        return false;
    else if(chance > 99)
        return true;
    
    chance /= 2;
    new valueCalc = 100;
    new valueRnd = random(valueCalc);
    new range1 = valueCalc / 2 - chance;
    new range2 = valueCalc / 2 + chance;
    return (valueRnd >= range1 && valueRnd <= range2);
}

Código teste:
Código:
new countYes, countNo;
for(new i = 0; i < 50; i ++)
{
    new res = GetProbability(10); // 1 - 99
    
    if(res) countYes ++;
    else countNo ++;
}
printf("Result: Yes = %i | No = %i", countYes, countNo);



RE: Códigos Úteis - Carlos Victor - 25/10/2022

Muitos gostariam de ativar as lojas no famoso shopping, como eu, a um tempo atrás não sabia como fazer isso, portanto, hoje deixo o código para remover os objetos e deixar aberto as lojinhas do shopping, ai vocês podem mapear do jeito de vocês.

Código PHP:
//OnPlayerConnect
RemoveBuildingForPlayer(playerid61301117.5859, -1490.007832.71880.25);
RemoveBuildingForPlayer(playerid62551117.5859, -1490.007832.71880.25);
RemoveBuildingForPlayer(playerid7621175.3594, -1420.187519.88280.25);

//OnGameModeInit
CreateObject(193221117.58594, -1490.0078132.718800.000000.000000.00000);
CreateObject(193231117.58594, -1490.0078132.718800.000000.000000.00000); 

Foto: [Imagem: sa-mp-12.jpg]


RE: Códigos Úteis - Carlos Victor - 28/10/2022

Uma função que deveria ser nativa, e todos deveriam usar para seus sistemas. Algo que adianta muito em nossas vidas.

Código:
stock GetXYFrontPlayer(playerid, &Float:x, &Float:y, Float:distance)
{
    new Float:a;
    GetPlayerPos(playerid, x, y, a);
    GetPlayerFacingAngle(playerid, a);

    if(GetPlayerVehicleID(playerid))
        GetVehicleZAngle(GetPlayerVehicleID(playerid), a);

    x += (distance * floatsin(-a, degrees));
    y += (distance * floatcos(-a, degrees));
}

stock GetXYBehindPlayer(playerid, &Float:x, &Float:y, Float:distance)
{
    new Float:a;
    GetPlayerPos(playerid, x, y, a);
    GetPlayerFacingAngle(playerid, a);

    if(GetPlayerVehicleID(playerid))
        GetVehicleZAngle(GetPlayerVehicleID(playerid), a);

    x -= (distance * floatsin(-a, degrees));
    y -= (distance * floatcos(-a, degrees));
}
Basicamente as funções acimas pegam a posição da frente e das costas de um jogador de acordo com a distância definida.

O moto de uso é bem simples.
Código:
new Float:x, Float:y, Float:z;
GetPlayerPos(playerid, x, y, z); //Pego a posição padrão do jogador.

GetXYFrontPlayer(playerid, x, y, 1); //Aqui as posições X e Y sofrem mudanças.
SetPlayerCheckpoint(playerid, x, y, z, 1); //Aqui eu seto a posição modificada.

[Imagem: unknown.png]

GetXYFrontPlayer    - Pega a posição frontal.
GetXYBehindPlayer   - Pega a posição de trás.


RE: Códigos Úteis - White_Blue - 02/01/2023

Código para retornar a distância entre dois players.

Código PHP:
stock GetDistanceBetweenPlayers(playeridplayerid2)
{
    new 
Float:x1Float:y1Float:z1Float:x2Float:y2Float:z2;
    new 
Float:tmpdis;
    
GetPlayerPos(playeridx1y1z1);
    
GetPlayerPos(playerid2x2y2z2);
    
tmpdis floatsqroot(floatpower(floatabs(floatsub(x2x1)), 2) +floatpower(floatabs(floatsub(y2y1)), 2)+floatpower(floatabs(floatsub(z2z1)), 2));
    return 
floatround(tmpdis);



Exemplo:
Código PHP:
CMD:checkd(playeridparams[]) {
       new plid
       if(sscanf(params"u"plid)) return SendClientMessage(playerid, -1"Use: /checkd [id]");
       if(GetDistanceBetweenPlayers(playeridplid) < 10) return SendClientMessage(playerid, -1"Você está próximo!");
       else return SendClientMessage(playerid, -1"Você está longe.");
       return 1;
}
     
stock GetDistanceBetweenPlayers
(playeridplayerid2)
{
    new Float:x1Float:y1Float:z1Float:x2Float:y2Float:z2;
    new Float:tmpdis;
    GetPlayerPos(playeridx1y1z1);
    GetPlayerPos(playerid2x2y2z2);
    tmpdis floatsqroot(floatpower(floatabs(floatsub(x2x1)), 2) +floatpower(floatabs(floatsub(y2y1)), 2)+floatpower(floatabs(floatsub(z2z1)), 2));
    return floatround(tmpdis);




RE: Códigos Úteis - Device-Black - 03/02/2023

(02/01/2023 00:53)White_Blue Escreveu: Código para retornar a distância entre dois players.

Código PHP:
stock GetDistanceBetweenPlayers(playeridplayerid2)
{
    new 
Float:x1Float:y1Float:z1Float:x2Float:y2Float:z2;
    new 
Float:tmpdis;
    
GetPlayerPos(playeridx1y1z1);
    
GetPlayerPos(playerid2x2y2z2);
    
tmpdis floatsqroot(floatpower(floatabs(floatsub(x2x1)), 2) +floatpower(floatabs(floatsub(y2y1)), 2)+floatpower(floatabs(floatsub(z2z1)), 2));
    return 
floatround(tmpdis);



Exemplo:
Código PHP:
CMD:checkd(playeridparams[]) {
       new plid
       if(sscanf(params"u"plid)) return SendClientMessage(playerid, -1"Use: /checkd [id]");
       if(GetDistanceBetweenPlayers(playeridplid) < 10) return SendClientMessage(playerid, -1"Você está próximo!");
       else return SendClientMessage(playerid, -1"Você está longe.");
       return 1;
}
     
stock GetDistanceBetweenPlayers
(playeridplayerid2)
{
    new Float:x1Float:y1Float:z1Float:x2Float:y2Float:z2;
    new Float:tmpdis;
    GetPlayerPos(playeridx1y1z1);
    GetPlayerPos(playerid2x2y2z2);
    tmpdis floatsqroot(floatpower(floatabs(floatsub(x2x1)), 2) +floatpower(floatabs(floatsub(y2y1)), 2)+floatpower(floatabs(floatsub(z2z1)), 2));
    return floatround(tmpdis);


Este código é inútil, pois pode ser feito facilmente de uma maneira simples como essa:
Código PHP:
stock Float:GetDistanceBetweenPlayers(playeridtargetid)
{
 static Float:xFloat:yFloat:z;
 GetPlayerPos(targetidxyz);

 // funcao nativa encontrada em: a_players.inc
 return GetPlayerDistanceFromPoint(playeridxyz);


Funciona da mesma forma, porém o seu codigo ocupa mais espaço tanto visual quanto em memoria
Eu mesmo não gosto de ficar ocupando linha desnecessáriamente... Da uma agonia da peste


RE: Códigos Úteis - DM110 - 02/03/2023

ativar função camaleao no veiculo. divirta-se

Código PHP:
CMD:camaleao(playerid)
{
    if( !IsPlayerInAnyVehicle(playerid) )
        return SendClientMessage(playerid, -1"Voce precisa esta em um veiculo!");

    SetTimerEx("MudarCor"1000false"i"playerid);
    ChangeVehicleColor(GetPlayerVehicleID(playerid), random(128), random(128));
    return 1;
}
forward MudarCor(playerid);
public 
MudarCor(playerid)
{
    if( !IsPlayerInAnyVehicle(playerid) )
    {
        return 1;
    
    ChangeVehicleColor(GetPlayerVehicleID(playerid), random(128), random(128));
    SetTimerEx("MudarCor"1000false"i"playerid);
    return 1;




RE: Códigos Úteis - Device-Black - 04/09/2023

Alguns mods e apks possuem o auto-reconnect, malfeito faz com que haja um flood de conexão, emitindo uma mensagem no log por atingir o limite do tempo de conexão.. uma não, varias!

Esse código bloqueia o IP do jogador que desconectou
Mantem bloqueado por 30 segundos, evitando sua reconexao instantânea e a irritante mensagem no log.
Código PHP:
#define IP_MAX_LEN    (16)
#define BLOCK_TIME    (30)

new pAddr[MAX_PLAYERS][IP_MAX_LEN];

public 
OnIncomingConnection(playeridip_address[], port) {
    
pAddr[playerid][0] = EOS;
    
strcat(pAddr[playerid], ip_addressIP_MAX_LEN);
    return 
1;
}

public 
OnPlayerDisconnect(playeridreason) {
    
BlockIpAddress(pAddr[playerid], (BLOCK_TIME 1000));
    return 
1;




RE: Códigos Úteis - zBreno - 05/09/2023

da crash no deamx na versão executável feito pelo daniel cortez do fórum pro pawn russo eu testei e funciona porem existe outra versão do de amx feita em lua https://github.com/AmyrAhmady/DeAMX nessa eu já não dizer se funciona

@___If_u_can_read_this_u_r_nerd(); // 10 different ways to crash DeAMX
@___If_u_can_read_this_u_r_nerd() // and also a nice tag for exported functions table in the AMX file
{ // by Daniel_Cortez \\ pro-pawn.ru
#emit stack 0x7FFFFFFF // wtf (1) (stack over... overf*ck!?)
#emit inc.s cellmax // wtf (2) (this one should probably make DeAMX allocate all available memory and lag forever)
static const ___[][] = {"pro-pawn", ".ru"}; // pretty old anti-deamx trick
#emit retn
#emit load.s.pri ___ // wtf (3) (opcode outside of function?)
#emit proc // wtf (4) (if DeAMX hasn't crashed already, it would think it is a new function)
#emit proc // wtf (5) (a function inside of another function!?)
#emit fill cellmax // wtf (6) (fill random memory block with 0xFFFFFFFF)
#emit proc
#emit stack 1 // wtf (7) (compiler usually allocates 4 bytes or 4*N for arrays of N elements)
#emit stor.alt ___ // wtf (8) (...)
#emit strb.i 2 // wtf (9)
#emit switch 0
#emit retn // wtf (10) (no "casetbl" opcodes before retn - invalid switch statement?)
L1:
#emit jump L1 // avoid compiler crash from "#emit switch"
#emit zero cellmin // wtf (11) (nonexistent address)
}

feito pelo bruno ips team procura por chaves abertas no seu código salve isso como html cole o código e mande procurar

<script>
function checkIt(str) {
var arrBracket = new Array();
var arrLineBkt = new Array();
var opens = 0;
var lines = 0;
for(i = 0, j = str.length; i != j; i++) {
if(str[i] == '{') {
arrBracket[opens] = 1;
arrLineBkt[opens] = lines;
opens++;
}
if(str[i] == '}') {
arrBracket[opens] = 0;
if(!opens) {
return alert("ERROR EXCESSIVE '}' on line " + lines);
}
opens--;
}
if(str[i] == '\n') lines ++;
}
if(!opens) {
alert('NO ERROR !!1 YOU IS BEST !!');
}
for(i = 0; i != opens; i++) {
if(arrBracket[i]) {
alert("ERROR '{' on line" + arrLineBkt[i]);
}
}

return true;
}
</script>
<textarea id=area>Put code here</textarea>
<input type=button onClick=checkIt(document.getElementById('area').value) value=Hey />


Random ex - zHypezinXzL - 12/10/2023

Hoje venho trazer uma extensão para a função nativa random, que nos permite manusear com mais opções e não estou dizendo daquela função simples:

Código PHP:
randomex (
    const val_min,
    const val_max
) {
    return ((val_min random (val_min val_max)) + 1);



Não há nenhum problema ao usar a função acima, mas a que venho trazer nos permite manusear com mais operações e correções 


  1. Primeiro vamos entender como funciona a função random, está função não tem nenhuma operação difícil, mas possui seus problemas, um deles é o seu retorno meio estranho, vou lhe mostrar: random (3); ok até aqui normal mas agora vamos analisar os resultados (0, 1, 2), ué cadê o 3? Bem o 3 é a quantia totalizará de números que ele irá retornar como vocês podem ver ele retorna do 0 ao 2 totalizando 3 números. Outro problema é que ele não trabalha com números negativos, caso queira testar verá que ele irá retornar números positivos e meio descontrolados isso provavelmente deve ser um problema nos bits. Isso é tudo que precisamos saber sobre o random.
  2. Então vamos ao assunto principal, oque a randomex oferece? Ela nos oferece uma manipulação extra que pode fazer coisas que a random não faz como poder escolher a partida dos números há serem retornados N° a N° um exemplo: randomex (2, 5) a sequência que ele irá retornar será (2, 3, 4, 5) diferente da random que só retorna de 0 a N°. Outro oferecimento é a manipulação de números negativos vamos a um exemplo: randomex (0, -2); os valores que serão retornados serão (0, -1, -2). E os últimos oferecimentos é que não é necessário colocar os 2 parâmetros e não é necessário que o "val_min" seja menor que o "val_max" pois a função faz essas verificação e corrige esse problema. Exemplos do uso de somente 1 parâmetro: randomex (3); -> (0, 1, 2, 3) ou randomex (-3); -> (0, -1, -2, -3).

Código PHP:
// Author      :  zHypezinXzL
// My Github   :  https://github.com/zHypezinXzL/

randomex (
    const val_min,
    const val_max 0
) {
    if (val_max == val_min)
        return val_min;
    else
        if (val_min >= && val_max >= 0)
            if (val_max >= val_min)
                return val_min random ((val_max val_min) + 1);
            else
                return val_max random ((val_min val_max) + 1);
        else if (val_min <= && val_max <= 0)
            if (-val_max >= -val_min)
                return -(-val_min random (-(val_max val_min) + 1));
            else
                return -(-val_max random (-(val_min val_max) + 1));
        else
            if (val_max >= val_min)
                return (val_min random ((val_max val_min) + 1));
            else
                return (val_max random ((val_min val_max) + 1));


Recomendo substituir as random nativas por essa randomex, pois a randomex tem suas correções, mas cuidado para não substituir as randons que estão dentro desta função.

Espero que tenham gostado deste "mini tutorial" sobre random e desta função que trago a vocês ;)