How to create command arguments?

Ok, I follow what @dualspiral said and created the code below. Now I need to make a vote counter to count how many people voted for each option. I assume I need to use the Collections api, but I don’t know which collection to use.
Code:


public boolean call(CommandSource source, String arguments, List parents) throws CommandException {

        String[] args = arguments.split(" ");

        if(!(source instanceof Player)) {
            source.sendMessage(ErrorMessage.PlayerOnlyError());
            return false;
        }

        Player player = (Player) source;
        UUID playerUUID = player.getUniqueId();
        String name = player.getName();
        Set voted = new HashSet();

        /*
         If someone uses the /vote command
         without providing arguments,
         it will show the player all
         the possible choices(arguments)
          */
        if(args.length <= 0) {

        }

        /*
        If someone using the /vote
        command supplies two arguments such as
        "/vote argument1 argument2", it will notify the
        player about this problem.
         */
        if(args.length >= 2) {

        }

        try {
            int MapNumber = Integer.parseInt(args[1]);

            if(MapNumber < 1 && MapNumber > 6) {
                player.sendMessage(ErrorMessage.InvalidOptionError());
                return false;
            }

            switch(MapNumber) {
                case 1:
                    if(voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                    }
                    break;
                case 2:
                    if(voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                    }
                    break;
                case 3:
                    if(voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                    }
                    break;
                case 4:
                    if(voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                    }
                    break;
                case 5:
                    if (voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                    }
                    break;
                default:
                    getLogger().info(player.getName() + " has entered an invalid option.");
                    break;
            }

        } catch (NumberFormatException e) {
            player.sendMessage(ErrorMessage.InvalidOptionError());
            getLogger().info(player.getName() + " has entered an invalid option.");
            return false;
        }

        return true;
    }

Did what you said and created a HashSet. Thanks for your help!

Have another question. I need to make a vote counter that counts how many player vote for a map. I would assume I need to use the Collections api, but I don’t know which I should use. If a player uses “/vote 4”, it adds on vote to option_5. After the voting process is over, the collection is cleared. Could anyone help me?

In your game object (if it’s a custom class) create a HashMap for the map, and the integer as a count. Simply add to the integer per vote.

e.g.

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

public void onVote(int MapNum) {
  map.put(MapNum, map.get(MapNum)++);
}

Thanks, @LordLambda. that helped me a lot. There are so much Collections to choose from!

Simple question, how do you get the amount of players currently online in the form of a int?

Thanks everyone for your help! I’ve finished the /vote command!

package com.blockenton.plugins.base.voter.command;

/*
Manage Imports
*/

import com.blockenton.plugins.base.voter.message.ErrorMessage;

import com.google.common.base.Optional;

import org.slf4j.Logger;

import org.spongepowered.api.Server;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyles;
import org.spongepowered.api.text.message.Message;
import org.spongepowered.api.text.message.Messages;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandException;
import org.spongepowered.api.util.command.CommandSource;

import java.util.*;

/**

  • The main class of the /vote command.

  • This class is registered in the {@link com.blockenton.plugins.base.voter.JavaPlugin}

  • class. This class implements {@link org.spongepowered.api.util.command.CommandCallable}

  • in order to create a command.

  • @author Jeff Chen

  • @since 0.0.1-DEV-2
    */
    public class VoteCommand implements CommandCallable {

    private final Server server;

    private Logger logger;

    private Logger getLogger() {
    return logger;
    }

    HashMap<Integer, Integer> VoteCounter = new HashMap<Integer, Integer>();

    public void onVote(int option) {
    VoteCounter.put(option, VoteCounter.get((option)++));
    }

    private final Optional desc = Optional.of(“Vote for a specific map”);
    private final Optional help = Optional.of(“Vote for a specific map”);

    public Message VoteSucess(int option) {
    return Messages.of("[").builder().color(TextColors.GRAY)
    .append(Messages.builder(“Lobby”).color(TextColors.BLUE).style(TextStyles.BOLD)
    .append(Messages.builder("] ").color(TextColors.GRAY)
    .append(Messages.builder("Your vote has been recieved. Your option now has ").color(TextColors.GOLD)
    .append(Messages.of(VoteCounter.get(option) + " ").builder().color(TextColors.GREEN)
    .append(Messages.builder(“vote(s).”).color(TextColors.GOLD)
    .build())
    .build())
    .build())
    .build())
    .build())
    .build();
    }

    public VoteCommand(Server server) {
    this.server = server;
    }

    /**

    • What happens when the command is called by the

    • player or the console is below.

    • @param source The source of the command, who it was sent by.

    • @param arguments Any arguments the player supplies.

    • @param parents Any traits the command inherits from.

    • @return If the command was successfully sent.

    • @throws CommandException

    • @see org.spongepowered.api.util.command.CommandSource

    • @since 0.0.1-DEV-2
      */
      public boolean call(CommandSource source, String arguments, List parents) throws CommandException {

      String[] args = arguments.split(" ");

      if (!(source instanceof Player)) {
      source.sendMessage(ErrorMessage.PlayerOnlyError());
      return false;
      }

      Player player = (Player) source;
      UUID playerUUID = player.getUniqueId();
      String name = player.getName();

      Set voted = new HashSet();
      Map<String, Integer> VoteMap = new HashMap<String, Integer>();

      /*
      If someone uses the /vote command
      without providing arguments,
      it will show the player all
      the possible choices(arguments)
      */
      if (args.length <= 0) {

      }

      /*
      If someone using the /vote
      command supplies two arguments such as
      “/vote argument1 argument2”, it will notify the
      player about this problem.
      */
      if (args.length >= 2) {

      }

      try {
      int MapNumber = Integer.parseInt(args[1]);

       if (MapNumber < 1 && MapNumber > 6) {
           player.sendMessage(ErrorMessage.InvalidOptionError());
           return false;
       }
      
       switch (MapNumber) {
           case 1:
               if (voted.contains(playerUUID)) {
                   player.sendMessage(ErrorMessage.AlreadyVotedError());
               } else {
                   voted.add(playerUUID);
                   onVote(MapNumber);
                   player.sendMessage(VoteSucess(MapNumber));
               }
               break;
           case 2:
               if (voted.contains(playerUUID)) {
                   player.sendMessage(ErrorMessage.AlreadyVotedError());
               } else {
                   voted.add(playerUUID);
                   onVote(MapNumber);
                   player.sendMessage(VoteSucess(MapNumber));
               }
               break;
           case 3:
               if (voted.contains(playerUUID)) {
                   player.sendMessage(ErrorMessage.AlreadyVotedError());
               } else {
                   voted.add(playerUUID);
                   onVote(MapNumber);
                   player.sendMessage(VoteSucess(MapNumber));
               }
               break;
           case 4:
               if (voted.contains(playerUUID)) {
                   player.sendMessage(ErrorMessage.AlreadyVotedError());
               } else {
                   voted.add(playerUUID);
                   onVote(MapNumber);
                   player.sendMessage(VoteSucess(MapNumber));
               }
               break;
           case 5:
               if (voted.contains(playerUUID)) {
                   player.sendMessage(ErrorMessage.AlreadyVotedError());
               } else {
                   voted.add(playerUUID);
                   onVote(MapNumber);
                   player.sendMessage(VoteSucess(MapNumber));
               }
               break;
           default:
               getLogger().info(player.getName() + " has entered an invalid option.");
               break;
       }
      

      } catch (NumberFormatException e) {
      player.sendMessage(ErrorMessage.InvalidOptionError());
      getLogger().info(player.getName() + " has entered an invalid option.");
      return false;
      } catch (Exception e) {
      getLogger().info(“An exception occured: NumberFormatException”);
      }

      return true;
      }

    /**

    • Test if a player has the correct permissions to
    • use this plugin.
    • @param source The source of the command, who it was sent by.
    • @return If the source has the correct permissions.
    • @since 0.0.1-DEV-2
      */
      public boolean testPermission(CommandSource source) {
      return source.hasPermission(“groups.user”);
      }

    public Optional getShortDescription() {
    return desc;
    }

    public Optional getHelp() {
    return help;
    }

    /**

    • Gets the usage of the command.
    • @return The usage of the command.
    • @since 0.0.1-DEV-2
      */
      public String getUsage() {
      return "/<vote|lobby:vote|v> ";
      }

    public List getSuggestions(CommandSource source, String arguments) throws CommandException {
    return Collections.emptyList();
    }
    }

