Java Code Examples for org.bukkit.event.EventPriority

The following are top voted examples for showing how to use org.bukkit.event.EventPriority. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: HCFCore   File: SignSubclaimListener.java   Source Code and License 7 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
        return;

    Player player = event.getPlayer();
    if (player.getGameMode() == GameMode.CREATIVE && player.hasPermission(ProtectionListener.PROTECTION_BYPASS_PERMISSION)) {
        return;
    }

    if (plugin.getEotwHandler().isEndOfTheWorld()) {
        return;
    }

    Block block = event.getClickedBlock();
    if (!this.isSubclaimable(block)) {
        return;
    }

    if (!this.checkSubclaimIntegrity(player, block)) {
        event.setCancelled(true);
        player.sendMessage(ChatColor.RED + "You do not have access to this subclaimed " + block.getType().toString() + '.');
    }
}
 
Example 2
Project: HCFCore   File: ConquestTracker.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerDeath(PlayerDeathEvent event) {
    Faction currentEventFac = plugin.getTimerManager().getEventTimer().getEventFaction();
    if (currentEventFac instanceof ConquestFaction) {
        Player player = event.getEntity();
        PlayerFaction playerFaction = plugin.getFactionManager().getPlayerFaction(player);
        if (playerFaction != null && SettingsYML.CONQUEST_POINT_LOSS_PER_DEATH > 0) {
            int oldPoints = getPoints(playerFaction);
            if (oldPoints == 0) return;

            int newPoints = takePoints(playerFaction, SettingsYML.CONQUEST_POINT_LOSS_PER_DEATH);
            event.setDeathMessage(null); // for some reason if it isn't handled manually, weird colour coding happens
            Bukkit.broadcastMessage(ChatColor.YELLOW + "[" + currentEventFac.getName() + "] " +
                    ChatColor.GOLD + playerFaction.getName() + " lost " +
                    SettingsYML.CONQUEST_POINT_LOSS_PER_DEATH + " points because " + player.getName() + " died." +
                    ChatColor.AQUA + " (" + newPoints + '/' + SettingsYML.CONQUEST_REQUIRED_WIN_POINTS + ')' + ChatColor.YELLOW + '.');
        }
    }
}
 
Example 3
Project: bskyblock   File: IslandGuard1_9.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionSplash(final LingeringPotionSplashEvent e) {
    if (DEBUG) {
        plugin.getLogger().info("1.9 " + e.getEventName());
        plugin.getLogger().info("1.9 entity = " + e.getEntity());
        plugin.getLogger().info("1.9 entity type = " + e.getEntityType());
        plugin.getLogger().info("1.9 radius = " + e.getAreaEffectCloud().getRadius());
        plugin.getLogger().info("1.9 id = " + e.getAreaEffectCloud().getEntityId());
        plugin.getLogger().info("1.9 hit entity = " + e.getHitEntity());
    }
    if (!Util.inWorld(e.getEntity().getLocation())) {
        return;
    }
    // Try to get the shooter
    Projectile projectile = e.getEntity();
    plugin.getLogger().info("shooter = " + projectile.getShooter());
    if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
        UUID uuid = ((Player)projectile.getShooter()).getUniqueId();
        // Store it and remove it when the effect is gone
        thrownPotions.put(e.getAreaEffectCloud().getEntityId(), uuid);
        plugin.getServer().getScheduler().runTaskLater(plugin, () -> thrownPotions.remove(e.getAreaEffectCloud().getEntityId()), e.getAreaEffectCloud().getDuration());
    }
}
 
Example 4
Project: HCFCore   File: EnderPearlTimer.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onInventoryClick(InventoryClickEvent event) {
    HumanEntity humanEntity = event.getWhoClicked();
    if (humanEntity instanceof Player) {
        Player player = (Player) humanEntity;
        PearlNameFaker pearlNameFaker = itemNameFakes.get(player.getUniqueId());
        if (pearlNameFaker == null)
            return;

        // Required to prevent ghost items.
        int heldSlot = player.getInventory().getHeldItemSlot();
        if (event.getSlot() == heldSlot) {
            pearlNameFaker.setFakeItem(CraftItemStack.asNMSCopy(player.getItemInHand()), heldSlot);
        } else if (event.getHotbarButton() == heldSlot) {
            pearlNameFaker.setFakeItem(CraftItemStack.asNMSCopy(event.getCurrentItem()), event.getSlot());
            new BukkitRunnable() {
                @Override
                public void run() {
                    player.updateInventory();
                }
            }.runTask(plugin);
        }
    }
}
 
Example 5
Project: Chambers   File: EnderpearlListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPearlClip(PlayerTeleportEvent event) {
	if (event.getCause() == PlayerTeleportEvent.TeleportCause.ENDER_PEARL) {
		Location to = event.getTo();
		if (blockedPearlTypes.contains(to.getBlock().getType())) {
			Player player = event.getPlayer();
			player.sendMessage(ChatColor.RED + "You cannot pearl there.");
			removeCooldown(player);
			event.setCancelled(true);

			return;
		}
		to.setX(to.getBlockX() + 0.5D);
		to.setZ(to.getBlockZ() + 0.5D);
		event.setTo(to);

	}
}
 
