Search code examples
javaminecraftbukkit

Java / bukkit: Run "For" method 1 time in runnable?


so I have this code:

                           ProtectedRegion region = WGBukkit.getRegionManager(p.getWorld()).getRegion("afk1mine");
                       Vector max = region.getMaximumPoint();
                       Vector min = region.getMinimumPoint();
                           for (int i = min.getBlockX(); i <= max.getBlockX();i++) {
                                 for (int j = min.getBlockY(); j <= max.getBlockY(); j++) {
                                   for (int k = min.getBlockZ(); k <= max.getBlockZ();k++) {
                                     final Block kasamas = Bukkit.getServer().getWorld("paradise").getBlockAt(i,j,k);
                                         //Bukkit.getPluginManager().callEvent(new BlockBreakEvent(kasamas, p));
                                         p.sendMessage(" kitas: " + kasamas); 
                                   }
                                 }
                               }   

And i do want to send the message only for the first block, then repeat the runnable in 1 second and send the message for the second block etc.


Solution

  • You need to increment the coordinates in the BukkitRunnable. Something like this would work, although I'll admit it's not very nice to look at.

    BukkitRunnable sendMessage = new BukkitRunnable() {
        final int minI = min.getBlockX(), minJ = min.getBlockY(), minK = min.getBlockZ();
        final int maxI = max.getBlockX(), maxJ = max.getBlockY(), maxK = max.getBlockZ();
        int i = minI, j = minJ, k = minK;
    
        @Override
        public void run() {
            final Block kasamas = Bukkit.getServer().getWorld("paradise").getBlockAt(i, j, k);
            p.sendMessage(" kitas: " + kasamas);
            if (k > maxK) {
                if (j > maxJ) {
                    if (i > maxI) {
                        cancel();
                    } else {
                        i++;
                        j = minJ;
                        k = minK;
                    }
                } else {
                    j++;
                    k = minK;
                }
            } else {
                k++;
            }
        }
    };
    sendMessage.runTaskTimer(plugin, 0, 20);
    

    This assumes that p is effectively final; otherwise, you may need to create an effectively final variable capturing it. Replace plugin with an instance of your plugin class.