How to randomize and then split an ArrayList<String> into two even ArrayLists
i know virtually no java but i'm trying to learn some for this project. I am trying to modify a program called GyaPickupBot which is basically a "pick up game" bot on IRC where players can type: !add in order to get added to a list of players who want to play a game and once enough players !add the bot announces the ip of the game server (i.e. quake server) that the game is to be played on. right now, when the specified number of players !add and the game launches, the bot only lists the players who previously !add'ed before the max number of players was reached. I would like for it to divide all of the players who have !add'ed up into 2 random teams of equal size. I have already done the random part using Collections.shuffle but I have no idea how to divide the players into 2 equally sized teams. I emailed the author who is based in Japan a few weeks ago and he finally replied this morning with some very vague hints on how to do this:
Well... at this time, I don't have much motivation to maintain this code. I can only suggest you some hints.
private boolean handleReady(String channel, String sender, String login, String hostname, String message) {
boolean isUpdate = false;
String readyGameID = mgr.getReadyGameID();
if (null != readyGameID) {
// *** add some code here to choose teams and stor开发者_JAVA技巧e that result to string variable. something like: "team1: ,,,, team2: ,,,,,"
// *** you can get players list by mgr.getPlayers(readyGameID) in order to divide players to 2 teams randomly
for (String ch : getChannels()) {
sendMessage(ch, mgr.getPickupReadyString(readyGameID));
// sendNotice(ch, mgr.getPickupReadyString(readyGameID));
// *** then, send that string to channel
}
mgr.setLastGame(Calendar.getInstance().getTimeInMillis(), mgr.getPickupReadyString(readyGameID));
ArrayList<String> players = mgr.getPlayers(readyGameID);
for (String nick : players) {
sendNotice(nick, mgr.getPickupReadyPMString(readyGameID));
// *** and send that string to players too
}
isUpdate = mgr.clearPlayers(players);
}
return isUpdate;
I know this is probably more than what is asked on here, but I'm really trying to learn this but I can't figure it out and any help would be appreciated
The code below is untested, but should give you an idea on how to proceed. Good luck.
// retrieve all players
ArrayList<String> players = mgr.getPlayers(readyGameID);
// randomize the list
Collections.shuffle(players);
// instantiate two arraylists for the teams
ArrayList<String> teamRed = new ArrayList<String>();
ArrayList<String> teamBlue = new ArrayList<String>();
// add the first half of players to teamRed
teamRed.addAll(players.subList(0, players.size() / 2 + players.size()%2));
// and the second half to teamBlue
teamBlue.addAll(players.subList(players.size() / 2 + players.size()%2, players.size()));
// now do whatever you need to do with the two teams
精彩评论