how to
#1

how to select a random player from all connected players?
Reply
#2

This should work (untested):

pawn Код:
stock GetRandomPlayer()
{
    //Get number of conneted players first
    new players = 0;
    for(new i = 0; i < GetMaxPlayers(); i++)
    {
        if(IsPlayerConnected(i)) players ++;
    }
    //now select a random number from 0 to players
    //note that this is NOT the playerid yet
    players = random(players) + 1;
    //Loop through connected players again, until you reach the "players"th player
    for(new i = 0; i < GetMaxPlayers(); i ++)
    {
        if(IsPlayerConnected(i))
        {
            players --;                //single-variable pwnage ;)
            if(players == 0) return i;
        }
    }
    return 0;
}
Reply
#3

Another way

pawn Код:
stock GetRandomPlayer()
{
    new ConnectedPlayers[MAX_PLAYERS];
    new idx;
    for(new i=0; i < MAX_PLAYERS; i++)
    {
        if(IsPlayerConnected(i))
        {
            ConnectedPlayers[idx] = i;
            idx++;
        }
    }
    return ConnectedPlayers[random(idx)];
}
Reply
#4

thx !!!

what i have 2 do in the command??
Reply
#5

What do you mean?
Add one of the function to your script (MadeMan's is slightly faster, mine uses slightly less ram) and use it.
Reply
#6

yea but where i add? like
dcmd_command(playerid,params[])
{
GetRandomPlayer()
}
?? and how to send like a message to a random player selected?
Reply
#7

Use this

new string[128];
format(string,sizeof(string),"I have picked a random player and it is id %d",GetRandomPlayer());
SendClientMessage(playerid,COLOR_RED,string);
printf("%s",string);
Reply
#8

thx you...
Reply
#9

btw... if you want to use the id of this player in the command for more than this line add:
new randomid = GetRandomPlayer();

and use "randomid" whenever you have to add the player's id
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)