Example 6
Project: HCFCore   File: BorderListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerMove(final PlayerMoveEvent event) {
    final Location from = event.getFrom();
    final Location to = event.getTo();
    if (from.getBlockX() == to.getBlockX() && from.getBlockZ() == to.getBlockZ()) {
        return;
    }
    if (!isWithinBorder(to) && isWithinBorder(from)) {
        final Player player = event.getPlayer();
        player.sendMessage(ChatColor.RED + "You cannot go past the border.");
        event.setTo(from);
        final Entity vehicle = player.getVehicle();
        if (vehicle != null) {
            vehicle.eject();
            vehicle.teleport(from);
            vehicle.setPassenger((Entity)player);
        }
    }
}
 
Example 7
Project: HCFCore   File: EventSignListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled=true, priority=EventPriority.HIGHEST)
public void onBlockBreak(BlockBreakEvent event)
{
  Block block = event.getBlock();
  if (isEventSign(block))
  {
    BlockState state = block.getState();
    Sign sign = (Sign)state;
    ItemStack stack = new ItemStack(Material.SIGN, 1);
    ItemMeta meta = stack.getItemMeta();
    meta.setDisplayName(EVENT_SIGN_ITEM_NAME);
    meta.setLore(Arrays.asList(sign.getLines()));
    stack.setItemMeta(meta);
    
    Player player = event.getPlayer();
    World world = player.getWorld();
    Location blockLocation = block.getLocation();
    if ((player.getGameMode() != GameMode.CREATIVE) && (world.isGameRule("doTileDrops"))) {
      world.dropItemNaturally(blockLocation, stack);
    }
    event.setCancelled(true);
    block.setType(Material.AIR);
    state.update();
  }
}
 
Example 8
Project: NeverLag   File: TilesLimiter.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlaceHopper(final BlockPlaceEvent e) {
	if (!cm.tileLimitEnabled) {
		return;
	}
	if (e.getBlock().getType() == Material.HOPPER) {
		Player p = e.getPlayer();
		if (p.isOp()) {
			return;
		}
		int limit = NeverLagUtils.getMaxPermission(p, "neverlag.limit.hopper.");
		if (limit <= 0) {
			limit = cm.tileLimitDefaultHopper;
		}
		if (isLimit(e.getBlock().getLocation(), Material.HOPPER, limit)) {
			e.setCancelled(true);
			p.sendMessage(i18n.tr("message", limit));
		}
	}
}
 
Example 9
Project: ProjectAres   File: RaindropListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL)
public void kill(final MatchPlayerDeathEvent event) {
    if(!event.isChallengeKill()) return;

    // Death raindrops are given by the backend, to reduce API usage

    final int raindrops = calculateRaindrops(
        event.getKiller(),
        RaindropConstants.KILL_REWARD,
        false,
        1
    );

    event.setRaindrops(raindrops);

    final MatchPlayer killer = event.getOnlineKiller();
    if(killer != null) {
        RaindropUtil.showRaindrops(
            killer.getBukkit(),
            raindrops,
            RaindropUtil.calculateMultiplier(event.getKiller().getPlayerId()),
            new TranslatableComponent("match.kill.killed", event.getVictim().getComponentName())
        );
    }
}
 
Example 10
Project: HCFCore   File: EntityLimitListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onCreatureSpawn(CreatureSpawnEvent event) {
    if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SLIME_SPLIT) { // allow slimes to always split
        return;
    }

    switch (event.getSpawnReason()) {
    case NATURAL:
        if (event.getLocation().getChunk().getEntities().length > MAX_NATURAL_CHUNK_ENTITIES) {
            event.setCancelled(true);
        }
        break;
    case CHUNK_GEN:
        if (event.getLocation().getChunk().getEntities().length > MAX_CHUNK_GENERATED_ENTITIES) {
            event.setCancelled(true);
        }
        break;
    default:
        break;
    }
}
 
Example 11
Project: NeverLag   File: AntiPlaceDoorDupe.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlace(BlockPlaceEvent e) {
	if (!cm.isAntiPlaceDoorDupe) {
		return;
	}
	// 判断手里的物品是否为门
	if (e.getItemInHand().getType() == Material.WOOD_DOOR || e.getItemInHand().getType() == Material.IRON_DOOR) {
		// 清理所在区块的甘蔗掉落物
		for (Entity entity : e.getPlayer().getLocation().getChunk().getEntities()) {
			if (entity instanceof Item) {
				Material itemType = ((Item) entity).getItemStack().getType();
				if (itemType == Material.SUGAR_CANE || itemType == Material.CACTUS) {
					entity.remove();
				}
			}
		}
	}
}
 
