Quote:
Originally Posted by thesamuraivega
Hi,
My Random Selection my way to select 1 players from online players and send to terrorist state.
Code:
public static void RandomSelect()
{
List<Client.GameState> players = new List<Client.GameState>();
foreach (Client.GameState p in ServerBase.Kernel.Clients.Values)
players.Add(p);
Random rand = new Random();
Client.GameState pOne;
int selectedIndex = rand.Next(players.[COLOR="Red"]Length[/COLOR]);
pOne = players[selectedIndex];
players.RemoveAt(selectedIndex);//this way we can never select same char twice
pOne.Entity.AddFlag(Network.GamePackets.Update.Flags.Flashy);
pOne.Entity.KillTheTerrorist_IsTerrorist = true;
Conquer_Online_Server.Network.PacketHandler.WorldMessage("Ahora " + pOne.Entity.Name + " Es el terrorista!!!");
}
int selectedIndex = rand.Next(players. Length);´
why?
|
That selects a random index for your selection.
Think of it like this... I have a deck of cards so I take a random number between 0 and the number of cards in the deck. I then take the Xth card in the deck.
That's what the code is doing exactly. I use an index based method and save the index simply because it makes pulling that user from the collection and then REMOVING him from the collection easier.
This is not needed if you're only taking 1 person though as you'd never be able to select the same person twice. This more has to do with taking multiple entries from small collections.
Lets say I have 4 players on a map and I need to at random pick two of them to fight.
There's a 1/4 chance for each person to be picked... but after I pick someone there's still a 1/4 chance of picking them AGAIN if I don't remove them from the possibilities.... which I do in the example I posted via RemoveAt
<edit>
oops sorry I was thinking you were asking the theory behind the code... not just why it was an 'error' (nothing in the code I posted is intended for use. It's an example rofl!)