Coins| Its that time again...

Discussion in 'Plugin Development' started by XgXXSnipz, Nov 4, 2014.

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

    XgXXSnipz

    Alrighty guys, so if any of you remember about 5 months ago I was trying to code a coins plugin and absolutely had no knowledge in java :( no I have a decent amount of knowledge, and only have 2 questions. Ok first off i show code: this is the coins
    Code:java
    1. public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    2. // Check if sender is a player first
    3. if (sender instanceof Player) {
    4. // Cast sender to Player
    5. Player player = (Player) sender;
    6. // Check if the command was "tokens"
    7. if (cmd.getName().equalsIgnoreCase("coins")) {
    8. // Check if no arguments are given
    9. if (args.length == 0) {
    10. // Return current owned tokens
    11. player.sendMessage(ChatColor.GREEN + "Your current credits: " + ChatColor.GOLD + Api.getMoney(player));
    12. return true;
    13. // Check if 1 argument is given
    14. } else if (args.length == 1) {
    15. // Argument 1 is the name
    16. String name = args[0];
    17. // Get the player with the given name from server
    18. Player target = Bukkit.getServer().getPlayer(name);
    19. // Check if player is online
    20. if (target != null) {
    21. // Get the tokens of the player
    22. player.sendMessage(target.getDisplayName() + "'s current credits: " + Api.getMoney(target));
    23. return true;
    24. // The player with the given name is not online that means target == null
    25. } else {
    26. // Return that the player is currently not online
    27. player.sendMessage(ChatColor.RED + "The player " + ChatColor.WHITE + name + " is currently not online!");
    28. return true;
    29. }
    30. // Check if 2 arguments are given
    31. } else if (args.length == 2) {
    32. player.sendMessage(ChatColor.RED + "You have to specify the amount of money!");
    33. return true;
    34. // Check if 3 arguments are given
    35. } else if (args.length >= 3) {
    36. // Try and catch here, because parsing could always return an invalid result and therefore an error
    37. try {
    38. // Parse an integer from argument 3
    39. int amount = Integer.parseInt(args[2]);
    40. // Check if the amount is not negative
    41. if (amount > 0) {
    42. // Check if the player has enough money
    43. if (Api.getMoney(player) >= amount) {
    44. // Argument 2 is the name
    45. String name = args[1];
    46. // Get the player with the given name from the server
    47. Player target = Bukkit.getServer().getPlayer(name);
    48. // Check if the player is online
    49. if (target != null) {
    50. // Check if the sub-command "give" was used
    51. if (args[0].equalsIgnoreCase("give")) {
    52.  
    53. // Take money from the player and give money to the target and send both a notification message
    54. Api.takeMoney(player, amount);
    55. Api.giveMoney(target, amount);
    56. player.sendMessage("You sent " + target.getName() + " an amount of " + amount + " credits!");
    57. target.sendMessage("You received " + amount + " credits from " + player.getName() + "!");
    58.  
    59.  
    60. return true;
    61. // Check if the sub-command "take" was used
    62. } else if (args[0].equalsIgnoreCase("take")) {
    63. // Check if the player has the permission to use this sub-command or is OP
    64. if (player.hasPermission("token.take") || player.isOp()) {
    65. // Take money from the target and give money to the player and send both a notification message
    66. Api.giveMoney(player, amount);
    67. Api.takeMoney(target, amount);
    68. player.sendMessage("You took" + amount + " credits from " + player.getName() + "!");
    69. target.sendMessage(player.getName() + " took " + amount + " credits from you!");
    70. return true;
    71. // The player has not the right permissions
    72. } else {
    73. target.sendMessage(ChatColor.RED + "You're missing the permission to take credits from other!");
    74. return true;
    75. }
    76. }
    77. // The player with the given name is not online that means target == null
    78. } else {
    79. // Return that the player is currently not online
    80. player.sendMessage(ChatColor.RED + "The player " + ChatColor.WHITE + name + " is currently not online!");
    81. return true;
    82. }
    83. // The player has not enough money
    84. } else {
    85. // Return that the player does not have enough money
    86. player.sendMessage(ChatColor.RED + "You don't have enough credits(s)! You're missing: " + (amount-Api.getMoney(player)) + " credit(s).");
    87. return true;
    88. }
    89. // The player typed in a negative amount or 0
    90. } else {
    91. // Return that the amount has to be higher than 0
    92. player.sendMessage(ChatColor.RED + "The credit amount has to be higher than 0!");
    93. return true;
    94. }
    95. // The player typed in an invalid money amount
    96. } catch (Exception ex) {
    97. // Return that the money amount is invalid
    98. player.sendMessage(ChatColor.RED + "Invalid credit amount!");
    99. return true;
    100. }
    101. }
    102. }
    103. }
    104. return false;
    105.  
    106. }

    API: Heart and soul of the whole plugin
    Code:java
    1. public class Api {
    2. static SettingsManager settings = SettingsManager.getInstance();
    3.  
    4. public static String getId(Player p){
    5. return p.getUniqueId().toString();
    6. }
    7. private static Map<String, Integer> moneyMap;
    8.  
    9. /* Private access methods */
    10.  
    11. /**
    12.   * Gets the map with all loaded player money values.
    13.   * @return Map<String, Integer> moneyMap
    14.   */
    15. private static Map<String, Integer> getMoneyMap() {
    16. // Checks if the money map exists
    17. if (moneyMap == null) {
    18. // Creates a new HashMap, because there is no existing money map
    19. setMoneyMap(new HashMap<String, Integer>());
    20. }
    21.  
    22. return moneyMap;
    23. }
    24.  
    25. /**
    26.   * Sets and replaces the current map with all player money values.
    27.   * @param Map<String, Integer> moneyMap
    28.   */
    29. private static void setMoneyMap(Map<String, Integer> map) {
    30. moneyMap = map;
    31. }
    32.  
    33. /* Direct access methods */
    34.  
    35. /**
    36.   * Gets the money of a specific player by his name.<br>
    37.   * If the player is already in the money map it will get the players money out of the map.<br>
    38.   * If the player is not in the money map it will load his money map from the FileConfiguration.<br>
    39.   * <p>
    40.   * Returns 0 if an error occurred or no saved money value was found.
    41.   * @param String name
    42.   * @return Integer money
    43.   */
    44. public static int getMoney(String name) {
    45. // Checks if the name is already inside the money map
    46. if (getMoneyMap().containsKey(name)) {
    47. // Returns the money of the found player
    48. return getMoneyMap().get(name);
    49. // No entry was found
    50. } else {
    51. // Try and catch, because the FileConfiguration could be invalid or null
    52. try {
    53. // Checks if the FileConfiguration contains the given name
    54. if (settings.getData().getKeys(false).contains(name)) {
    55. // Checks if the name section contains a "Tokens" section
    56. if (settings.getData().getConfigurationSection(name).getKeys(false).contains("Tokens")) {
    57. // Get the tokens as integer from the FileConfiguration
    58. int tokens = settings.getData().getInt(name+".Tokens");
    59. // Sets and therefore creates an entry with the given name and tokens inside the money map
    60. setMoney(name, tokens);
    61. return tokens;
    62. // No "Tokens" section was found and therefore no tokens values is existent
    63. } else {
    64. // Sets and creates an entry with the given name and 0 tokens inside the money map
    65. setMoney(name, 0);
    66. // Creates the "Tokens" section inside the FileConfiguration
    67. settings.getData().set(name+".Tokens", 0);
    68. return 0;
    69. }
    70. // No section with the given name was found
    71. } else {
    72. // Sets and creates an entry with the given name and 0 tokens inside the money map
    73. setMoney(name, 0);
    74. // Creates the name and "Tokens" sections inside the FileConfiguration
    75. settings.getData().set(name+".Tokens", 0);
    76. return 0;
    77. }
    78. // Something went very wrong and the FileConfiguration or something else created an error
    79. } catch (Exception ex) {
    80. // Print error into console for debug reasons
    81. ex.printStackTrace();
    82. System.out.println("Invalid config data!");
    83. // Return 0 as last option
    84. return 0;
    85. }
    86. }
    87. }
    88.  
    89. /**
    90.   * Gets the money of a specific player.<br>
    91.   * If the player is already in the money map it will get the players money out of the map.<br>
    92.   * If the player is not in the money map it will load his money from the FileConfiguration and then put it into the money map.<br>
    93.   * <p>
    94.   * Returns 0 if an error occurred or no saved money value for the player was found inside the FileConfiguration.
    95.   * @param Player player
    96.   * @return Integer money
    97.   */
    98. public static int getMoney(Player player) {
    99. return getMoney(getId(player));
    100. }
    101.  
    102. /**
    103.   * Sets the money of a specific player by his name.
    104.   * @param String name
    105.   * @param Integer amount
    106.   */
    107. public static void setMoney(String name, int amount) {
    108. getMoneyMap().put(name, amount);
    109. }
    110.  
    111. /**
    112.   * Sets the money of a specific player.
    113.   * @param Player player
    114.   * @param Integer amount
    115.   */
    116. public static void setMoney(Player player, int amount) {
    117. setMoney(getId(player), amount);
    118.  
    119. }
    120.  
    121. /* Simple access methods */
    122.  
    123. /**
    124.   * Gives the specified player with the given name the given amount of money.
    125.   * <p>
    126.   * Automatically caps the money at Integer.MAX_VALUE.
    127.   * @param String name
    128.   * @param Integer amount
    129.   */
    130. public static void giveMoney(String name, int amount) {
    131. int money = getMoney(name) + amount;
    132. setMoney(name, (money <= Integer.MAX_VALUE ? money : Integer.MAX_VALUE));
    133. }
    134.  
    135. /**
    136.   * Gives the specified player the given amount of money.
    137.   * <p>
    138.   * Automatically caps the money at Integer.MAX_VALUE.
    139.   * @param Player player
    140.   * @param Integer amount
    141.   */
    142. public static void giveMoney(Player player, int amount) {
    143. int money = getMoney(getId(player)) + amount;
    144. setMoney(getId(player), (money <= Integer.MAX_VALUE ? money : Integer.MAX_VALUE));
    145. }
    146.  
    147. /**
    148.   * Takes from the specified player with the given name the given amount of money.
    149.   * <p>
    150.   * Automatically caps the money at 0.
    151.   * @param String name
    152.   * @param Integer amount
    153.   */
    154. public static void takeMoney(String name, int amount) {
    155. int money = getMoney(name) - amount;
    156. setMoney(name, (money >= 0 ? money : 0));
    157. }
    158.  
    159. /**
    160.   * Takes from the specified player the given amount of money.
    161.   * <p>
    162.   * Automatically caps the money at 0.
    163.   * @param Player player
    164.   * @param Integer amount
    165.   */
    166. public static void takeMoney(Player player, int amount) {
    167. int money = getMoney(getId(player)) - amount;
    168. setMoney(getId(player), (money >= 0 ? money : 0));
    169. }
    170. public static void saveMoneyValues() {
    171. for (String name : getMoneyMap().keySet()) {
    172. settings.getData().set(name+".Tokens", getMoney(name));
    173. }
    174. }



    Settings manager:
    Code:java
    1. public class SettingsManager {
    2.  
    3. private SettingsManager() { }
    4.  
    5. static SettingsManager instance = new SettingsManager();
    6.  
    7. public static SettingsManager getInstance() {
    8. return instance;
    9. }
    10.  
    11. Plugin p;
    12.  
    13. FileConfiguration config;
    14. File cfile;
    15.  
    16. FileConfiguration data;
    17. File dfile;
    18.  
    19. public void setup(Plugin p) {
    20. cfile = new File(p.getDataFolder(), "config.yml");
    21. config = p.getConfig();
    22. //config.options().copyDefaults(true);
    23. //saveConfig();
    24.  
    25. if (!p.getDataFolder().exists()) {
    26. p.getDataFolder().mkdir();
    27. }
    28.  
    29. dfile = new File(p.getDataFolder(), "money.yml");
    30.  
    31. if (!dfile.exists()) {
    32. try {
    33. dfile.createNewFile();
    34. }
    35. catch (IOException e) {
    36. Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create money.yml!");
    37. }
    38. }
    39.  
    40. data = YamlConfiguration.loadConfiguration(dfile);
    41. }
    42.  
    43. public FileConfiguration getData() {
    44. return data;
    45. }
    46.  
    47. public void saveData() {
    48. try {
    49. data.save(dfile);
    50. }
    51. catch (IOException e) {
    52. Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save money.yml!");
    53. }
    54. }
    55.  
    56. public void reloadData() {
    57. data = YamlConfiguration.loadConfiguration(dfile);
    58. }
    59.  
    60. public FileConfiguration getConfig() {
    61. return config;
    62. }
    63.  
    64. public void saveConfig() {
    65. try {
    66. config.save(cfile);
    67. }
    68. catch (IOException e) {
    69. Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not save config.yml!");
    70. }
    71. }
    72.  
    73. public void reloadConfig() {
    74. config = YamlConfiguration.loadConfiguration(cfile);
    75. }
    76.  
    77. public PluginDescriptionFile getDesc() {
    78. return p.getDescription();
    79. }
    80.  


    NOW: two questions
    1. Im horrible at configs, so I need help saving the players money to a config, so he can keep his money after logging off

    2. How can I make a admin command to give myself coins without having the right amount

    ERROR: I cant see to get /take to work, for some reason in order to take coins from someone I have to have the same amount that I want to take
     
  2. Offline

    Funergy

    XgXXSnipz
    Use MySQL, its really not hard. and is faster (I think) but if you know how to use it. when he joins you get the coins from the database (if he contains in the database) then put the coins into a HashMap -> we do that because we don't need to connect to the database every transaction with your coins. and when you do a transaction or you take money get the uuid of that player in the HashMap update their coins. and when they leave then update his coins from the HashMap in the Database

    And about the /take please send us the error from the console
     
  3. Offline

    Skionz

    I have a MySQL version of this that I can send you. I'm to lazy to even read the problem lol
     
  4. Offline

    XgXXSnipz

  5. Offline

    Skionz

    XgXXSnipz Give me a few hours I'm at school atm lol
     
  6. Offline

    XgXXSnipz

  7. Offline

    teej107

    XgXXSnipz Your first class's code is curving A LOT.
     
  8. Offline

    mythbusterma

    Funergy

    In what instance is any SQL server faster for this application, I challenge you to find me benchmarks stating that this is faster than the equivilant code in YAML.

    XgXXSnipz

    Use YAML, it's faster and easier to work with. There's nothing wrong with using YAML for this.
     
  9. Offline

    97WaterPolo

    XgXXSnipz
    I agree with mythbusterma, there is no point of storing this data to a database unless you plan to display it with stats on a website or sync them across multiple servers, YAML will be your best bet. If you don't want to create a custom config file, you can just use the default config.yml that is part of the API. Yaml is 10x easier to work with IMO for a situation like this.
     
  10. Offline

    Funergy

    mythbusterma People told me that. let me check my threads.
     
Thread Status:
Not open for further replies.

Share This Page