Example 12
Project: HCFCore   File: InvincibilityTimer.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    World world = player.getWorld();
    Location location = player.getLocation();
    Collection<ItemStack> drops = event.getDrops();
    if (!drops.isEmpty()) {
        Iterator<ItemStack> iterator = drops.iterator();

        // Drop the items manually so we can add meta to prevent
        // PVP Protected players from collecting them.
        long stamp = System.currentTimeMillis() + +ITEM_PICKUP_DELAY;
        while (iterator.hasNext()) {
            itemUUIDPickupDelays.put(world.dropItemNaturally(location, iterator.next()).getUniqueId(), stamp);
            iterator.remove();
        }
    }

    clearCooldown(player);
}
 
Example 13
Project: HCFCore   File: ExpMultiplierListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerFish(PlayerFishEvent event) {
    double amount = event.getExpToDrop();
    if (amount > 0) {
        amount = Math.ceil(amount * SettingsYML.EXP_MULTIPLIER_FISHING);
        ProjectileSource projectileSource = event.getHook().getShooter();
        if (projectileSource instanceof Player) {
            ItemStack stack = ((Player) projectileSource).getItemInHand();
            int enchantmentLevel = stack.getEnchantmentLevel(Enchantment.LUCK);
            if (enchantmentLevel > 0L) {
                amount = Math.ceil(amount * (enchantmentLevel * SettingsYML.EXP_MULTIPLIER_LUCK_PER_LEVEL));
            }
        }

        event.setExpToDrop((int) amount);
    }
}
 
Example 14
Project: SurvivalAPI   File: RiskyRetrievalModule.java   Source Code and License 6 votes vote down vote up
/**
 * Add ore to chest on drop
 *
 * @param event Item spawn event instance
 */
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event)
{
    if (event.getEntityType() != EntityType.DROPPED_ITEM
            || Meta.hasMeta(event.getEntity().getItemStack())
            || event.getEntity().hasMetadata("playerDrop"))
        return;

    for (int i = 0; i < MATERIALS.length; i++)
    {
        ItemStack stack = event.getEntity().getItemStack();

        if (MATERIALS[i] != stack.getType())
            continue;

        ItemStack newStack = stack.clone();
        this.inventory.addItem(Meta.addMeta(newStack));
        event.getEntity().setItemStack(Meta.addMeta(event.getEntity().getItemStack()));
    }
}
 
Example 15
Project: NeverLag   File: AntiUseEggsChangeSpawnerType.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent e) {
	if (!cm.isDisableChangeSpawnerType) {
		return;
	}
	if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
		if (e.getClickedBlock().getType() == Material.MOB_SPAWNER) {
			if (e.getItem() == null) {
				return;
			}
			if (e.getPlayer().isOp()) {
				return;
			}
			if (e.getItem().getType() == Material.MONSTER_EGG || e.getItem().getType() == Material.MONSTER_EGGS) {
				e.setCancelled(true);
			}
		}
	}
}
 
Example 16
Project: NeverLag   File: TilesLimiter.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlaceDispenser(final BlockPlaceEvent e) {
	if (!cm.tileLimitEnabled) {
		return;
	}
	if (e.getBlock().getType() == Material.DISPENSER) {
		Player p = e.getPlayer();
		if (p.isOp()) {
			return;
		}
		int limit = NeverLagUtils.getMaxPermission(p, "neverlag.limit.dispenser.");
		if (limit <= 0) {
			limit = cm.tileLimitDefaultDispenser;
		}
		if (isLimit(e.getBlock().getLocation(), Material.DISPENSER, limit)) {
			e.setCancelled(true);
			p.sendMessage(i18n.tr("message", limit));
		}
	}
}
 
Example 17
Project: RPGInventory   File: PetListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) {
    Player player = event.getPlayer();
    if (!InventoryManager.playerIsLoaded(player)) {
        return;
    }

    PlayerWrapper playerWrapper = InventoryManager.get(player);
    if (playerWrapper.hasPet() && playerWrapper.getPet().getPassenger() != player) {
        LivingEntity petEntity = playerWrapper.getPet();
        PetType pet = PetManager.getPetFromEntity(petEntity, player);
        if (pet != null && pet.getRole() != PetType.Role.COMPANION) {
            EntityUtils.goPetToPlayer(player, petEntity);
        }
    }
}
 
Example 18
Project: ProjectAres   File: ServerVisibilityCommands.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void hideAbandonedServer(PlayerQuitEvent event) {
    final Server local = minecraftService.getLocalServer();

    if(local.startup_visibility() != ServerDoc.Visibility.PUBLIC &&      // If server was initially not public and
       local.visibility() == ServerDoc.Visibility.PUBLIC &&              // server was made public and
       event.getPlayer().hasPermission(VISIBILITY_PERMISSION)) {    // someone with perms to do that is leaving...

        // ...check if there is still someone online with that permission
        for(Player player : event.getPlayer().getServer().getOnlinePlayers()) {
            // If someone else with perms is online, we're cool
            if(player != event.getPlayer() && player.hasPermission(VISIBILITY_PERMISSION)) return;
        }

        // If nobody with perms is online, make the server non-public again
        logger.info("Reverting server visibility to " + local.startup_visibility() + " because nobody with permissions is online");
        setVisibility(local.startup_visibility());
    }
}
 
Example 19
Project: SurvivalPlus   File: FoodDiversityConsume.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onConsumeCake(PlayerInteractEvent event)
{
	if(event.isCancelled()) return;
	Player player = event.getPlayer();
	if(event.hasBlock() && event.getAction().equals(Action.RIGHT_CLICK_BLOCK))
	{
		Block cake = event.getClickedBlock();
		if(cake.getType().equals(Material.CAKE_BLOCK))
		{
			if(player.getFoodLevel() < 20 && (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE))
			{
				addStats(player, carbon, 171);
				addStats(player, protein, 114);
				addStats(player, salts, 3);
			}
		}
	}
}
 
Example 20
Project: HCFCore   File: CoreListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onEntityChangeBlock(final EntityChangeBlockEvent event) {
    final Entity entity = event.getEntity();
    if (entity instanceof LivingEntity && !attemptBuild(entity, event.getBlock().getLocation(), null)) {
        event.setCancelled(true);
    }
}
 
Example 21
Project: HCFCore   File: CreativeClickListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onInventoryCreative(InventoryCreativeEvent event) {
    HumanEntity humanEntity = event.getWhoClicked();
    if (humanEntity instanceof Player && !humanEntity.hasPermission("base.command.gamemode")) {
        event.setCancelled(true);
       // humanEntity.sendMessage(ChatColor.RED + "You are not allowed to be in gamemode! Setting you to default gamemode!");
        humanEntity.setGameMode(GameMode.SURVIVAL);
    }
}
 
Example 22
Project: HCFCore   File: ProtectionListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
    if (!event.hasBlock()) {
        return;
    }

    Block block = event.getClickedBlock();
    Action action = event.getAction();
    if (action == Action.PHYSICAL) { // Prevent players from trampling on crops or pressure plates, etc.
        if (!attemptBuild(event.getPlayer(), block.getLocation(), null)) {
            event.setCancelled(true);
        }
    } else if (action == Action.RIGHT_CLICK_BLOCK) {
        boolean canBuild = !BLOCK_INTERACTABLES.contains(block.getType());

        // Special case for cauldron
        if (canBuild) {
            Material itemType = event.hasItem() ? event.getItem().getType() : null;
            if (itemType != null && ITEM_BLOCK_INTERACTABLES.containsKey(itemType) && ITEM_BLOCK_INTERACTABLES.get(itemType).contains(event.getClickedBlock().getType())) {
                if (block.getType() != Material.WORKBENCH || !event.getPlayer().hasPermission("utilities.openchestsilent") || !plugin.getFactionManager().getFactionAt(block).isSafezone()) {
                    canBuild = false;
                }
            } else {
                MaterialData materialData = block.getState().getData();
                if (materialData instanceof Cauldron) {
                    Cauldron cauldron = (Cauldron) materialData;
                    if (!cauldron.isEmpty() && event.hasItem() && event.getItem().getType() == Material.GLASS_BOTTLE) {
                        canBuild = false;
                    }
                }
            }
        }

        if (!canBuild && !attemptBuild(event.getPlayer(), block.getLocation(), ChatColor.YELLOW + "You cannot do this in the territory of %1$s" + ChatColor.YELLOW + '.', true)) {
            event.setCancelled(true);
        }
    }
}
 
Example 23
Project: UltraCore   File: Events.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onThunderChange(ThunderChangeEvent event) {

    if (plugin.getConfig().getString("toggle.noweather").equals(true)) {
        boolean storm = event.toThunderState();
        if (storm)
            event.setCancelled(true);
    }
}
 
Example 24
Project: HCFCore   File: BorderListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onBucketEmpty(final PlayerBucketEmptyEvent event) {
    if (!isWithinBorder(event.getBlockClicked().getLocation())) {
        event.setCancelled(true);
        event.getPlayer().sendMessage(ChatColor.RED + "You cannot empty buckets past the border.");
    }
}
 
Example 25
Project: NeverLag   File: HotChunkHolder.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onUnloadChunk(ChunkUnloadEvent e) {
	if (!cm.hotChunkEnabled || NeverLag.getTpsWatcher().getAverageTPS() < cm.hotChunkTpsThreshold) {
		return;
	}
	ChunkInfo chunkInfo = new ChunkInfo(e.getChunk());
	if (hotChunkRecord.contains(chunkInfo)) {
		e.setCancelled(true);
		this.addHotChunkUnloadCount(chunkInfo);
	}
}
 
Example 26
Project: HCFCore   File: TeleportTimer.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) {
    Location from = event.getFrom();
    Location to = event.getTo();
    // Player didn't move a block.
    if (from.getBlockX() == to.getBlockX() && from.getBlockY() == to.getBlockY() && from.getBlockZ() == to.getBlockZ()) {
        return;
    }

    cancelTeleport(event.getPlayer(), ChatColor.YELLOW + "You moved a block, therefore cancelling your teleport.");
}
 
Example 27
Project: HCFCore   File: BottledExpListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onCraftItem(CraftItemEvent event) {
    HumanEntity humanEntity = event.getWhoClicked();
    if (humanEntity instanceof Player) {
        Player player = (Player) humanEntity;
        if (event.getSlotType() == InventoryType.SlotType.RESULT && isBottledExperience(event.getCurrentItem())) {
            player.setLevel(0);
            player.setExp(0);
        }
    }
}
 
Example 28
Project: HCFCore   File: FactionListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onFactionRenameMonitor(FactionRenameEvent event) {
    Faction faction = event.getFaction();
    if (faction instanceof KothFaction) {
        ((KothFaction) faction).getCaptureZone().setName(event.getNewName());
    }
}
 
Example 29
Project: ProjectAres   File: DamageDisplayPlayerFacet.java   Source Code and License 5 votes vote down vote up
@TargetedEventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onDamage(MatchPlayerDamageEvent event) {
    if(!event.isAttacker(attacker)) return;
    if(!(event.info() instanceof MeleeInfo)) return;
    // Absorbed damage is removed from the final value, so we add it back
    showDamage(event.victim().getBukkit(), event.cause().getFinalDamage() - event.cause().getDamage(EntityDamageEvent.DamageModifier.ABSORPTION));
}
 
Example 30
Project: HCFCore   File: ScoreboardHandler.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled=true, priority=EventPriority.MONITOR)
public void onFactionAllyCreate(FactionRelationCreateEvent event)
{
  Set<Player> updates = new HashSet(event.getSenderFaction().getOnlinePlayers());
  updates.addAll(event.getTargetFaction().getOnlinePlayers());
  for (PlayerBoard board : this.playerBoards.values()) {
    board.addUpdates(updates);
  }
}
 
Example 31
Project: skript-mirror   File: EvtByReflection.java   Source Code and License 5 votes vote down vote up
private static void registerEvent(Class<? extends Event> event, EventPriority priority) {
  PriorityListener listener = listeners[priority.ordinal()];
  Set<Class<? extends Event>> events = listener.getEvents();

  if (!events.contains(event)) {
    events.add(event);
    Bukkit.getPluginManager()
        .registerEvent(event, listener, priority, executor, SkriptMirror.getInstance());
  }
}
 
Example 32
Project: ProjectAres   File: DeathTracker.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerDamage(EntityDamageEvent event) {
    MatchPlayer victim = match.getParticipant(event.getEntity());
    if(victim == null) return;

    lastDamageInfos.put(victim, eventResolver.resolveDamage(event));
}
 
Example 33
Project: HCFCore   File: WorldListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onWitherChangeBlock(EntityChangeBlockEvent event) {
    Entity entity = event.getEntity();
    if (entity instanceof Wither || entity instanceof EnderDragon) {
        event.setCancelled(true);
    }
}
 
Example 34
Project: VoxelGamesLibv2   File: CommandHandler.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) {
    String label = event.getMessage().split(" ")[0].replace("/", "");
    if (!commands.containsKey(label)) {
        return;
    }

    if (commands.get(label).stream().noneMatch(phase -> phase.getGame().isPlaying(event.getPlayer().getUniqueId()))) {
        event.setCancelled(true);
        event.getPlayer().sendMessage("Unknown command. Type \"/help\" for help.");
    }
}
 
Example 35
Project: HCFCore   File: BlockHitFixListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = false, priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.hasBlock() && event.getAction() != Action.PHYSICAL) {
        if (NON_TRANSPARENT_ATTACK_INTERACT_TYPES.contains(event.getClickedBlock().getType())) {
            cancelAttackingMillis(event.getPlayer().getUniqueId(), THRESHOLD);
        }
    }
}
 
Example 36
Project: HCFCore   File: SkullListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
        Player player = event.getPlayer();
        BlockState state = event.getClickedBlock().getState();
        if (state instanceof Skull) {
            Skull skull = (Skull) state;
            player.sendMessage(ChatColor.YELLOW + "This is " + ChatColor.WHITE
                    + (skull.getSkullType() == SkullType.PLAYER && skull.hasOwner() ? skull.getOwner() : "a " + WordUtils.capitalizeFully(skull.getSkullType().name()) + " skull") + ChatColor.YELLOW
                    + '.');
        }
    }
}
 
Example 37
Project: ProjectAres   File: EnvironmentControlListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void interactEntity(PlayerInteractEvent event) {
    if(!event.getPlayer().isOp()) {
        event.setCancelled(true);
        event.setUseInteractedBlock(Event.Result.DENY);
        event.setUseItemInHand(Event.Result.DENY);
    }
}
 
Example 38
Project: AddGun   File: Guns.java   Source Code and License 5 votes vote down vote up
/**
 * Prevent using the gun-item to damage blocks (cancels even damaging)
 * @param event the damage event
 */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void preventBlockDamageWithGun(BlockDamageEvent event) {
	if (event.getItemInHand() == null)
		return;
	
	ItemStack item = event.getItemInHand();
	StandardGun gun = findGun(item);
	if (gun == null) // can't match it
		return;
	
	event.setCancelled(true);
}
 
Example 39
Project: HCFCore   File: WallBorderListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
    if (!this.useTaskInstead)
        return;
    BukkitTask task = wallBorderTask.remove(event.getPlayer().getUniqueId());
    if (task != null) {
        task.cancel();
    }
}
 
Example 40
Project: HCFCore   File: CoreListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event) {
    Player player = event.getPlayer();
    if (player.getWorld().getEnvironment() == World.Environment.NETHER && event.getBlock().getState() instanceof CreatureSpawner
            && !player.hasPermission(ProtectionListener.PROTECTION_BYPASS_PERMISSION)) {

        event.setCancelled(true);
        player.sendMessage(ChatColor.RED + "You may not place spawners in the nether.");
    }
}
 
Example 41
Project: emojix-spigot   File: SignEvent.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public final void onSignChange(SignChangeEvent event) {

	String[] lines = event.getLines();
	Player player = (Player) event.getPlayer();

	if (!player.hasPermission("emojix.sign.use"))
		return;

	/*
	 * This loop allows detection for emotes mixed with words and also
	 * eliminates emotes appearing in URL's - emotes must have a space on
	 * both sides if applicable
	 */
	for (Object obj : EmojiConfig.emoji.getConfigurationSection("emoji").getKeys(false)) {
		for (int i = 0; i < lines.length; i++) {

			String[] words = lines[i].split(" ");

			// If player has colored prefix we obtain that color
			String color = ChatColor.getLastColors(words[0]);

			for (String word : words) {

				// This is so the user can use an emoji singularly or at the start of line
				if (word == words[0])
					word = ChatColor.stripColor(word);

				if (word.equals(obj.toString()) && player.hasPermission("emojix.chat." + word))
					lines[i] = lines[i].replace(word,
							ChatColor.RESET + EmojiConfig.emoji.getString("emoji." + obj.toString()) + color);
			}

			event.setLine(i, lines[i]);
			// TODO: Plugin works as intended - 1. Fix any bugs should they occur 2. Add extra functionality
		}
	}
}
 
Example 42
Project: EchoPet   File: PetEntityListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
    Entity e = event.getEntity();
    if (ReflectionUtil.getEntityHandle(e) instanceof IEntityPet) {
        event.setCancelled(true);
    }
}
 
Example 43
Project: HCFCore   File: MinerClass.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerDamage(EntityDamageByEntityEvent event) {
    Entity entity = event.getEntity();
    if (entity instanceof Player && BukkitUtils.getFinalAttacker(event, false) != null) {
        Player player = (Player) entity;
        if (plugin.getPvpClassManager().hasClassEquipped(player, this)) {
            removeInvisibilitySafely(player);
        }
    }
}
 
Example 44
Project: ProjectAres   File: PGMListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void clearActiveEnderPearls(final PlayerDeathEvent event) {
    for(Entity entity : event.getEntity().getWorld().getEntitiesByClass(EnderPearl.class)) {
        if(((EnderPearl) entity).getShooter() == event.getEntity()) {
            entity.remove();
        }
    }
}
 
Example 45
Project: HCFCore   File: FactionListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onFactionRenameMonitor(FactionRenameEvent event) {
    Faction faction = event.getFaction();
    if (faction instanceof KothFaction) {
        ((KothFaction) faction).getCaptureZone().setName(event.getNewName());
    }
}
 
Example 46
Project: ProjectAres   File: ProjectileTrailMatchModule.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onProjectileLaunch(ProjectileLaunchEvent event) {
    match.player(event.getActor()).ifPresent(shooter -> {
        final Projectile projectile = event.getEntity();
        projectile.setMetadata(TRAIL_META, new FixedMetadataValue(PGM.get(), shooter.getParty().getFullColor()));
        // Set critical metadata to false in order to remove default particle trail.
        // The metadata will be restored just before the arrow hits something.
        if(projectile instanceof Arrow) {
            final Arrow arrow = (Arrow) projectile;
            arrow.setMetadata(CRITICAL_META, new FixedMetadataValue(PGM.get(), arrow.isCritical()));
            arrow.setCritical(false);
        }
    });
}
 
Example 47
Project: ZorahPractice   File: KitEditManager.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onThrow(ProjectileLaunchEvent event) {
    if (event.getEntity().getShooter() instanceof Player) {
        Player player = (Player) event.getEntity().getShooter();

        if (this.editKits.containsKey(player.getUniqueId())) {
            event.setCancelled(true);
        }
    }
}
 
