random ID -
marrcko - 04.01.2012
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?
Re: random ID -
[ABK]Antonio - 04.01.2012
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);
}
Re: random ID -
Babul - 04.01.2012
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[]
Re: random ID -
Joe_ - 04.01.2012
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
Re: random ID -
marrcko - 04.01.2012
why I didn't thought about that?.... Anyway, THX
Re: random ID -
[MG]Dimi - 04.01.2012
pawn Код:
#include <a_samp>
stock PickPlayer()
{
new target;
target = random(GetMaxPlayers());
if(!IsPlayerConnected(target) || IsPlayerNPC(target)) PickPlayer();
return target;
}
Easy one.
Re: random ID -
Babul - 04.01.2012
@[MG]Dimi: your code causes endless recursions when no players/only npcs are connected.
Re: random ID -
RyDeR` - 04.01.2012
Just use
foreach. Then simply use this code: