random ID
#1

hi there, I need ur help:
Im trying to get random other player id, if he is connected, not npc and not himself
pawn Код:
for(new j = 0;j < MAX_PLAYERS; j++)
{
    i = random(MAX_PLAYERS);
    if(IsPlayerConnected(i) && i!=playerid && !IsPlayerNPC(i)) break;
}
after that i check id and its, for example, 263 even player limit is 100

I've tried with while loop, but then server stops(get crashed).
SO, any help?
Reply
#2

pawn Код:
new playercount=0;
OnPlayerConnect(playerid)
{
    playercount++;
}
OnPlayerDisconnect(playerid, reason)
{
    playercount--;
}
pawn Код:
new rand = random(playercount);
if(IsPlayerConnected(rand) && rand !=playerid && !IsPlayerNPC(rand))
{
    //Lets do somethin here...
    new str[15];
    format(str,sizeof(str), "Rand ID %d", rand)
    SendClientMessage(playerid, -1, str);
}
Reply
#3

you do a loop 500 times with the j variable, but the i=random could leave out some playerids, or pick a wrong player 500 times - this will fail (some/most times, depending on the player/bot/emptyslots/MAX_PLAYERS relations).
the better way is to "collect" all valid players (not yourself, not a bot, and indeed only connected players):
pawn Код:
new foundIDs;//0 atm, will get raised up at each valid player, and then being used as pointer into a cell of the IDs[] array...
new IDs[MAX_PLAYERS];//temp array for filling with valid players...
for(new j = 0;j < MAX_PLAYERS; j++)//your loop is ok
{
    if(IsPlayerConnected(j) && j!=playerid && !IsPlayerNPC(j))
    {
        IDs[foundIDs]=j;//the pointer foundIDs (raising 1 by 1) tells into which cell the IDs[] gets filled up with j-playerids
        foundIDs++;//to fill up IDs[0], then [1] etc - the foundIDs is used as pointer the IDs[].
    }
}
return IDs[random(foundIDs)];//finally, chose a random value of the IDs[]
Reply
#4

MAX_PLAYERS is not your server player limit, it's just a constant.

Replace MAX_PLAYERS with GetMaxPlayers(), this will return your server.cfg value for max_players.

https://sampwiki.blast.hk/wiki/GetMaxPlayers
Reply
#5

why I didn't thought about that?.... Anyway, THX
Reply
#6

pawn Код:
#include <a_samp>

stock PickPlayer()
{
    new target;
    target = random(GetMaxPlayers());
    if(!IsPlayerConnected(target) || IsPlayerNPC(target)) PickPlayer();
    return target;
}
Easy one.
Reply
#7

@[MG]Dimi: your code causes endless recursions when no players/only npcs are connected.
Reply
#8

Just use foreach. Then simply use this code:
pawn Код:
Iter_Random(Player);
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)