Example 48
Project: ProjectAres   File: FriendlyFireRefundMatchModule.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL)
public void handleFriendlyFire(EntityDamageByEntityEvent event) {
    if(event.isCancelled() && event.getDamager() instanceof Arrow) {
        Arrow arrow = (Arrow) event.getDamager();
        if(arrow.getPickupRule() == Arrow.PickupRule.ALLOWED && arrow.getShooter() != null && arrow.getShooter() instanceof Player){
            Player owner = (Player) arrow.getShooter();
            owner.getInventory().addItem(new ItemStack(Material.ARROW));
            arrow.remove();
        }
    }
}
 
Example 49
Project: Kineticraft   File: Splef.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onDamage(EntityDamageEvent evt) { // Teleport a player out if they lose.
    if (evt.getCause() == EntityDamageEvent.DamageCause.LAVA && evt.getEntity() instanceof Player) {
        evt.getEntity().playEffect(EntityEffect.HURT);
        removePlayer((Player) evt.getEntity());
        Bukkit.getScheduler().runTask(Core.getInstance(), () -> evt.getEntity().setFireTicks(0)); // Must run a tick late.
    }
}
 
Example 50
Project: ProjectAres   File: TeamListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void addPlayersToRegisteredTeam(EntrantRegisterEvent event) throws EventException {
    event.yield();

    Match match = event.getTeam().getMatch();
    TeamMatchModule tmm = match.needMatchModule(TeamMatchModule.class);

    for(MatchPlayer player : match.getPlayers()) {
        if(event.getEntrant().members().contains(player.getPlayerId())) {
            tourney.getLogger().info("Adding player '" + player.getDisplayName() + "' to team '" + event.getTeam().getName() + "'");
            tmm.forceJoin(player, event.getTeam());
        }
    }
}
 
Example 51
Project: ProjectAres   File: SpawnMatchModule.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPartyChange(final PlayerChangePartyEvent event) throws EventException {
    final MatchPlayer player = event.getPlayer();
    if(event.getOldParty() == null) {
        // Join match
        event.yield();
        if(event.getNewParty().isParticipating()) {
            enterState(player, new Joining(player));
        } else {
            enterState(player, new Observing(player, true, true));
        }
    } else if(event.getNewParty() == null) {
        // Leave match
        leaveState(player);
    } else {
        // Party change during match
        withState(player, state -> {
            state.onEvent(event);
            if(hasQueuedTransitions(player)) {
                // If the party change caused a state transition, leave the old
                // state before the change, and enter the new state afterward.

                // The potential danger here is that the player has no spawn state
                // during the party change, while other events are firing. The
                // danger is minimized by listening at MONITOR priority.

                leaveState(player);
                event.yield();
                processQueuedTransitions(player);
            }
        });
    }
}
 
Example 52
Project: bskyblock   File: IslandGuard.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOW)
public void onShear(final PlayerShearEntityEvent e) {
    if (DEBUG) {
        plugin.getLogger().info(e.getEventName());
    }
    if (Util.inWorld(e.getPlayer())) {
        if (actionAllowed(e.getPlayer(), e.getEntity().getLocation(), SettingsFlag.SHEARING)) {
            return;
        }
        // Not allowed
        Util.sendMessage(e.getPlayer(), plugin.getLocale(e.getPlayer().getUniqueId()).get("island.protected"));
        e.setCancelled(true);
    }
}
 
Example 53
Project: HCFCore   File: InvincibilityTimer.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onItemPickup(PlayerPickupItemEvent event) {
    Player player = event.getPlayer();
    long remaining = getRemaining(player);
    if (remaining > 0L) {
        UUID itemUUID = event.getItem().getUniqueId();
        Long delay = itemUUIDPickupDelays.get(itemUUID);
        if (delay == null)
            return;

        // The item has been spawned for over the required pickup time for
        // PVP Protected players, let them pick it up.
        long millis = System.currentTimeMillis();
        if ((delay - millis) > 0L) {
            event.setCancelled(true);

            // Don't let the pickup event spam the player.
            List<MetadataValue> value = player.getMetadata(ITEM_PICKUP_MESSAGE_META_KEY);
            if (value != null && !value.isEmpty() && value.get(0).asLong() - millis <= 0L) {
                player.setMetadata(ITEM_PICKUP_MESSAGE_META_KEY, new FixedMetadataValue(plugin, millis + ITEM_PICKUP_MESSAGE_DELAY));
                player.sendMessage(ChatColor.RED + "You cannot pick this item up for another " + ChatColor.BOLD + DurationFormatUtils.formatDurationWords(remaining, true, true) + ChatColor.RED
                        + " as your " + getDisplayName() + ChatColor.RED + " timer is active [" + ChatColor.BOLD + DurationFormatter.getRemaining(remaining, true, false) + ChatColor.RED
                        + " remaining]");
            }
        } else
            itemUUIDPickupDelays.remove(itemUUID);
    }
}
 
