Random player!
#1

Hello SA-MP Forums.

Today I have been making a new script and now I need to find out how can I choose someone randomly?

So like, there is 10 players online and function "FirstInfected" starts, it has to choose 1 random player and change he's team to SetPlayerTeam(playerid, 1);

Thank you allready!
Reply
#2

pawn Код:
// Anywhere in your script (i just copied this from another topic right now)
GetPlayersOnServer() {
    new count;
    for(new x=0; x< MAX_PLAYERS; x++) { //x = MAX_PLAYERS
      if(IsPlayerConnected(x))) {
            count++;
        }
    }
    return count;
}

// Then do;
new randomid = random(GetPlayersOnServer());
Reply
#3

Okey another question:

forward FirstInfected();
public FirstInfected(playerid)
{
new randomid = random(GetPlayersOnServer());
GetPlayersOnServer()
{
new count;
for(new x=0; x< MAX_PLAYERS; x++)
{
if(IsPlayerConnected(x)))
{
count++;
}
}
return count;
}


Whats wrong?
Reply
#4

Mike_Garber, your function might be buggy. Why? For example you have 10 players in your server with id's 0, 1, 3, 5, 6, 9, 10, 12, 13, 14. Random function might pick Non existing ID, for example 4.
Foreach include has an function with what you can pick random player with no bugs( search for it )
Reply
#5

pawn Код:
stock FirstInfected()
{
    new array[MAX_PLAYERS],count; // replace MAX_PLAYERS to Your server slots
    for(new x=0; x < MAX_PLAYERS; x++) { // up
        if(IsPlayerConnected(x) && !IsPlayerInfected(x)) { // replace 'IsPlayerInfected' to Your own array / function
            array[count] = x;
            count++;
        }
    }
    return array[random(count)];
}

// Then do:
new randomid = FirstInfected();
Reply
#6

Quote:
Originally Posted by armyoftwo
Посмотреть сообщение
Mike_Garber, your function might be buggy. Why? For example you have 10 players in your server with id's 0, 1, 3, 5, 6, 9, 10, 12, 13, 14. Random function might pick Non existing ID, for example 4.
Foreach include has an function with what you can pick random player with no bugs( search for it )
It's not my function, but yeah I guess... And i know about foreach but he might not have it... But
my code can easily be rewritten to not pick an invalid ID.
pawn Код:
GetPlayersOnServer() {
    new count;
    for(new x=0; x< MAX_PLAYERS; x++) { //x = MAX_PLAYERS
      if(IsPlayerConnected(x))) {
            count++;
        }
    }
    return count;
}

// Then do;
randomplayer()
{
    new randomid = random(GetPlayersOnServer());
    if(!IsPlayerConnected(randomid)){ return randomplayer(); }
    return randomid;
}

//And now you can do a function like;
infectplayer(randomplayer);
This should work.
Reply
#7

Sorry but it didnt...

Stand.pwn(955) : error 029: invalid expression, assumed zero

if(IsPlayerConnected(x))) { is the error line

I guess you meant if(IsPlayerConnected(x)) ?
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)