Put your code in code tags. Syntax highlighting and it does not take up the whole page :stuck_out_tongue:

  1. try do your string builders in readable state and not build all the time.
  2. Your argument checks for length isnt 1 are unfinished.
  3. whats the point of the switch case if all cases are identical?
  4. Are you going to save the vote data to file?

How do you even do SYNTAX HIGHLIGHTING?

```Your Code```

Example:

``` java

class Main {

   public static void main(String[] args) {
       System.out.println(1 + 1);
   }

}
```

Produces


class Main {

   public static void main(String[] args) {
       System.out.println(1 + 1);
   }

}
int MapNumber = Integer.parseInt(args[1]);

^ Ew, PascalCase variable names.

3 Likes

Ok. I have a HashMap that counts everyone’s votes, but I need to find the option with the most votes. I tried searching the internet, and they said HashMap is not suitable for ordering. My HashMap is named VoteMap. Preview of my code below.

package com.blockenton.plugins.base.voter.command;

import com.blockenton.plugins.base.voter.message.ErrorMessage;

import com.google.common.base.Optional;

import org.slf4j.Logger;

import org.spongepowered.api.Server;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyles;
import org.spongepowered.api.text.message.Message;
import org.spongepowered.api.text.message.Messages;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandException;
import org.spongepowered.api.util.command.CommandSource;

import java.util.*;

/**
 * <p>
 * The main class of the /vote command.
 * This class is registered in the {@link com.blockenton.plugins.base.voter.JavaPlugin}
 * class. This class implements {@link org.spongepowered.api.util.command.CommandCallable}
 * in order to create a command.
 * </p>
 *
 * @author Jeff Chen
 * @since 0.0.1-DEV-2
 */
public class VoteCommand implements CommandCallable {

    private final Server server;

    private Logger logger;

    private Logger getLogger() {
        return logger;
    }
    HashMap<Integer, Integer> VoteCounter = new HashMap<Integer, Integer>();
    Map<Integer, Integer> VoteMap = new HashMap<Integer, Integer>();
    Set<UUID> voted = new HashSet<UUID>();

    public void onVote(int option) {
        VoteCounter.put(option, VoteCounter.get((option)++));
    }

    private final Optional<String> desc = Optional.of("Vote for a specific map");
    private final Optional<String> help = Optional.of("Vote for a specific map");

    public Message VoteSucess(int option) {
        return Messages.of("[").builder().color(TextColors.GRAY)
                .append(Messages.builder("Lobby").color(TextColors.BLUE).style(TextStyles.BOLD)
                        .append(Messages.builder("] ").color(TextColors.GRAY)
                                .append(Messages.builder("Your vote has been recieved. Your option now has ").color(TextColors.GOLD)
                                        .append(Messages.of(VoteCounter.get(option) + " ").builder().color(TextColors.GREEN)
                                                .append(Messages.builder("vote(s).").color(TextColors.GOLD)
                                                        .build())
                                                .build())
                                        .build())
                                .build())
                        .build())
                .build();
    }

    public VoteCommand(Server server) {
        this.server = server;
    }