Example 54
Project: NetworkAnalytics   File: AnalyticsListener.java   Source Code and License 5 votes vote down vote up
@Override
public void setup(@Nonnull TerminableConsumer consumer) {
    Events.subscribe(PlayerLoginEvent.class, EventPriority.MONITOR)
            .filter(e -> e.getResult() == PlayerLoginEvent.Result.ALLOWED)
            .handler(e -> {
                plugin.getDataManager().logPlayer(e.getPlayer().getUniqueId(), e.getPlayer().getName());
                Metadata.provideForPlayer(e.getPlayer()).put(NetworkAnalytics.CONNECTION_TIME_SECONDS, (System.currentTimeMillis() / 1000L));
            })
            .bindWith(consumer);

    Events.subscribe(PlayerJoinEvent.class, EventPriority.MONITOR)
            .handler(e -> {
                ProtocolVersion protocolVersion = ProtocolSupportAPI.getProtocolVersion(e.getPlayer());
                if (protocolVersion != null) {
                    Metadata.provideForPlayer(e.getPlayer()).put(NetworkAnalytics.PROTOCOL_VERSION, protocolVersion);
                }
            })
            .bindWith(consumer);

    Events.subscribe(PlayerQuitEvent.class)
            .handler(e -> {
                Long loginTime = Metadata.provideForPlayer(e.getPlayer()).getOrNull(NetworkAnalytics.CONNECTION_TIME_SECONDS);
                long now = System.currentTimeMillis() / 1000L;
                if (loginTime != null) {
                    long diff = now - loginTime;
                    int mins = (int) TimeUnit.SECONDS.toMinutes(diff);
                    if (mins > 0) {
                        plugin.getDataManager().incrementPlayerMinutesPlayed(e.getPlayer().getUniqueId(), mins);
                    }
                }
            })
            .bindWith(consumer);
}
 
Example 55
Project: CommandEdit-minecraftPlugin   File: CommandEditListener.java   Source Code and License 5 votes vote down vote up
@EventHandler( priority = EventPriority.HIGHEST )
public void onPlayerCommand( PlayerCommandPreprocessEvent event )
{
    String m = event.getMessage();
    
    // Debugging
    if( m_Base.isDebugging() ){ m_Base.getLogger().info( "Command Edit catched the following command: " + m ); }
    
    event.setCancelled( m_Processor.ProcessCommand( event ) );     
}
 
Example 56
Project: ProjectAres   File: NicknameCommands.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void sendNickReminderOnLogin(UserLoginEvent event) {
    if(event.getUser().nickname() != null) {
        if(event.getPlayer().hasPermission(PERMISSION_SET)) {
            audiences.get(event.getPlayer()).sendMessage(new TranslatableComponent(
                "nick.joinReminder",
                new Component("/nick", ChatColor.GOLD),
                new Component("/nick clear", ChatColor.GOLD)
            ));
        } else {
            set(event.getUser(), null, true);
        }
    }
}
 
Example 57
Project: HCFCore   File: CoreListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onHangingDamageByEntity(final EntityDamageByEntityEvent event) {
    final Entity entity = event.getEntity();
    if (entity instanceof Hanging) {
        final Player attacker = BukkitUtils.getFinalAttacker((EntityDamageEvent)event, false);
        if (!attemptBuild((Entity)attacker, entity.getLocation(), ChatColor.GRAY + "You may not build in the territory of %1$s" + ChatColor.GRAY + '.')) {
            event.setCancelled(true);
        }
    }
}
 
Example 58
Project: HCFCore   File: PlayerTimer.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onTimerExpireLoadReduce(TimerExpireEvent event) {
    if (event.getTimer() == this) {
        Optional<UUID> optionalUserUUID = event.getUserUUID();
        if (optionalUserUUID.isPresent()) {
            UUID userUUID = optionalUserUUID.get();
            onExpire(userUUID);
            clearCooldown(userUUID);
        }
    }
}
 
Example 59
Project: HCFCore   File: FactionListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onFactionRemove(FactionRemoveEvent event) {
    Faction faction = event.getFaction();
    if (faction instanceof PlayerFaction) {
        CommandSender sender = event.getSender();
        for (Player player : Bukkit.getOnlinePlayers()) {
            Relation relation = faction.getRelation(player);
            String msg = ChatColor.YELLOW + "The faction " + relation.toChatColour() + (player == null ? faction.getName() : faction.getName()) + ChatColor.YELLOW + " has been " + ChatColor.RED
                    + "disbanded" + ChatColor.YELLOW + " by " + ChatColor.AQUA + (sender instanceof Player ? ((Player) sender).getName() : sender.getName()) + ChatColor.YELLOW + '.';
            player.sendMessage(msg);
        }
    }
}
 
Example 60
Project: HCFCore   File: ClassLoad.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onEquipmentSet(EquipmentSetEvent event) {
    HumanEntity humanEntity = event.getHumanEntity();
    if (humanEntity instanceof Player) {
        this.attemptEquip((Player) humanEntity);
    }
}