Random Players

Discussion in 'Plugin Development' started by dragon53170, Aug 25, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    dragon53170

    I am making a plugin for a team game where the teams are picked using captains. You can either have the captains set manually or random. I know how to do the manual part, it's the random part I don't know how to do. I think it would have something to do with looping through all the players and then getting the random ones but, as I said I don't know how to do that. Any help would be appreciated.
     
  2. Offline

    St3venAU

    This would pick a random player from all online players.
    Code:java
    1. Random random = new Random();
    2. int numPlayers = getServer().getOnlinePlayers().length;
    3. int randomNumber = random.nextInt(numPlayers);
    4. Player randomPlayer = getServer().getOnlinePlayers()[randomNumber];


    Edit: if you are picking multiple players you will want to add a check in the code to make sure you havn't picked the same player twice.
     
  3. Offline

    Dragonphase

    St3venAU

    That's okay, but you really should be coding against Bukkit for this, not CraftBukkit; getOnlinePlayers() using Bukkit returns a Collection, whereas building against CraftBukkit returns an array.
     
  4. Offline

    marwzoor

    CraftBukkit classes are just classes implementing Bukkit interfaces. Meaning most Bukkit classes are just interfaces for CraftBukkit classes.

    The old getOnlinePlayers() returned an array, this is why he gets an array and not a Collection. Guessing he has been using the 1.7.9 version of Bukkit.
     
    St3venAU likes this.
  5. Offline

    St3venAU

  6. Offline

    marwzoor

    :)

    Here's another suggestion of how to do it. With the latest API :)

    Code:java
    1.  
    2. Collection<Player> players = Bukkit.getOnlinePlayers();
    3.  
    4. Random rand = new Random();
    5.  
    6. Player captain1 = players.get(rand.nextInt(players.size()));
    7.  
    8. //Remove the player from the list/collection. He can't be selected again.
    9. players.remove(captain1);
    10.  
    11. Player captain2 = players.get(rand.nextInt(players.size()));
    12.  
    13. players.remove(captain2);
    14.  
     
    St3venAU likes this.
Thread Status:
Not open for further replies.

Share This Page