[Help]How to make a counter player specific!

Discussion in 'Plugin Development' started by fred302, Apr 25, 2012.

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

    fred302

    Im making a criminal record plugin and i want to know how to make a counter player specific. Its for the infraction counts. When you type /cr add (Name): it adds a infraction to the players counter!
     
  2. Offline

    Karl Marx

    I'd use a map to store each player's counter. Use the player's name (String) as the key, and then it's just a simple lookup whenever the command runs; and it will serialize directly to/from your config.
     
  3. Offline

    fred302

    can you give me the code to put in and thanks. Karl Marx
     
  4. Offline

    Karl Marx

    If I did that, there wouldn't be anything left for you to write :p

    Here's the basic idea, though:
    1. You declare a Map<String, Integer> in your class to "map" player names to their count. For now, I'll just call it "counts".
    2. Try to load counts from your config: counts = myConfig.getMap("path/to/map");
    3. If counts is null, then your config didn't have anything, so create the Map manually (try HashMap).
    4. Whenever your command is called, retrieve the player's count: counts.get(thePlayer.getName());
    5. We use Integer here (instead of int) so that the map can return null when it doesn't have a record for that player - make sure you check for null.
    6. add one to the player's count.
    7. store it back into the map: counts.put(thePlayer.getName(), playerCount);
    8. At some point (probably in your plugin's onDisable()) write your map back to the config: myConfig.set("path/to/map", counts);
    If you're not familiar with maps and other data structures, you should probably look them up- they're pretty useful.
     
  5. Offline

    fred302

    Do you think you could make a example.
     
  6. Offline

    Craftiii4

    Your hash map would look like this:

    Code:java
    1.  
    2. public final static Map<Player, Integer> record = new HashMap<Player, Integer>();
    3.  


    Maybe load and save to the hash map on player join / leave?
     
  7. Offline

    Sagacious_Zed Bukkit Docs

    1.
    Code:
    Map<String, Integer> counts;
    2.
    Code:
    counts = getConfig().getConfigurationSection("path.to.existing.map").getValues(false);
    3.
    Code:
    if (counts == null) counters = new HashMap<String, Integer>();
    4.
    Code:
    counts.get(player.getName());
    5.
    Code:
    if (counts.get(player.getName() != null) {
      //do something
    }
    6. 7.
    Code:
    counts.put(player.getName(), counts.get(player.getName() + 1));
    8.
    Code:
    getConfig().set("path.to.existing.map",  counts);
    saveConfig()
     
  8. Offline

    Craftiii4

    I quickly put this together, i have not tested though.

    Code:java
    1.  
    2.  
    3. package me.craftiii4.TestTest04;
    4.  
    5. import java.io.File;
    6. import java.io.FileNotFoundException;
    7. import java.io.IOException;
    8. import java.util.Arrays;
    9. import java.util.HashMap;
    10. import java.util.List;
    11. import java.util.Map;
    12.  
    13.  
    14. import org.bukkit.Bukkit;
    15. import org.bukkit.ChatColor;
    16. import org.bukkit.Location;
    17. import org.bukkit.Material;
    18. import org.bukkit.OfflinePlayer;
    19. import org.bukkit.block.Block;
    20. import org.bukkit.block.Chest;
    21. import org.bukkit.command.Command;
    22. import org.bukkit.command.CommandSender;
    23. import org.bukkit.configuration.InvalidConfigurationException;
    24. import org.bukkit.configuration.file.FileConfiguration;
    25. import org.bukkit.configuration.file.YamlConfiguration;
    26. import org.bukkit.entity.Player;
    27. import org.bukkit.inventory.ItemStack;
    28. import org.bukkit.plugin.java.JavaPlugin;
    29.  
    30. public class TestTest04 extends JavaPlugin {
    31.  
    32. public final static Map<Player, Integer> record = new HashMap<Player, Integer>();
    33.  
    34.  
    35. @Override
    36. public void onDisable() {
    37.  
    38. System.out.println("[TestTest04] TestTest04 v"
    39. + getDescription().getVersion() + " disabled!");
    40.  
    41.  
    42. saveConfig();
    43.  
    44. }
    45.  
    46. @Override
    47. public void onEnable() {
    48.  
    49. loadConfiguration();
    50.  
    51. new TestTest04PlayerListener(this);
    52.  
    53. System.out.println("[TestTest04] TestTest04 v"
    54. + getDescription().getVersion() + " Enabled!");
    55.  
    56. }
    57.  
    58.  
    59. public void loadConfiguration() {
    60.  
    61. //inset anything you wish to load in here
    62.  
    63. }
    64.  
    65.  
    66. public boolean onCommand(CommandSender sender, Command command,
    67. String commandLabel, String args[]) {
    68. String commandName = command.getName().toLowerCase();
    69. final Player player;
    70. if (sender instanceof Player) {
    71. player = (Player) sender;
    72. } else {
    73. return true;
    74. }
    75.  
    76. if (commandName.equals("cr")) {
    77.  
    78. if (args.length == 0) {
    79.  
    80. player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GOLD + "CR"
    81. + ChatColor.AQUA + "] " + ChatColor.RED
    82. + "/cr add <name>");
    83.  
    84. }
    85.  
    86. if (args.length == 1) {
    87.  
    88. player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GOLD + "CR"
    89. + ChatColor.AQUA + "] " + ChatColor.RED
    90. + "/cr add <name>");
    91.  
    92. }
    93.  
    94. if (args.length == 2) {
    95.  
    96. boolean correct1 = false;
    97.  
    98. String whatisit1;
    99. whatisit1 = args[0];
    100. if (whatisit1.equalsIgnoreCase("add")) {
    101. correct1 = true;
    102.  
    103. String whatisit2;
    104. whatisit2 = args[1];
    105.  
    106. Player p2name = Bukkit.getPlayer(whatisit2);
    107.  
    108. if (TestTest04.record.containsKey(p2name)) {
    109.  
    110. String p2namestring = p2name.getName();
    111.  
    112. int currentrecord = TestTest04.record.get(p2name);
    113. int newrecord = currentrecord++;
    114. TestTest04.record.remove(p2name);
    115. TestTest04.record.put(p2name, newrecord);
    116.  
    117. player.sendMessage(ChatColor.AQUA + "["
    118. + ChatColor.GOLD + "CR" + ChatColor.AQUA + "] "
    119. + ChatColor.GOLD + "Player " + ChatColor.GREEN
    120. + p2namestring + ChatColor.GOLD + " Now has "
    121. + ChatColor.LIGHT_PURPLE + newrecord
    122. + ChatColor.GOLD + " Warning points");
    123.  
    124. } else {
    125.  
    126. player.sendMessage(ChatColor.AQUA + "["
    127. + ChatColor.GOLD + "CR" + ChatColor.AQUA + "] "
    128. + ChatColor.RED + "Player " + ChatColor.GREEN
    129. + whatisit2 + ChatColor.RED + " is not online");
    130.  
    131. }
    132.  
    133. }
    134.  
    135. if (correct1 == false) {
    136.  
    137. player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GOLD
    138. + "CR" + ChatColor.AQUA + "] " + ChatColor.RED
    139. + "/cr add <name>");
    140.  
    141. }
    142.  
    143. }
    144.  
    145. }
    146. return false;
    147.  
    148. }
    149.  
    150.  
    151. }
    152.  
    153.  


    This is just the main class
     
  9. Offline

    Father Of Time

    Fyi, it's poor practice to have a timer per player object IMO; instead use one "master timer" that ticks once a second, and during that tick cycle through everyone's "criminal record" and take the necessary action on them.

    With my method you have one timer handling 0 to infinite records; however, with your method you have one timer per criminal, which could result in 100s of timers depending on your servers popularity.
     
  10. Offline

    fred302

  11. Offline

    fred302

    Anyother things. For some reason it wont work Craftiii4
     
  12. Offline

    CorrieKay

    This typically happens when you ask others to write your code for you.

    protip: dont ever copypaste others code examples into your own projects, they never work that way, the variables and stuff rarely ever match up correctly.
     
  13. Offline

    SirTyler

    Fred302 They are doing your work for you, I think you should look into what they are talking about and understand it first so that you can try and answer your own questions.
     
  14. Offline

    fred302

    i know they are going the work for me, but i do need some development help. If anyone wants to help me with this i would be more than happy to give credit.
     
  15. Offline

    CorrieKay

    credit isnt what we're worrying about, its that youre not learning anything. Youre just asking for the code to do something, instead of learning how to utilize the code, and figuring it out yourself. Thats not good for you.


    ...and to be very honest, using a key/value datatype is kinda basic stuff, so you shouldnt have an issue with learning this...

    (this is plugin development, not java 101 ;3)
     
  16. Offline

    fred302

    well i am. Im a slow learner. If you could please help me write this it would be nice of you
     
  17. Offline

    CorrieKay

    Sorry, i cant do that :\

    Im not trying to be a dick or anything, but it wont help you in the slightest, nor will i know how to write it correctly.

    If you want someone to write a plugin for you, i suggest asking in the plugin requests forum.
     
  18. Offline

    fred302

    i want to write it myself just need a little help
     
  19. Offline

    CorrieKay

    Then ill help you to understand what you need to do.

    First things first, do you have any idea how to work with a hash map?
     
  20. Offline

    fred302

    no i dont
     
  21. Offline

    CorrieKay

    Then you really shouldnt be doing this...

    Okay, a hash map is a type of Map (which is a data type). hash maps store data in Key/Value type storage.

    Basically, a hash map is locked in to what kinds of objects it can have as keys and values, defined when you declare the map.

    HashMap<Object,Object> hashMapExample = new HashMap<Object,Object>();

    You can have the object's be pretty much anything you want, including hash maps. (creating multidimensional maps, but we wont get into that)

    SO, if you wanted to keep a specific value to a player, you would create a hash map that looks like this

    HashMap<Player,Integer> infractions = new HashMap<Player,Integer>();

    =================

    Getter/Setters:

    To modify data within the hash map, you will "put" sets of data in a map.

    for instance, if you have a player, and want to set his infraction count to 1, you would do

    infractions.put(player,1);

    Note that if player is already a key in the map, it wont add another player, but will override the original player's value. (basically, if player.equals(key) it will replace it, not that you cant have multiple player objects in a key)

    To get a value, you do infractions.get(player);
    this will return an integer for you. Note, that since values can be the same thing, you cannot grab a key by value, however, you can use an enhanced for loop to return a key that has a specific value, just note again that its not guarenteed to be unique.

    i think this should be good enough, though i may have missed a point or two..
     
  22. Offline

    fred302

    ok so now how do i add a infraction to a player. like /cr add fred50 will add me to the infraction list with one
    and then /cr add fred50 1 will add another infraction
     
  23. Offline

    CorrieKay

    well first, you would want to modify the players infraction. Something like,
    infraction.put(player, infraction.get(player)+1);
    this will add +1 to the infraction count every time you use it.
     
  24. Offline

    fred302

    ok what else
     
  25. Offline

    Craftiii4

    I learned everything i know about java by looking at other peoples code and testing around.

    fred302

    What code have you currently got? mind pasting so we can direct you?
     
  26. Offline

    fred302

    Yes i can paste it. Here you go!
    Code:
    package me.fred50.plugins.criminal;
     
    import java.util.HashMap;
    import java.util.Map;
    import java.util.logging.Logger;
     
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class Criminal extends JavaPlugin{
        public static Criminal plugin;
        HashMap<String,Integer> counts;
        Logger log;
        Logger logger = Logger.getLogger("Minecraft");
        @Override
        public void onEnable(){
            log = this.getLogger();
            log.info("Criminal has been enabled!");
            this.reloadConfig();
            getConfig().set("path.to.existing.map",  counts);
            saveConfig();
            }
        @Override
        public void onDisable(){
            log.info("Criminal has been disabled!");
            this.saveConfig();
        }
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[], Object infractionCount){
            Player player = (Player) sender;
            if(commandLabel.equalsIgnoreCase("cr")){
                if(args.length == 0){
                    if (counts == null) counts = new HashMap<String, Integer>();
                    if(player.isOp()){
                        player.sendMessage(ChatColor.GREEN + "Criminal Records");
                        player.sendMessage(ChatColor.GREEN + "/Cr add <name>");
                        player.sendMessage(ChatColor.GREEN + "/Cr view <name>");
                        player.sendMessage(ChatColor.GREEN + "/Cr myrecord");
                    }
                }if(args.length == 1){
                    if (counts == null) counts = new HashMap<String, Integer>();
                    if(player.isOp()){
                        if(args[0].equalsIgnoreCase("add")){
                            player.sendMessage(ChatColor.DARK_RED + "Too little arguments! /cr add <name>");
                        }
                    }if(player.isOp()){
                        if(args[0].equalsIgnoreCase("view")){
                            player.sendMessage(ChatColor.DARK_RED + "Too little arguments! /cr view <view>");
                        }
                    }if(player.isOp()){
                        if(args[0].equalsIgnoreCase("myrecord")){
                            player.sendMessage(ChatColor.GREEN + "You have " + counts.get(player) + " infractions!");
                        }
                    }
                }if(args.length == 2){
                    if (counts == null) counts = new HashMap<String, Integer>();
                    Player targetPlayer = player.getServer().getPlayer(args [0]);
                    if(args[0].equalsIgnoreCase("add")){
                        if(player.isOp()){
                            if(counts.get(player.getName())!= null){
                                counts.put(player.getName(), counts.get(player.getName() + 1));
                                sender.sendMessage(ChatColor.GREEN + "Added a infraction to " + targetPlayer.getName() + "'s account!");
                            }
                        }
                    }if(player.isOp()){
                        if(args[0].equalsIgnoreCase("view")){
                            if(player.isOp()){
                                player.sendMessage(ChatColor.GREEN + "That player has " + counts.get(plugin.getServer().getPlayer("") + " infractions"));
                            }
                        }
                    }
                }
            }
            return false;
        }
    }
     
  27. Offline

    Craftiii4

    Well, for a start change
    Code:java
    1. HashMap<String,Integer> counts;

    to
    Code:java
    1. public final static HashMap<String,Integer> counts = new HashMap<String,Integer>();


    Remove all of these
    Code:java
    1. if (counts == null) counts = new HashMap<String, Integer>();


    and when seeing if counts contains a player use this
    Code:java
    1.  
    2. if(counts.containsKey(targetPlayer.getName())) {
    3.  


    When getting a players counts use
    Code:java
    1. int oldcounts = counts.get(targetPlayer.getName());


    and when adding one use
    Code:java
    1.  
    2. int newcounts = oldcounts + 1;
    3. counts.remove(targetPlayer.getName());
    4. counts.put(targetPlayer.getName(), newcounts);
    5.  


    Also make sure what player you are getting with targetPlayer, using player means you are getting te sender not the target player and your "Player targetPlayer = player.getServer().getPlayer(args [0]);" is getting the first arg? is this right?
     
  28. Offline

    fred302

    yes but what if i want to use /cr view <name>
     
  29. Offline

    Craftiii4

    Code:java
    1.  
    2. int currentrecord = TestTest04.counts.get(targetplayername);
    3.  
    4. player.sendMessage(ChatColor.AQUA + "["
    5. + ChatColor.GOLD + "CR" + ChatColor.AQUA + "] "
    6. + ChatColor.GOLD + "Player " + ChatColor.GREEN
    7. + targetplayername + ChatColor.GOLD + " has " + ChatColor.LIGHT_PURPLE + currentrecord + ChatColor.GOLD + " Warning Points");
    8.  
     
  30. Offline

    CorrieKay

    Im not trying to be mean or anything, nor do i really care, but spoonfeeding him the code like that isnt gonna help, youre just writing his plugin for him.

    Again, not trying to be rude, just pointing that out...
     
Thread Status:
Not open for further replies.

Share This Page