LeavesDecayModule.java (2349B)
1 package poppy.modules; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Collections; 6 import java.util.List; 7 8 import org.bukkit.Tag; 9 import org.bukkit.block.Block; 10 import org.bukkit.block.BlockFace; 11 import org.bukkit.block.data.type.Leaves; 12 import org.bukkit.event.EventHandler; 13 import org.bukkit.event.Listener; 14 import org.bukkit.event.block.BlockBreakEvent; 15 import org.bukkit.event.block.LeavesDecayEvent; 16 import org.bukkit.plugin.Plugin; 17 18 public class LeavesDecayModule implements Listener 19 { 20 private static final int DELAY = 25; 21 private static final List<BlockFace> NEIGHBORS = Arrays.asList( 22 BlockFace.UP, 23 BlockFace.NORTH, 24 BlockFace.EAST, 25 BlockFace.SOUTH, 26 BlockFace.WEST, 27 BlockFace.DOWN 28 ); 29 30 private Plugin plugin; 31 private List<Block> scheduled = new ArrayList<>(); 32 33 public LeavesDecayModule(Plugin plugin) 34 { 35 this.plugin = plugin; 36 } 37 38 @EventHandler 39 public void onBlockBreak(BlockBreakEvent event) 40 { 41 onBlockRemove(event.getBlock()); 42 } 43 44 @EventHandler 45 public void onLeavesDecay(LeavesDecayEvent event) 46 { 47 onBlockRemove(event.getBlock()); 48 } 49 50 private void onBlockRemove(Block block) 51 { 52 if(!Tag.LOGS.isTagged(block.getType()) && !Tag.LEAVES.isTagged(block.getType())) 53 { 54 return; 55 } 56 57 Collections.shuffle(NEIGHBORS); 58 59 for(BlockFace face : NEIGHBORS) 60 { 61 final Block neighbor = block.getRelative(face); 62 63 if(!Tag.LEAVES.isTagged(neighbor.getType())) 64 { 65 continue; 66 } 67 68 Leaves leaves = (Leaves) neighbor.getBlockData(); 69 70 if(leaves.isPersistent()) 71 { 72 continue; 73 } 74 75 if(scheduled.contains(neighbor)) 76 { 77 continue; 78 } 79 80 plugin.getServer().getScheduler().runTaskLater(plugin, () -> decay(neighbor), DELAY); 81 82 scheduled.add(neighbor); 83 } 84 } 85 86 private boolean decay(Block block) 87 { 88 scheduled.remove(block); 89 90 if(!block.getWorld().isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) 91 { 92 return false; 93 } 94 95 if(!Tag.LEAVES.isTagged(block.getType())) 96 { 97 return false; 98 } 99 100 Leaves leaves = (Leaves) block.getBlockData(); 101 102 if(leaves.isPersistent()) 103 { 104 return false; 105 } 106 107 if(leaves.getDistance() < 7) 108 { 109 return false; 110 } 111 112 LeavesDecayEvent event = new LeavesDecayEvent(block); 113 plugin.getServer().getPluginManager().callEvent(event); 114 115 if(event.isCancelled()) 116 { 117 return false; 118 } 119 120 block.breakNaturally(); 121 122 return true; 123 } 124 }