How Can I Effect Random Online Players?

Hi there, I’m trying to make a plugin to practice/learn java. The plugin I’m making has a random teleport command that can be run from the console or by a player. I’m trying to figure out if there is a way to effect a random player on the server with this command.

I thought I could just replace the player name given to the command executor with the @r that vanilla uses to effect random players. Obviously it didn’t work, and the more I think about it the more obvious it seems.

I’m probably missing something simple, but is there a way to pass the word random or @r to my command and have it teleport a random player?

Here is a pastebin of my RandomTP Command: http://pastebin.com/VR1He8fZ

Any help would be nice.
Thank you,

TopHatDuck

Having thought about it overnight, I may have figured out part of an answer.
First I would have to make a separate if statement to detect if the argument passes with /rtp is equal to a string “@r” or “random” or whatever I decide. Then somehow use sponge to make a string array of all the online players. Then use the Random Class to generate a random number based on the length of the String Array.

I’m just not sure how to do these things. And I’m away from my computer with the plugin on it to test.

Any advice on how to accomplish this would be nice.

Thank you,
TopHatDuck

After you’ve checked that your argument is “@r”, “random” or whatever the following is a simple way of doing what you’re asking for.

NOTE: I’ve split everything up on its own line, to make it easier to read:

// Let's get all online players from Sponge.
Collection<Player> players = Sponge.getServer().getOnlinePlayers();

// Let's get the amount of online players.
int amount = players.size();

// Let's convert our collection to an array, so that we can get a player at an index.
Player[] playerArray = players.toArray(new Player[amount]);

// Let's get a random number that is between 0 and amount. (0 being inclusive and amount being exclusive)
int random = ThreadLocalRandom.current().nextInt(amount);

// Let's get the random player within the player array, getting the player at the index of the random number.
Player randomPlayer = playerArray[random];

I was getting ready to say to use a random array. Cx but i believe that would work.

Thank you, this is exactly what I was looking for!

Finally got it working! In order to use “@a” as an argument I had to make sure the argument was passed as a string, so unfortunately I can’t tab finish this command, but I’m ok with that for now.

If anyone has a way to fix this then I would appreciate this, but until then, thank you for your help.

TopHatDuck

p.s. here is my new command: http://pastebin.com/PzczNy4a