[Tutorial] Scoreboards/Teams with the Bukkit API

Discussion in 'Resources' started by chasechocolate, Apr 5, 2013.

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

    SymbioteCodes

    I've read through many forum posts about how to set each Player's health below their name. This has certainly been the most helpful in learning about scoreboards in the first place, but I have been unsuccessful in displaying the player's health below their name. I just get 0.

    Here is my main class
    Code:
    package me.some.plugin;
    
    import java.io.File;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.scoreboard.DisplaySlot;
    import org.bukkit.scoreboard.Objective;
    import org.bukkit.scoreboard.Scoreboard;
    
    public class Main extends JavaPlugin {
    
    
        Config config;
        ChatHandler chatHandler;
        GameManager gm;
        ScoreboardMngr sMngr;
        Scoreboard board;
    
        public void onEnable() {
        
            if (new File(getDataFolder().toString()).exists() == false) {
                this.saveDefaultConfig();
            }
        
            board = Bukkit.getScoreboardManager().getNewScoreboard();
            board.registerNewObjective("showhealth", "health");
            Objective objective = board.getObjective("showhealth");
            objective.setDisplaySlot(DisplaySlot.BELOW_NAME);
            objective.setDisplayName(ChatColor.RED + "❤");
        
        
            config = new Config(this);
            chatHandler = new ChatHandler(this);
            gm = new GameManager(this);
            sMngr = new ScoreboardMngr(this);
        
            this.getCommand("list").setExecutor(new GameManager(this));
            this.getCommand("team").setExecutor(new TeamCmd(this));
            this.getCommand("showhealth").setExecutor(sMngr);
        
        
            Bukkit.getLogger().info("[Plugin] Enabled!");
        
        
        }
    
    
        public void onDisable() {
        
            Bukkit.getLogger().info("[Plugin] Disabled!");
        }
    
    }
    
    And here is ScoreboardMngr (Where I'm setting the scoreboard to players via both a command, and when a player logs in)

    Code:
    package me.some.plugin;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    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.player.PlayerLoginEvent;
    
    public class ScoreboardMngr implements CommandExecutor, Listener {
    
       Main plugin;
       Boolean showHealth;
    
    
       public ScoreboardMngr(Main plugin) {
         this.plugin = plugin;
         this.showHealth = true;
      
       }
    
       @EventHandler
       public void onPlayerJoin(PlayerLoginEvent event) {
         if (this.showHealth == true) {
           event.getPlayer().setScoreboard(plugin.board); // Added this in because I wasn't sure if PlayerLoginEvent would pick up all players including the account triggering the event...
           for (Player p : Bukkit.getOnlinePlayers()) {
             p.setScoreboard(plugin.board);
             p.setHealth(p.getHealth());
           }
         }
        
       }
    
    
    
    
       @Override
       public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
         if (!(sender instanceof Player)) {
           //Coming from console
           Bukkit.getLogger().info("Can't do that from console yet");
           return true;
        
         } else {
        
           Player p = (Player) sender;
        
           if (p.hasPermission("plugin.admin")) {
          
             if (args.length == 1) {
            
               if (args[0].equalsIgnoreCase("enable")) {
              
                 for (Player x : Bukkit.getOnlinePlayers()) {
                   x.setScoreboard(plugin.board);
                   x.setHealth(x.getHealth());
                
                 }
                 this.showHealth = true;
                 p.sendMessage(plugin.config.prefix + ChatColor.GRAY + "Player Health displayed!");
                 return true;
              
               } else if (args[0].equalsIgnoreCase("disable")) {
              
                 for (Player x : Bukkit.getOnlinePlayers()) {
                   x.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
                 }
                 this.showHealth = false;
                 p.sendMessage(plugin.config.prefix + ChatColor.GRAY + "Player Health hidden!");
                 return true;
              
               } else {
                 p.sendMessage(plugin.config.prefix + ChatColor.RED + "Usage: " + ChatColor.GOLD + "/showhealth " + ChatColor.YELLOW + "<enable|disable>");
                 return true;
               }
            
             } else {
               p.sendMessage(plugin.config.prefix + ChatColor.RED + "Usage: " + ChatColor.GOLD + "/showhealth " + ChatColor.YELLOW + "<enable|disable>");
               return true;
             }
          
           } else {
             p.sendMessage(plugin.config.prefix + uhc.config.permissionError);
             return true;
           }
        
         }
       }
    
    
    
    }
    
    
    Can anybody tell me why this isn't working? I feel like I've tried everything I know, I can't get it to display anything but 0.

    I'm using Bukkit 1.8 R0.1 Snapshot release.

    Any help would be very much appreciated!
     
    Last edited: Mar 14, 2015
  2. Offline

    RyuGamer97



    Hello there I have health plugin for my miss just do not have more options because only he got there I try to add more things as is done with the command block but I fail and only get errors might want to have fun?
     
  3. Offline

    Nokoa

    I was able to get it to work to my liking but it appears to cause massive lag, and I just don't understand why? Is anyone else experiencing this?
     
  4. Offline

    andreaskal

    this doesn't work for me! IDK why but in the console it says this:
    upload_2015-8-4_19-34-15.png
    and i have 3 classes:
    Code:Java
    1.  
    2. package me.Slastic.scoreboard2;
    3.  
    4. import org.bukkit.Bukkit;
    5. import org.bukkit.plugin.java.JavaPlugin;
    6. import org.bukkit.scoreboard.Objective;
    7. import org.bukkit.scoreboard.Scoreboard;
    8. import org.bukkit.scoreboard.ScoreboardManager;
    9. import org.bukkit.scoreboard.Team;
    10.  
    11. public class Scoreboard2 extends JavaPlugin {
    12.  
    13.  
    14. @Override
    15. public void onEnable() {
    16. this.getServer().getPluginManager().registerEvents(new team(), this);
    17. ScoreboardManager manager = Bukkit.getScoreboardManager();
    18. Scoreboard board = manager.getNewScoreboard();
    19.  
    20. Team team = board.registerNewTeam("team1");
    21. Objective objective = board.registerNewObjective("test", "dummy");
    22. }
    23. }
    24.  

    Code:java
    1.  
    2. package me.Slastic.scoreboard2;
    3.  
    4. import org.bukkit.ChatColor;
    5. import org.bukkit.entity.Player;
    6. import org.bukkit.event.EventHandler;
    7. import org.bukkit.event.Listener;
    8. import org.bukkit.event.player.PlayerJoinEvent;
    9. import org.bukkit.scoreboard.Score;
    10.  
    11. public class team implements Listener {
    12.  
    13. @EventHandler
    14. public void onPlayerJoin(PlayerJoinEvent e) {
    15. Player p = e.getPlayer();
    16. team.addPlayer(p);
    17.  
    18. Score score = objective.getScore(p);
    19. score.setScore(42); //Integer only!
    20.  
    21. Score score1 = objective.getScore(ChatColor.GREEN + "Kills:"); //Get a fake offline player
    22. score1.setScore(1);
    23. }
    24.  
    25. public static void addPlayer(Player player) {
    26. // TODO Auto-generated method stub
    27.  
    28. }
    29. }
    30.  


    Code:java
    1.  
    2. package me.Slastic.scoreboard2;
    3.  
    4. import org.bukkit.entity.Player;
    5. import org.bukkit.scoreboard.Score;
    6.  
    7. public class objective {
    8.  
    9. public static Score getScore(Player p) {
    10. // TODO Auto-generated method stub
    11. return null;
    12. }
    13.  
    14. public static Score getScore(String string) {
    15. // TODO Auto-generated method stub
    16. return null;
    17. }
    18.  
    19. }
    20.  


    thanks :D
     
  5. Offline

    megamichiel

    @andreaskal
    You seriously should consider learning java before using the bukkit API. A person with basic java knowledge would know the awnser to that
     
    sgavster and Synapz like this.
  6. Offline

    Synapz

    Lol don't use methods you haven't finished... Espically when you use return null in them. Null isn't a tool just to satisfy IDE errors. (They throw null pointer exceptions) I suggest you never return null unless you want it to and even then you should surround it in a try/catch and explicitly use "throws NullPonterExecption" in your method. How should you fix this? Don't return null!!
     
  7. Felt like I should post this code:


    Code:
    import java.util.AbstractMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import org.bukkit.Bukkit;
    import org.bukkit.OfflinePlayer;
    import org.bukkit.entity.Player;
    import org.bukkit.scoreboard.DisplaySlot;
    import org.bukkit.scoreboard.Objective;
    import org.bukkit.scoreboard.Scoreboard;
    import org.bukkit.scoreboard.Team;
    import com.google.common.base.Preconditions;
    import com.google.common.base.Splitter;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    public class SimpleScoreboard {
            private Scoreboard scoreboard;
            private String title;
            private Map<String, Integer> scores;
            private List<Team> teams;
            public SimpleScoreboard(String title) {
                    this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
                    this.title = title;
                    this.scores = Maps.newLinkedHashMap();
                    this.teams = Lists.newArrayList();
            }
            public void blankLine() {
                    add(" ");
            }
            public void add(String text) {
                    add(text, null);
            }
            public void add(String text, Integer score) {
                    Preconditions.checkArgument(text.length() < 48, "text cannot be over 48 characters in length");
                    text = fixDuplicates(text);
                    scores.put(text, score);
            }
            private String fixDuplicates(String text) {
                    while (scores.containsKey(text))
                            text += "§r";
                    if (text.length() > 48)
                            text = text.substring(0, 47);
                    return text;
            }
            private Map.Entry<Team, String> createTeam(String text) {
                    String result = "";
                    if (text.length() <= 16)
                            return new AbstractMap.SimpleEntry(null, text);
                    Team team = scoreboard.registerNewTeam("text-" + scoreboard.getTeams().size());
                    Iterator<String> iterator = Splitter.fixedLength(16).split(text).iterator();
                    team.setPrefix(iterator.next());
                    result = iterator.next();
                    if (text.length() > 32)
                            team.setSuffix(iterator.next());
                    teams.add(team);
                    return new AbstractMap.SimpleEntry(team, result);
            }
            public void build(Player p) {
                    Objective obj = scoreboard.registerNewObjective((title.length() > 16 ? title.substring(0, 15) : title), "dummy");
                    obj.setDisplayName(title);
                    obj.setDisplaySlot(DisplaySlot.SIDEBAR);
                    int index = scores.size();
                    for (Map.Entry<String, Integer> text : scores.entrySet()) {
                            Map.Entry<Team, String> team = createTeam(text.getKey());
                            Integer score = text.getValue() != null ? text.getValue() : index;
                            if (team.getKey() != null)
                                    team.getKey().addEntry(team.getValue());
                            obj.getScore(team.getValue()).setScore(score);
                            index -= 1;
                    }
            }
            public void reset() {
                    title = null;
                    scores.clear();
                    for (Team t : teams)
                            t.unregister();
                    teams.clear();
            }
            public Scoreboard getScoreboard() {
                    return scoreboard;
            }
            public void send(Player... players) {
                    for (Player p : players)
                            p.setScoreboard(scoreboard);
            }
    }
    The OP's code was using OfflinePlayers which really slowed it down. I got timings of up to 600ms. So I edited the code. Timings are about 4ms(per call to scoreboard.build()).
     
  8. Offline

    thorvaldemar

    Last edited: Dec 23, 2015
  9. Offline

    logabeast11

    public void manageScoreboard(PlayerJoinEvent e) {
    Player player = e.getPlayer();
    int cash = player.getInventory().getItem(265).getAmount();
    ScoreboardManager manager = Bukkit.getScoreboardManager();
    Scoreboard board = manager.getNewScoreboard();
    Objective obj = board.registerNewObjective("test", "dummy");
    obj.setDisplaySlot(DisplaySlot.SIDEBAR);
    obj.setDisplayName("Player Stats");
    Score money = obj.getScore(player);
    money.setScore(cash);
    player.setScoreboard(board);
    }
    For some reason, this won't work :/ can somebody help?
     
  10. Offline

    Zombie_Striker

    @logabeast11
    Are you sure you have the @EventHandler tag? Did you register the class?

    The player's inventory only has 36 slots. There is no slot 266. I think what you want is to get the item who's type id is 265. Is this correct? If so, please note you should no longer work with IDs and should instead use the MaterialEnums when getting the itemstack's material.
     
  11. Offline

    logabeast11

    first of all, thank you for responding, and yes i registered the class, and thanks, i was trying to get the type id
     
  12. Offline

    Zombie_Striker

    @logabeast11
    1. Create an integer that will store the amount of the item the player has in their inventory
    2. For loop through the inventory.
    3. If the item's material is equal to the one you are testing for
    4. add the amount to the integer
     
  13. Offline

    logabeast11

    so how would that look in my case? could you provide an example? Thanks
    EDIT: and btw the problem is that it wont display
     
    Last edited: Mar 1, 2016
  14. Offline

    logabeast11

  15. Offline

    GamerzKing

    We're not going to spoon feed you or give you an example. He gave you everything you'll need above. What are you having troubles with, and I can try and help?
     
  16. Offline

    logabeast11

    The actual scoreboard wont display
     
  17. Offline

    GamerzKing

    Show me your code and I can tell you why.
     
  18. Offline

    logabeast11

    public void manageScoreboard(PlayerJoinEvent e) {

    Player player = e.getPlayer();

    int cash = player.getInventory().getItem(265).getAmount();

    ScoreboardManager manager = Bukkit.getScoreboardManager();
    Scoreboard board = manager.getNewScoreboard();
    Objective obj = board.registerNewObjective("test", "dummy");
    obj.setDisplaySlot(DisplaySlot.SIDEBAR);
    obj.setDisplayName("Player Stats");
    Score money = obj.getScore(player);
    money.setScore(cash);
    player.setScoreboard(board);
    }
     
  19. Offline

    GamerzKing

    Are you getting any console errors? Also, the inventory only has 36 slots, not sure why you are trying to get an index of 265.
     
  20. Offline

    logabeast11

    @GamerzKing
    there are no console errors, and i was trying to get the item id, because the item enums wont work for me
     
  21. Offline

    teej107

    @logabeast11 Perhaps you should read the documentation on that method. It'll be very clear why enums don't work and will tell you what you are doing wrong as well.
     
  22. Offline

    Cool_Nick_Name

    If I use
    Code:
    player.setScoreboard(manager.getNewScoreboard());
    to clear the scoreboard, wouldn't this remove all scoreboards?

    Also, is it possible to have a scoreboard under the name of 1 player only, but that all other players can see it?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 1, 2016
  23. How can i ask help of a plugin? It gives me error!
     
  24. Offline

    PhantomUnicorns

    Create a help thread in plugin development here.
     
  25. Offline

    cabler

  26. Offline

    VentroxHD

    GREAT, it's working well. I searched for such a method over months
     
Thread Status:
Not open for further replies.

Share This Page