    /**
     * <p>
     * What happens when the command is called by the
     * player or the console is below.
     * </p>
     *
     * @param source    The source of the command, who it was sent by.
     * @param arguments Any arguments the player supplies.
     * @param parents   Any traits the command inherits from.
     * @return If the command was successfully sent.
     * @throws CommandException
     * @see org.spongepowered.api.util.command.CommandSource
     * @since 0.0.1-DEV-2
     */
    public boolean call(CommandSource source, String arguments, List<String> parents) throws CommandException {

        String[] args = arguments.split(" ");

        if (!(source instanceof Player)) {
            source.sendMessage(ErrorMessage.PlayerOnlyError());
            return false;
        }

        Player player = (Player) source;
        UUID playerUUID = player.getUniqueId();
        String name = player.getName();

        int MostPopularVote = Collections.max(VoteMap.values());

        /*
         If someone uses the /vote command
         without providing arguments,
         it will show the player all
         the possible choices(arguments)
          */
        if (args.length <= 0) {

        }

        /*
        If someone using the /vote
        command supplies two arguments such as
        "/vote argument1 argument2", it will notify the
        player about this problem.
         */
        if (args.length >= 2) {

        }

        try {
            int MapNumber = Integer.parseInt(args[1]);

            if (MapNumber < 1 && MapNumber > 6) {
                player.sendMessage(ErrorMessage.InvalidOptionError());
                return false;
            }

            switch (MapNumber) {
                case 1:
                    if (voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                        onVote(MapNumber);
                        player.sendMessage(VoteSucess(MapNumber));
                    }
                    break;
                case 2:
                    if (voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                        onVote(MapNumber);
                        player.sendMessage(VoteSucess(MapNumber));
                    }
                    break;
                case 3:
                    if (voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                        onVote(MapNumber);
                        player.sendMessage(VoteSucess(MapNumber));
                    }
                    break;
                case 4:
                    if (voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                        onVote(MapNumber);
                        player.sendMessage(VoteSucess(MapNumber));
                    }
                    break;
                case 5:
                    if (voted.contains(playerUUID)) {
                        player.sendMessage(ErrorMessage.AlreadyVotedError());
                    } else {
                        voted.add(playerUUID);
                        onVote(MapNumber);
                        player.sendMessage(VoteSucess(MapNumber));
                    }
                    break;
                default:
                    getLogger().info(player.getName() + " has entered an invalid option.");
                    break;
            }

        } catch (NumberFormatException e) {
            player.sendMessage(ErrorMessage.InvalidOptionError());
            getLogger().info(player.getName() + " has entered an invalid option.");
            return false;
        } catch (Exception e) {
            getLogger().info("An exception occured: NumberFormatException");
        }

        return true;
    }

    /**
     * <p>
     * Test if a player has the correct permissions to
     * use this plugin.
     * </p>
     *
     * @param source The source of the command, who it was sent by.
     * @return If the source has the correct permissions.
     * @since 0.0.1-DEV-2
     */
    public boolean testPermission(CommandSource source) {
        return source.hasPermission("groups.user");
    }

    public Optional<String> getShortDescription() {
        return desc;
    }

    public Optional<String> getHelp() {
        return help;
    }

    /**
     * <p>
     * Gets the usage of the command.
     * </p>
     *
     * @return The usage of the command.
     * @since 0.0.1-DEV-2
     */
    public String getUsage() {
        return "/<vote|lobby:vote|v> <map>";
    }

    public List<String> getSuggestions(CommandSource source, String arguments) throws CommandException {
        return Collections.emptyList();
    }
}

Could you please follow Java’s standards and use camelCase for variable names?

Just iterate through the hashmap and put all of the values in an array, and get the highest number from there.

Try a LinkedHashMap? Just iterate over the map.

Ok, I tried looking at the SpongeDocs and I noticed there wasn’t a section on how to create and work with the inventory. When a player joins the server, I want there to be the player’s custom head in the first slot, a book in the second slot, and a door in the last slot. I want these items to be not droppable and I don’t want players to pick up items. I am pretty sure I need to use ItemStackBuilder but I do not know how to use it.
I will be trying my best to skim the JavaDocs, but meanwhile, I would need the help of the Sponge community.


You need to get GameRegistry from Game (which is from the main class) and then get ItemStackBuilder from GameRegistry.

Example: (Warning: Pseudo code)
Game game; GameRegistry gr = game.getRegistry(); ItemStackBuilder itemBuilder = gr.getItemStackBuilder();

You should really create a new post for this.

I created a new post!