Solved Block in World guard region

Discussion in 'Spigot Plugin Development' started by TheSupreme, Apr 18, 2017.

  1. Alright, in theory this should work, but it doesn't.
    Code (Text):
        public static boolean canBuild(Player player, Block block) {
            PlayerObject playerObject = Main.Players.get(player.getName());

            if (playerObject.canBuild == false)
                return false;

            Location location = block.getLocation();
            com.sk89q.worldguard.protection.managers.RegionManager regionManager = Plugins.getWorldGuard().getRegionManager(location.getWorld());
            ApplicableRegionSet regionsAtLocation = regionManager.getApplicableRegions(location);

            for (ProtectedRegion region : regionsAtLocation) {
               
                if (!TerritoryManager.Territories.containsKey(region.getId()))
                {
                    player.sendMessage(region.getId());
                    return false;
                }
               
                TerritoryObject territoryObject = TerritoryManager.Territories.get(region.getId());
               
                if (playerObject.getClanId().equals(territoryObject.getOwner()))
                {
                    return true;
                }
               
                return false;
            }
            return true;
        }
    I get this error:
    Code (Text):
    [10:55:58 WARN]: [Empires] Task #45 for Empires v1.0 generated an exception
    java.lang.NullPointerException
            at net.prickledpvp.empires.RegionManager.inTerritory(RegionManager.java:35) ~[?:?]
            at net.prickledpvp.empires.Update.update(Update.java:11) ~[?:?]
            at net.prickledpvp.empires.Main$1.run(Main.java:37) ~[?:?]
            at org.bukkit.craftbukkit.v1_11_R1.scheduler.CraftTask.run(CraftTask.java:71) ~[spigot.jar:git-Spigot-54ec0b8-1ac133e]
            at org.bukkit.craftbukkit.v1_11_R1.scheduler.CraftScheduler.mainThreadHeartbeat(CraftScheduler.java:353) [spigot.jar:git-Spigot-54ec0b8-1ac133e]
            at net.minecraft.server.v1_11_R1.MinecraftServer.D(MinecraftServer.java:738) [spigot.jar:git-Spigot-54ec0b8-1ac133e]
            at net.minecraft.server.v1_11_R1.DedicatedServer.D(DedicatedServer.java:399) [spigot.jar:git-Spigot-54ec0b8-1ac133e]
            at net.minecraft.server.v1_11_R1.MinecraftServer.C(MinecraftServer.java:678) [spigot.jar:git-Spigot-54ec0b8-1ac133e]
            at net.minecraft.server.v1_11_R1.MinecraftServer.run(MinecraftServer.java:576) [spigot.jar:git-Spigot-54ec0b8-1ac133e]
            at java.lang.Thread.run(Unknown Source) [?:1.8.0_121]
     
  2. Your error is in a completely different method: RegionManager.inTerritory(RegionManager.java:35)

    Post the class RegionManager and mark Line 35 please
     
  3. Code (Text):
    public static Boolean inTerritory(Player player)
        {
            // wrapping the player and getting its position again
           
            Vector pos = Plugins.getWorldGuard().wrapPlayer(player).getPosition();
            World w = Bukkit.getWorld("world");
            com.sk89q.worldguard.protection.managers.RegionManager manager  = Plugins.getWorldGuard().getRegionManager(w);
            // pre initialization of the region
            ProtectedRegion inTerritory = null;

            ApplicableRegionSet regionSet = manager.getApplicableRegions(pos);
            for(ProtectedRegion r : regionSet) {
                if(r.contains(pos)) {
                    inTerritory = r;
                    break;
                }
            }
           
            PlayerObject playerObject = Main.Players.get(player.getName());

            if(inTerritory == null) {
                if (!playerObject.lastTerritory.equals("")) /*########## LINE 35 ##########*/
                    {
                    player.sendMessage("┬žeLeaving " + playerObject.lastTerritory + "!");
                    playerObject.lastTerritory = "";
                    playerObject.canBuild = false;
                    playerObject.inOwnTerritory = false;
                    }
                return false;
            }

            /* In region */
            if (!TerritoryManager.Territories.containsKey(inTerritory.getId()))
            {
                player.sendMessage(inTerritory.getId());
                return false;
            }
           
            TerritoryObject territoryObject = TerritoryManager.Territories.get(inTerritory.getId());
           
            if (!playerObject.lastTerritory.equals(territoryObject.getName()))
                player.sendMessage("┬žaEntering " + territoryObject.getName() + "!");
           
            playerObject.lastTerritory = territoryObject.getName();
           
            if (playerObject.getClanId().equals(territoryObject.getOwner()))
            {
                playerObject.canBuild = true;
                playerObject.inOwnTerritory = true;
                return true;
            }
           
            playerObject.canBuild = false;
            playerObject.inOwnTerritory = false;
            return true;
        }
    }
     
  4. regionmanager works fine.
    It's checking if blocks are outside of the current region that doesn't.
     
  5. Either playerObject or lastTerritory is null. Add some checks an print them to the console.
     
  6. Code (Text):
    Location location = block.getLocation();
            com.sk89q.worldguard.protection.managers.RegionManager regionManager = Plugins.getWorldGuard().getRegionManager(location.getWorld());
            ApplicableRegionSet regionsAtLocation = regionManager.getApplicableRegions(location);

            for (ProtectedRegion region : regionsAtLocation) {
               
                if (!TerritoryManager.Territories.containsKey(region.getId()))
                {
                    player.sendMessage(region.getId());
                    return false;
                }
               
                TerritoryObject territoryObject = TerritoryManager.Territories.get(region.getId());
               
                if (playerObject.getClanId().equals(territoryObject.getOwner()))
                {
                    return true;
                }
               
                return false;
            }
    Adding this code creates the errors. Without this, everything works completely as intended.
     
  7. Your code is pretty messy. And I prefer a more object-orientated approach, and so should you. I managed to scrap this together, by looking at the code and seeing what you might want. You of course would have to edit it. And please stop the static scrap, makes me pretty sick ;).

    Your loop basically isn't looping...

    Pastebin, Hastebin, or view raw code below:
    Code (Text):
    package wg;

    import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
    import com.sk89q.worldguard.protection.ApplicableRegionSet;
    import com.sk89q.worldguard.protection.managers.RegionManager;
    import com.sk89q.worldguard.protection.regions.ProtectedRegion;
    import org.bukkit.Bukkit;
    import org.bukkit.Location;
    import org.bukkit.block.Block;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.Plugin;
    import java.util.HashMap;
    import java.util.Map;

    /**
    * Project created by ExpDev
    */


    public class WgTest2 {

        // I prefer a more object orientated approach rather than static abuse
        private Map<String, TerritoryObject> territories;

        /**
         * main constructor for class
         */
        public WgTest2() {
            this.territories = new HashMap<>();
        }

        /**
         * @return Map containing the territories and its appropriate [String] ID
         */
        public Map<String, TerritoryObject> getTerritories() {
            return territories;
        }

        /**
         * Executes when the programs runs
         */
        public static boolean main(String[] strings) {
            // init of main class
            WgTest2 main = new WgTest2();

            // init of world guard plugin and checking if it is enabled or not
            WorldGuardPlugin wg = main.getWorldGuard();
            if (wg == null) {
                return false;
            }

            // just a player created from my name
            Player player = Bukkit.getPlayer("ExpDev");
            // random block :)
            Block block = Bukkit.getWorld("world").getBlockAt(0, 0, 0);

            // the player object representation
            PlayerObject playerObject = new PlayerObject();

            // can they build? if no, return false!
            if (!playerObject.canBuild()) {
                return false;
            }

            // relevant location to use for operation
            Location location = block.getLocation();

            // the region manager for the location's world. if it doesn't exist return false
            RegionManager regionManager = wg.getRegionManager(location.getWorld());
            if (regionManager == null) {
                return false;
            }

            // pre-init of territory object
            TerritoryObject territoryObject = null;
            // applicable regions to given location (location)
            ApplicableRegionSet regionsAtLocation = regionManager.getApplicableRegions(location);
            // looping through all the [protected] applicable regions at that location
            for (ProtectedRegion region : regionsAtLocation) {
                // if the the territories map does not contain the region id, then continue search for it
                if (!main.getTerritories().containsKey(region.getId())) {
                    player.sendMessage(region.getId());
                    continue;
                }
                // we found it, perform proper init
                territoryObject = main.getTerritories().get(region.getId());
            }

            // if territoryObject does not (not found) = null and the clanId = the owner of the territory return true
            return territoryObject != null && playerObject.getClanId().equals(territoryObject.getOwner());

        }

        /**
         * Get the world guard plugin instance
         * @return The world guard plugin instance (null if not found)
         */
        private WorldGuardPlugin getWorldGuard() {
            Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");

            // WorldGuard may not be loaded
            if (plugin == null || !(plugin instanceof WorldGuardPlugin)) {
                return null; // Maybe you want throw an exception instead
            }
            return (WorldGuardPlugin) plugin;
        }

    }
     
    Code should be well documented enough for you to understand it. And cleaned it up.
     
  8. Curious why static isn't a good practice? It seems much simpler?
    Also it's not intended to loop but rather just check if a block is inside a region when broke.
    Code (Text):
        @EventHandler
        public void buildEvent(BlockPlaceEvent event)
        {
            event.setCancelled(!BuildManager.canBuild(event.getPlayer(), event.getBlock()));
        }
       
        @EventHandler
        public void buildEvent(BlockBreakEvent event)
        {
            event.setCancelled(!BuildManager.canBuild(event.getPlayer(), event.getBlock()));
        }
     
  9. I prefer singletons over statics. I don't know why, I think SOMEBODY ONCE TOLD ME (sorry) that static is slightly dirty and uses way more resources. Using alot of statics would be way more inefficient than using alot of singletons. I think.
     
  10. http://stackoverflow.com/questions/752758/is-using-a-lot-of-static-methods-a-bad-thing
    Because you're writing in a object orientated language, and constant use of static defeats the object orientated side of it.
    Then why have a loop? :p
     
  11. I'm unsure how this is a loop?
    Code (Text):
        public static boolean canBuild(Player player, Block block) {
            PlayerObject playerObject = Main.Players.get(player.getName());

            if (playerObject.canBuild == false)
                return false;

            Location location = block.getLocation();

            // the region manager for the location's world. if it doesn't exist return false
            com.sk89q.worldguard.protection.managers.RegionManager regionManager = Plugins.getWorldGuard().getRegionManager(location.getWorld());
            if (regionManager == null) {
                return false;
            }

            // pre-init of territory object
            TerritoryObject territoryObject = null;
            // applicable regions to given location (location)
            ApplicableRegionSet regionsAtLocation = regionManager.getApplicableRegions(location);
            // looping through all the [protected] applicable regions at that location
            for (ProtectedRegion region : regionsAtLocation) {
                // if the the territories map does not contain the region id, then continue search for it
                if (!TerritoryManager.Territories.containsKey(region.getId())) {
                    player.sendMessage(region.getId());
                    continue;
                }
                // we found it, perform proper init
                territoryObject = TerritoryManager.Territories.get(region.getId());
            }

            // if territoryObject does not (not found) = null and the clanId = the owner of the territory return true
            return territoryObject != null && playerObject.getClanId().equals(territoryObject.getOwner());
        }
     
  12. Read the comments and you see why I did it like I did.