Have you ever wanted to make your players vote for a poll or arena selection? This is a tutorial on how to make voting possible using Java! Example: Let's say I am playing Survival Games and I want to play on a certain map. I would vote for it. Let's look at how it's done. Step 1. Create a HashMap storing what each player voted for and the value being the Object you want to be voted for (in my case, an arena). Code:java private Map<String, Arena> vote = new HashMap<String, Arena>(); Step 2. Make a method that gets the votes of your object. (I will explain). Code:java public int getVotes(Arena a) {if(a == null) // If the arena doesn't exist, return 0.return 0;int count = 0; // Default votes.for(String s : vote.keySet()) { // Loop through all keys (player names/UUIDs)if(Bukkit.getPlayer(s) == null) { // Checks if player isn't online.vote.remove(s); // Removes this 'ghost' vote (Player vote doesn't count) to avoid bugs.continue; // Skips the player.}if(vote.get(s) == a) // If the value of the player's name/UUID is equal to the arena (a),count++; // We add 1 to the count.}return count; // Returns votes.} Step 3. Compare the votes of all your Objects. Code:java public Arena getMostPopular() {Arena chosen = null;for(Arena a : array) { // Replace array with your array/list.if(a == null) { // Safe null check.array.remove(a); // Removes arena from array.continue; // Skips.}if(chosen == null) { // Checks if chosen is null.chosen = a; // Sets chosen to that arena.continue;}if(getVotes(a) >= getVotes(chosen)) { // Checks if votes are higher than chosen's.chosen = a; // Sets chosen to that arena.continue;}}return chosen; // Returns the chosen arena.// This will not return null unless the array is empty.} Then of course you can use this method to start a game with that specified arena. Thanks for reading, Gabe.
Why not Arena, Integer (heck, an integer wrapper that automatically increments for you) so you can do something like: PHP: class IntWrapper { int wrapped = 0; public static IntWrapper wrap(int in) { wrapped = in; } public int wrapped() { return wrapped; } public IntWrapper increment() { wrapped += 1; return this; }}private final Map<Arena, IntWrapper> votes = // ...// Increment (Arena arena)votes.put(arena, votes.get(arena).increment());// Get (Arena arena)int votes = votes.get(arena).wrapped();
xTrollxDudex Because the player might leave and the game might take a ghost vote (if player is not online), however, that's another possible way using a null check.
You could back IntWrapper with an ArrayList with player strings and get the size each time, then when you get the amount of votes, update the list.