Custom config player data saving

Discussion in 'Plugin Development' started by Greeniousity, Mar 31, 2024.

  1. Offline

    Greeniousity

    Well, spigot couldnt find the issue so I came here.
    The thing is that, this plugin needs to edit player levels when it reaches a certain exp, exp is gained when a mob is killed.
    Its all in the code.
    The issue is that when I do anything, i level up. Nothing goes into the config neither the player data not the sections.

    https://paste.myst.rs/db1o8ks4
     
  2. Offline

    timtower Administrator Administrator Moderator

    And where do you save the data?
     
  3. Offline

    Greeniousity

    players.yml
    Code:
    players:
      player:
        main:
          required: 20
          level: 0
          boost: 1
          exp: 0
     
  4. Offline

    timtower Administrator Administrator Moderator

    I mean: when do you write to the file? And when do you check for changes?
     
  5. Offline

    Greeniousity

    I update playerData on level up and on entity kill, then on quit I save it the the config and retrieve it on join using config.set

    Nice profile picture btw
     
  6. Offline

    timtower Administrator Administrator Moderator

    You save when somebody quits, the plugin disabled.
    When do you look at the config to see if the values in it change?

    And thanks, somebody made it for me
     
  7. Offline

    Greeniousity

    The config is generated but for some reason its all empty, sorry i forgot to mention that.
     
  8. Offline

    timtower Administrator Administrator Moderator

    When are you checking that?
    With the server stopped?
    User logged out?
    Or just after the action?
     
  9. Offline

    Greeniousity

    User logged out

    On user logout it inserts the sections players.Greeniousity.main...
    On enable it generates the config
    on join if their section is not created, its created
    These are in the pastemyst i sent.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
    EDIT by me: alright sorry
     
    Last edited: Apr 1, 2024
  10. Offline

    timtower Administrator Administrator Moderator

    I know, and I wanted to know when YOU looked at it.
    But you answered that as well now.


    FileConfiguration player; is not being used.
    I can't find anything that saves
    private static Map<String, playerData> playerData = new HashMap<>();
     
  11. Offline

    Greeniousity

    I need to save it on disable right?
     
  12. Offline

    timtower Administrator Administrator Moderator

    Whenever you want it to be saved.
     
  13. Offline

    Greeniousity

    I spotted something: On first join if config does not contain a section fro player, player's data is updated but the config isnt: so i did this:
    Code:
        @EventHandler
        private void onJoinEvent(PlayerJoinEvent event)
        {
            playerData data = new playerData();
            File dat = new File(getDataFolder().getAbsolutePath() + "/players.yml");
            FileConfiguration conf = YamlConfiguration.loadConfiguration(dat);
            if(conf.contains("players." + event.getPlayer().getUniqueId().toString()))
            {
                data.setLevel(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.level"));
                data.setReq(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.required"));
                data.setExp(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.exp"));
                data.setBoost(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.boost"));
            } else {
                data.setLevel(1);
                data.setReq(50);
                data.setExp(0);
                data.setBoost(1);
                conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.level", data.getLevel());
                conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.required", data.getReq());
                conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.exp", data.getExp());
                conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.boost", data.getBoost());
            }
            command.setPlayerData(event.getPlayer(), data);
     
  14. Offline

    timtower Administrator Administrator Moderator

    @Greeniousity Considered saving the file?
    And don't need to create the config values when they join.
     
  15. Offline

    Greeniousity

    But config values are unique for all players, , though i needed to create them on first join.
    and i added a conf.save(dat); after
    conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.boost", data.getBoost());
     
  16. Offline

    timtower Administrator Administrator Moderator

    You don't need to save them on first join, your plugin will set the values anyways.
     
  17. Offline

    Greeniousity

    file is saved on quit, thats right. To summarize, the issue is with inserting sections into the confnig and retrieving them.
    But I have no idea what's the exact issue thats causing it
     
  18. Offline

    timtower Administrator Administrator Moderator

    How many config instances do you use? One or multiple?
     
  19. Offline

    Greeniousity

  20. Offline

    timtower Administrator Administrator Moderator

    Please post your new code.
    And mention where you store the data to the actual file.
     
  21. Offline

    Greeniousity

    What do you mean by actual file? Like the default congif.yml
    and There isnt much change in the code I kept adding stuff and deleted them because it wasnt the case
     
  22. Offline

    timtower Administrator Administrator Moderator

    You changed plenty of stuff, I want to see the actual code to see what you changed and what you have right now.

    And you are writing to a file somewhere, I want to see how you do that.
     
  23. Offline

    Greeniousity

    Code:
       @EventHandler
        public void onBlockBreak(BlockBreakEvent event)
        {
            BlockData bdata = event.getBlock().getBlockData();
            if(bdata instanceof Ageable){
                Ageable age = (Ageable) bdata;
                if(age.getAge() == age.getMaximumAge())
                {
                    playerData data = command.getPlayerData(event.getPlayer()); //remove if needed
                    Player player = event.getPlayer();
                    int currentPoints = data.getExp();
                    int booster = data.getBoost();
                    int pointsToAdd = 4 * booster;
                    //level related
                    int currentLevel = data.getLevel();
                    int newLevel = currentLevel + 1;
                    //end of level related
                    int totalPoints = pointsToAdd + currentPoints;
                    int playerReq = data.getReq();
                    data.setExp(totalPoints);
                    player.sendTitle("§e§l+" + pointsToAdd, "§6§l" + currentLevel + " §8§l>> " + "§a" + totalPoints + "§7/§a" + playerReq, 1, 20, 1);
                    player.playSound(player.getLocation() ,"entity.experience_orb.pickup", 20, 300);
                    if(totalPoints >= playerReq)
                    {// Get player's current level or 0 if not found
                        int newReq = playerReq + 50;
                        data.setLevel(newLevel); // Update player's level
                        data.setExp(0); // Reset player's points to 0
                        data.setReq(newReq);
                        player.sendTitle("§6§lLEVEL UP!", "§8You are now §dLvl. " + currentLevel, 1, 20, 1);
                        player.playSound(player.getLocation() ,"ui.toast.challenge_complete", 20, 300);
                    }
    
                }
            }
        }
    This is where I edit the values, getter and setter.
    And I got rid of:
    Code:
        FileConfiguration player;
    
        public FileConfiguration getData() {
            return this.player;
        }
    since there werent any usages
     
  24. Offline

    timtower Administrator Administrator Moderator

    That is not the full code
     
  25. Offline

    Greeniousity

    Code:
    package me.altug.levelingsystem;
    
    import me.altug.levelingsystem.data.playerData;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.block.data.Ageable;
    import org.bukkit.block.data.BlockData;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.BlockBreakEvent;
    import org.bukkit.event.entity.EntityDeathEvent;
    import org.bukkit.event.inventory.InventoryClickEvent;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    public class command implements Listener, CommandExecutor {
        private static Map<String, playerData> playerData = new HashMap<>();
    
    
    
        public static playerData getPlayerData(Player player)
        {
            if(!playerData.containsKey(player.getUniqueId().toString()))
            {
                playerData data =  new playerData();
                playerData.put(player.getUniqueId().toString(), data);
                return data;
            }
            return playerData.get(player.getUniqueId().toString());
    
        }
    
        public static void setPlayerData(Player player, playerData data)
        {
            playerData.put(player.getUniqueId().toString(), data);
        }
    
        public static void resPlayerData(Player player)
        {
            playerData.remove(player.getUniqueId().toString());
        }
    
        //separatoooooooooooooooooooooooooooaaaaaaaaaaaaaaaaaaaaar//
        final private String invLevel = "Level Progress";
    
        public command(Leveling_System plugin)
        {
            Bukkit.getPluginManager().registerEvents(this, plugin);
        }
    
    
    
        @EventHandler
        public void onInventoryClick(InventoryClickEvent event)
        {
            if (!event.getView().getTitle().equals(invLevel))
            {
                return;
            }
    
            Player player = (Player) event.getWhoClicked();
            int slot = event.getSlot();
            event.setCancelled(true);
        }
    
        @EventHandler
        public void onBlockBreak(BlockBreakEvent event)
        {
            BlockData bdata = event.getBlock().getBlockData();
            if(bdata instanceof Ageable){
                Ageable age = (Ageable) bdata;
                if(age.getAge() == age.getMaximumAge())
                {
                    playerData data = command.getPlayerData(event.getPlayer()); //remove if needed
                    Player player = event.getPlayer();
                    int currentPoints = data.getExp();
                    int booster = data.getBoost();
                    int pointsToAdd = 4 * booster;
                    //level related
                    int currentLevel = data.getLevel();
                    int newLevel = currentLevel + 1;
                    //end of level related
                    int totalPoints = pointsToAdd + currentPoints;
                    int playerReq = data.getReq();
                    data.setExp(totalPoints);
                    player.sendTitle("§e§l+" + pointsToAdd, "§6§l" + currentLevel + " §8§l>> " + "§a" + totalPoints + "§7/§a" + playerReq, 1, 20, 1);
                    player.playSound(player.getLocation() ,"entity.experience_orb.pickup", 20, 300);
                    if(totalPoints >= playerReq)
                    {// Get player's current level or 0 if not found
                        int newReq = playerReq + 50;
                        data.setLevel(newLevel); // Update player's level
                        data.setExp(0); // Reset player's points to 0
                        data.setReq(newReq);
                        player.sendTitle("§6§lLEVEL UP!", "§8You are now §dLvl. " + currentLevel, 1, 20, 1);
                        player.playSound(player.getLocation() ,"ui.toast.challenge_complete", 20, 300);
                    }
    
                }
            }
        }
    
        @EventHandler
        public void onEntityDeath(EntityDeathEvent event)
        {
            if("Dead Mobius".equals(event.getEntity().getCustomName()))
            {
                if(event.getEntity().getKiller() instanceof Player)
                {
                    Player player = (Player) event.getEntity().getKiller();
                    playerData data = command.getPlayerData(event.getEntity().getKiller()); //remove if needed
                    int currentPoints = data.getExp();
                    int booster = data.getBoost();
                    int pointsToAdd = 4 * booster;
                    //level related
                    int currentLevel = data.getLevel();
                    int newLevel = currentLevel + 1;
                    //end of level related
                    int totalPoints = pointsToAdd + currentPoints;
                    int playerReq = data.getReq();
                    data.setExp(totalPoints);
                    player.sendTitle("§e§l+" + pointsToAdd, "§6§l" + currentLevel + " §8§l>> " + "§a" + totalPoints + "§7/§a" + playerReq, 1, 20, 1);
                    player.playSound(player.getLocation() ,"entity.experience_orb.pickup", 20, 300);
                    if(totalPoints >= playerReq)
                    {// Get player's current level or 0 if not found
                        int newReq = playerReq + 50;
                        data.setLevel(newLevel); // Update player's level
                        data.setExp(0); // Reset player's points to 0
                        data.setReq(newReq);
                        player.sendTitle("§6§lLEVEL UP!", "§8You are now §dLvl. " + currentLevel, 1, 20, 1);
                        player.playSound(player.getLocation() ,"ui.toast.challenge_complete", 20, 300);
                        }
                }
            }
        }
        @Override
        public boolean onCommand(CommandSender sender, Command comm, String label, String [] args) {
            if(!(sender instanceof Player))
            {
                sender.sendMessage("Console cannot execute this");
                return true;
            }
            Player player = (Player) sender;
            Inventory inv = Bukkit.createInventory(player, 9 * 3, invLevel);
            playerData data = command.getPlayerData(player);
            player.openInventory(inv);
    
            int currentExperience = data.getExp();
            int playerReq = data.getReq();
            int currentLevel = data.getLevel();
            int nextLevel = currentLevel + 1;
            int booster = data.getBoost();
            inv.setItem(13, getItem(new ItemStack(Material.BOOK), "&aLevel progress", "&6&l" + currentLevel + " &8&l>> &r&d&n" + nextLevel, "&a" + currentExperience + "&7/&a" + playerReq));
            inv.setItem(22, getItem(new ItemStack(Material.SLIME_BALL), "&dBooster", "&6&lActive: &d" + booster + "x &a&nXP Multiplier" ));
            return true;
        }
    
        private ItemStack getItem(ItemStack item, String name, String ... lore)
        {
            ItemMeta meta = item.getItemMeta();
            meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
            List<String> lores = new ArrayList<>();
            for (String s : lore)
            {
                lores.add(ChatColor.translateAlternateColorCodes('&', s));
            }
            meta.setLore(lores);
    
            item.setItemMeta(meta);
    
            return item;
    
        }
    }
    
    Code:
    package me.altug.levelingsystem;
    import me.altug.levelingsystem.data.playerData;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.configuration.file.YamlConfiguration;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.event.player.PlayerQuitEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    
    import java.io.File;
    import java.io.IOException;
    
    
    public final class Leveling_System extends JavaPlugin implements Listener {
    
        @Override
        public void onEnable() {
            // Plugin startup logic
            createCustomConfig();
            getCommand("level").setExecutor(new command(this));
        }
        private void createCustomConfig()
        {
            File createDataFile = new File(getDataFolder(), "players.yml");
            if(!createDataFile.exists())
            {
                createDataFile.getParentFile().mkdirs();
                saveResource("players.yml", false);
            }
        }
    
        @Override
        public void onDisable() {
            saveConfig();
        }
        @EventHandler
        private void onJoinEvent(PlayerJoinEvent event)
        {
            playerData data = new playerData();
            File dat = new File(getDataFolder().getAbsolutePath() + "/players.yml");
            FileConfiguration conf = YamlConfiguration.loadConfiguration(dat);
            if(conf.contains("players." + event.getPlayer().getUniqueId().toString()))
            {
                data.setLevel(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.level"));
                data.setReq(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.required"));
                data.setExp(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.exp"));
                data.setBoost(conf.getInt("players." + event.getPlayer().getUniqueId().toString() + ".main.boost"));
            } else {
                data.setLevel(1);
                data.setReq(50);
                data.setExp(0);
                data.setBoost(1);
    
    
            }
            command.setPlayerData(event.getPlayer(), data);
    
        }
        @EventHandler
        private void onQuit(PlayerQuitEvent event)
        {
            playerData data = command.getPlayerData(event.getPlayer());
            File dat = new File(getDataFolder().getAbsolutePath() + "/players.yml");
            FileConfiguration conf = YamlConfiguration.loadConfiguration(dat);
            conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.level", data.getLevel());
            conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.required", data.getReq());
            conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.exp", data.getExp());
            conf.set("players." + event.getPlayer().getUniqueId().toString() + ".main.boost", data.getBoost());
            try {
                conf.save(dat);
            } catch
            (IOException e){
                e.printStackTrace();
            }
            command.resPlayerData(event.getPlayer());
        }
    }
    
    Code:
    package me.altug.levelingsystem.data;
    
    public class playerData {
        private int playerLevel;
        private int playerExperience;
        private int playerRequired;
        private int playerBooster;
    
    
        public int getLevel() {
            return playerLevel;
        }
        public void setLevel(int amount) {
            this.playerLevel = playerLevel;
        }
    
        public int getExp() {
            return playerExperience;
        }
        public void setExp(int amount) {
            this.playerExperience = playerExperience;
        }
        public int getReq() {
            return playerRequired;
        }
        public void setReq(int amount) {
            this.playerRequired = playerExperience;
        }
        public int getBoost() {
            return playerBooster;
        }
        public void setBoost(int amount) {
            this.playerBooster = playerBooster;
        }
    }
     
  26. Offline

    timtower Administrator Administrator Moderator

    That is the danger of 2 classes that use listeners.
    You can forget to register your main class as one. (This is why I wanted the full code)
    And saveConfig does nothing for you btw (onDisable)
     
  27. Offline

    Greeniousity

    I couldn't understand I what you meant by forgetting to register the main class as one. Do I have to register the main class differently than others?
     
  28. Offline

    timtower Administrator Administrator Moderator

    You only register the command class.
    Not the main class.
    You need to register both

    AKA:
    Where is this line for the main class?
    Bukkit.getPluginManager().registerEvents(this, plugin);
     
    Last edited: Apr 1, 2024
  29. Offline

    Greeniousity

    plugin apppears in red, anything I have to import?
     
  30. Offline

    timtower Administrator Administrator Moderator

    Plugin is sending an error log in your server console.
    Start by looking there, it says what is wrong.
     

Share This Page