Java Code Examples for org.bukkit.event.EventHandler

The following examples show how to use org.bukkit.event.EventHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(EntityDamageEvent event) {
    Entity entity = event.getEntity();
    if (!(entity instanceof Player)) {
        return;
    }

    Player player = ((Player) entity).getPlayer();

    if (!Main.isPlayerInGame(player)) {
        return;
    }

    GamePlayer gPlayer = Main.getPlayerGameProfile(player);
    Game game = gPlayer.getGame();

    if (gPlayer.isSpectator) {
        return;
    }

    ArrowBlocker arrowBlocker = (ArrowBlocker) game.getFirstActivedSpecialItemOfPlayer(player, ArrowBlocker.class);
    if (arrowBlocker != null && event.getCause() == EntityDamageEvent.DamageCause.PROJECTILE) {
        event.setCancelled(true);
    }
}
 
Example 2
Source Project: GriefDefender   Source File: BlockEventHandler.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockDispense(BlockDispenseEvent event) {
    final Block block = event.getBlock();
    final World world = event.getBlock().getWorld();
    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(world.getUID())) {
        return;
    }

    final Location location = block.getLocation();
    final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(world.getUID());
    final GDChunk gpChunk = claimWorldManager.getChunk(block.getChunk());
    final GDPermissionUser user = gpChunk.getBlockOwner(location);
    if (user != null) {
        final BlockFace face = NMSUtil.getInstance().getFacing(block);
        final Location faceLocation = BlockUtil.getInstance().getBlockRelative(location, face);
        final GDClaim targetClaim = this.storage.getClaimAt(faceLocation);
        final ItemStack activeItem = user != null && user.getOnlinePlayer() != null ? NMSUtil.getInstance().getActiveItem(user.getOnlinePlayer()) : null;
        final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, targetClaim, Flags.INTERACT_BLOCK_SECONDARY, activeItem, event.getBlock(), user, TrustTypes.BUILDER, true);
        if (result == Tristate.FALSE) {
            event.setCancelled(true);
        } else {
            GDCauseStackManager.getInstance().pushCause(user);
        }
    }
}
 
Example 3
Source Project: PGM   Source File: AntiGriefListener.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void checkDefuse(final PlayerInteractEvent event) {
  ItemStack hand = event.getPlayer().getItemInHand();
  if (hand == null || hand.getType() != DEFUSE_ITEM) return;

  MatchPlayer clicker = this.mm.getPlayer(event.getPlayer());
  if (clicker != null
      && clicker.isObserving()
      && clicker.getBukkit().hasPermission(Permissions.DEFUSE)) {
    if (event.getAction() == Action.RIGHT_CLICK_AIR) {
      this.obsTntDefuse(clicker, event.getPlayer().getLocation());
    } else if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
      this.obsTntDefuse(clicker, event.getClickedBlock().getLocation());
    }
  }
}
 
Example 4
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerToggleFlight(final PlayerToggleFlightEvent event) {
  Player player = event.getPlayer();
  Jumper jumper = this.jumpers.get(player);
  if (jumper == null) return;

  if (event.isFlying()) {
    event.setCancelled(true);

    this.setCharge(jumper, 0f);
    this.refreshJump(player);

    // calculate jump
    Vector impulse = player.getLocation().getDirection();

    impulse.setY(0.75 + Math.abs(impulse.getY()) * 0.5);
    impulse.multiply(jumper.kit.power / 3f);
    event.getPlayer().setVelocity(impulse);

    player.getWorld().playSound(player.getLocation(), Sound.ZOMBIE_INFECT, 0.5f, 1.8f);
  }
}
 
Example 5
Source Project: PGM   Source File: FallTracker.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerSpleef(final PlayerSpleefEvent event) {
  MatchPlayer victim = event.getVictim();
  FallState fall = this.falls.get(victim);
  if (fall == null || !fall.isStarted) {
    if (fall != null) {
      // End the existing fall and replace it with the spleef
      endFall(fall);
    }

    fall = new FallState(victim, FallInfo.From.GROUND, event.getSpleefInfo());
    fall.isStarted = true;

    Location loc = victim.getBukkit().getLocation();
    fall.isClimbing = Materials.isClimbable(loc);
    fall.isSwimming = Materials.isWater(loc);
    fall.isInLava = Materials.isLava(loc);

    this.falls.put(victim, fall);

    logger.fine("Spleefed " + fall);
  }
}
 
Example 6
@EventHandler
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
    try {
        final Player player = event.getPlayer();
        final User user = User.getUser(player);
        final Entity rightClicked = event.getRightClicked();
        final Location location = rightClicked.getLocation();
        final IslandManager islandManager = IridiumSkyblock.getIslandManager();
        final Island island = islandManager.getIslandViaLocation(location);
        if (island == null) return;

        if (island.getPermissions(user).interact) return;

        event.setCancelled(true);
    } catch (Exception e) {
        IridiumSkyblock.getInstance().sendErrorMessage(e);
    }
}
 
Example 7
@EventHandler(priority = EventPriority.HIGHEST)
public void onInteract(final PlayerInteractEvent event) {
  if (cancelUnlessInteracting(event, event.getPlayer())) {
    // Allow the how-to book to be read
    if (event.getMaterial() == Material.WRITTEN_BOOK) {
      event.setUseItemInHand(Event.Result.ALLOW);
    }

    MatchPlayer player = match.getPlayer(event.getPlayer());
    if (player == null) return;

    ClickType clickType = convertClick(event.getAction(), event.getPlayer());
    if (clickType == null) return;

    match.callEvent(
        new ObserverInteractEvent(
            player, clickType, event.getClickedBlock(), null, event.getItem()));
  }
}
 
Example 8
Source Project: GriefDefender   Source File: CommandEventHandler.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChatPost(AsyncPlayerChatEvent event) {
    final Player player = event.getPlayer();
    final Iterator<Player> iterator = event.getRecipients().iterator();

    while (iterator.hasNext()) {
        final Player receiver = iterator.next();
        if (receiver == player) {
            continue;
        }

        final GDPlayerData receiverData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(receiver.getWorld(), receiver.getUniqueId());
        if (receiverData.isRecordingChat()) {
            iterator.remove();
            final String s = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage());
            final Component message = LegacyComponentSerializer.legacy().deserialize(s, '&');
            final Component component = TextComponent.builder()
                    .append(TextComponent.builder()
                            .append(message)
                            .hoverEvent(HoverEvent.showText(TextComponent.of(formatter.format(Instant.now()))))
                            .build())
                    .build();
            receiverData.chatLines.add(component);
        }
    }
}
 
Example 9
@EventHandler
public void onLaunchProjectile(ProjectileLaunchEvent event) {
    if (event.isCancelled()) {
        return;
    }

    Projectile projectile = event.getEntity();
    if (projectile.getShooter() instanceof Player) {
        Player damager = (Player) projectile.getShooter();
        if (Main.isPlayerInGame(damager)) {
            if (Main.getPlayerGameProfile(damager).isSpectator) {
                event.setCancelled(true);
            }
        }
    }
}
 
Example 10
Source Project: BedWars   Source File: WorldListener.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onCreatureSpawn(CreatureSpawnEvent event) {
    if (event.isCancelled() || event.getSpawnReason() == SpawnReason.CUSTOM) {
        return;
    }

    for (String gameName : Main.getGameNames()) {
        Game game = Main.getGame(gameName);
        if (game.getStatus() != GameStatus.DISABLED)
            // prevent creature spawn everytime, not just in game
            if (/*(game.getStatus() == GameStatus.RUNNING || game.getStatus() == GameStatus.GAME_END_CELEBRATING) &&*/ game.getOriginalOrInheritedPreventSpawningMobs()) {
                if (GameCreator.isInArea(event.getLocation(), game.getPos1(), game.getPos2())) {
                    event.setCancelled(true);
                    return;
                    //}
                } else /*if (game.getStatus() == GameStatus.WAITING) {*/
                    if (game.getLobbyWorld() == event.getLocation().getWorld()) {
                        if (event.getLocation().distanceSquared(game.getLobbySpawn()) <= Math
                                .pow(Main.getConfigurator().config.getInt("prevent-lobby-spawn-mobs-in-radius"), 2)) {
                            event.setCancelled(true);
                            return;
                        }
                    }
            }
    }
}
 
Example 11
@EventHandler
public void onEntityDamageEvent(EntityDamageEvent event) {
    final Entity damagee = event.getEntity();
    if (!(damagee instanceof Player)) return;
    final Player player = (Player) damagee;
    final User user = User.getUser(player);
    final Location damageeLocation = damagee.getLocation();
    final IslandManager islandManager = IridiumSkyblock.getIslandManager();
    final Island island = islandManager.getIslandViaLocation(damageeLocation);
    if (island == null) return;

    //The user is visiting this island, so disable damage
    if (user.islandID != island.getId() && IridiumSkyblock.getConfiguration().disablePvPOnIslands) {
        event.setCancelled(true);
    }

}
 
Example 12
@EventHandler
public void onPostAction(PostActionEvent event) {
    if (event.getFormat() != simpleGuiFormat) {
        return;
    }

    Player player = event.getPlayer();
    MapReader reader = event.getItem().getReader();
    if (reader.containsKey("team")) {
        Team team = (Team) reader.get("team");
        game.selectTeam(Main.getPlayerGameProfile(player), team.getName());
        player.closeInventory();

        repaint();
        openedForPlayers.remove(player);
    }
}
 
Example 13
Source Project: GriefDefender   Source File: WorldEventHandler.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onWorldSave(WorldSaveEvent event) {
    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(event.getWorld().getUID())) {
        return;
    }

    GDTimings.WORLD_SAVE_EVENT.startTiming();
    GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(event.getWorld().getUID());
    if (claimWorldManager == null) {
        GDTimings.WORLD_SAVE_EVENT.stopTiming();
        return;
    }

    claimWorldManager.save();

    GDTimings.WORLD_SAVE_EVENT.stopTiming();
}
 
Example 14
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void processBlockDamage(BlockDamageEvent event) {
  if (this.match.getWorld() != event.getBlock().getWorld()) return;

  Block block = event.getBlock();
  MaterialData material = block.getState().getData();
  MatchPlayer player = this.match.getPlayer(event.getPlayer());

  for (Destroyable destroyable : this.destroyables) {
    if (player != null
        && player.getParty() == destroyable.getOwner()
        && !destroyable.isDestroyed()
        && destroyable.getBlockRegion().contains(block)
        && destroyable.hasMaterial(material)) {

      event.setCancelled(true);
      // TODO: translate this
      player.sendWarning(TextComponent.of("You may not damage your own objective."));
    }
  }
}
 
Example 15
Source Project: PGM   Source File: CoreMatchModule.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void leakCheck(final BlockTransformEvent event) {
  if (event.getWorld() != this.match.getWorld()) return;

  if (event.getNewState().getType() == Material.STATIONARY_LAVA) {
    Vector blockVector = BlockVectors.center(event.getNewState()).toVector();
    for (Core core : this.cores) {
      if (!core.hasLeaked() && core.getLeakRegion().contains(blockVector)) {
        // core has leaked
        core.markLeaked();
        this.match.callEvent(new CoreLeakEvent(this.match, core, event.getNewState()));
        this.match.callEvent(
            new GoalCompleteEvent(
                this.match, core, core.getOwner(), false, core.getContributions()));
      }
    }
  }
}
 
Example 16
Source Project: PGM   Source File: KitMatchModule.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onGrenadeLaunch(final ProjectileLaunchEvent event) {
  if (event.getEntity().getShooter() instanceof Player) {
    Player player = (Player) event.getEntity().getShooter();
    ItemStack stack = player.getItemInHand();

    if (stack != null) {
      // special case for grenade arrows
      if (stack.getType() == Material.BOW) {
        int arrows = player.getInventory().first(Material.ARROW);
        if (arrows == -1) return;
        stack = player.getInventory().getItem(arrows);
      }

      Grenade grenade = Grenade.ITEM_TAG.get(stack);
      if (grenade != null) {
        grenade.set(PGM.get(), event.getEntity());
      }
    }
  }
}
 
Example 17
Source Project: BedWars   Source File: GolemListener.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onGolemDeath(EntityDeathEvent event) {
    if (!(event.getEntity() instanceof IronGolem)) {
        return;
    }

    IronGolem ironGolem = (IronGolem) event.getEntity();
    for (String name : Main.getGameNames()) {
        Game game = Main.getGame(name);
        if ((game.getStatus() == GameStatus.RUNNING || game.getStatus() == GameStatus.GAME_END_CELEBRATING) && ironGolem.getWorld().equals(game.getGameWorld())) {
            List<SpecialItem> golems = game.getActivedSpecialItems(Golem.class);
            for (SpecialItem item : golems) {
                if (item instanceof Golem) {
                    Golem golem = (Golem) item;
                    if (golem.getEntity().equals(ironGolem)) {
                        event.getDrops().clear();
                    }
                }
            }
        }
    }
}
 
Example 18
@EventHandler
public void onTeamChestBuilt(BedwarsPlayerBuildBlock event) {
    if (event.isCancelled()) {
        return;
    }

    Block block = event.getBlock();
    RunningTeam team = event.getTeam();

    if (block.getType() != Material.ENDER_CHEST) {
        return;
    }

    String unhidden = APIUtils.unhashFromInvisibleStringStartsWith(event.getItemInHand(), TEAM_CHEST_PREFIX);

    if (unhidden != null || Main.getConfigurator().config.getBoolean("specials.teamchest.turn-all-enderchests-to-teamchests")) {
        team.addTeamChest(block);
        String message = i18n("team_chest_placed");
        for (Player pl : team.getConnectedPlayers()) {
            pl.sendMessage(message);
        }
    }
}
 
Example 19
@EventHandler
public void onMove(PlayerMoveEvent event) {
    Player player = event.getPlayer();
    if (event.isCancelled() || !Main.isPlayerInGame(player)) {
        return;
    }

    if (event.getFrom().getBlock().equals(event.getTo().getBlock())) {
        return;
    }

    GamePlayer gPlayer = Main.getPlayerGameProfile(player);
    Game game = gPlayer.getGame();
    if (gPlayer.isSpectator) {
        return;
    }

    WarpPowder warpPowder = (WarpPowder) game.getFirstActivedSpecialItemOfPlayer(player, WarpPowder.class);
    if (warpPowder != null) {
        warpPowder.cancelTeleport(true, true);
    }
}
 
Example 20
Source Project: BedWars   Source File: TrapListener.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onTrapBuild(BedwarsPlayerBuildBlock event) {
    if (event.isCancelled()) {
        return;
    }

    ItemStack trapItem = event.getItemInHand();
    String unhidden = APIUtils.unhashFromInvisibleStringStartsWith(trapItem, TRAP_PREFIX);
    if (unhidden != null) {
        int classID = Integer.parseInt(unhidden.split(":")[2]);

        for (SpecialItem special : event.getGame().getActivedSpecialItems(Trap.class)) {
            Trap trap = (Trap) special;
            if (System.identityHashCode(trap) == classID) {
                trap.place(event.getBlock().getLocation());
                event.getPlayer().sendMessage(i18n("trap_built"));
                return;
            }
        }
    }

}
 
Example 21
Source Project: PGM   Source File: FireTracker.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityIgnite(EntityCombustByEntityEvent event) {
  if (event.getDuration() == 0) return;

  FireInfo info = resolveBurning(event.getCombuster());
  if (info != null) {
    // First, try to resolve the player who ignited the combuster
    info = new FireInfo(new EntityInfo(event.getCombuster(), info.getOwner()));
  } else {
    // If an igniter is not found, fall back to the owner of the entity
    info = new FireInfo(entities().resolveEntity(event.getCombuster()));
  }

  burningEntities.put(event.getEntity(), info);
}
 
Example 22
/**
 * This handler only checks to see if the event should be cancelled. It does not change the state
 * of any Destroyables.
 */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void testBlockChange(BlockTransformEvent event) {
  if (this.match.getWorld() != event.getWorld() || !this.anyDestroyableAffected(event)) {
    return;
  }

  // This is a temp fix until there is a tracker for placed minecarts (only dispensed are tracked
  // right now)
  if ((event.getCause() instanceof EntityExplodeEvent
          && ((EntityExplodeEvent) event.getCause()).getEntity() instanceof ExplosiveMinecart)
      || event.getCause() instanceof BlockPistonExtendEvent
      || event.getCause() instanceof BlockPistonRetractEvent) {

    event.setCancelled(true);
    return;
  }

  for (Destroyable destroyable : this.destroyables) {
    String reasonKey =
        destroyable.testBlockChange(
            event.getOldState(),
            event.getNewState(),
            ParticipantBlockTransformEvent.getPlayerState(event));
    if (reasonKey != null) {
      event.setCancelled(true, TranslatableComponent.of(reasonKey));
      return;
    }
  }
}
 
Example 23
Source Project: BedWars   Source File: SignListener.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
    if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
        if (event.getClickedBlock().getState() instanceof Sign) {
            if (manager.isSignRegistered(event.getClickedBlock().getLocation())) {
                SignBlock sign = manager.getSign(event.getClickedBlock().getLocation());
                owner.onClick(event.getPlayer(), sign);
            }
        }
    }
}
 
Example 24
Source Project: GriefDefender   Source File: PlayerEventHandler.java    License: MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerFoodLevelChange(FoodLevelChangeEvent event) {
    final Player player = event.getEntity() instanceof Player ? (Player) event.getEntity() : null;
    if (player == null) {
        return;
    }

    GDCauseStackManager.getInstance().pushCause(player);
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    final GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Boolean denyHunger = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Boolean.class), playerData.getSubject(), Options.PLAYER_DENY_HUNGER, claim);
    if (denyHunger != null && denyHunger) {
        event.setCancelled(true);
    }
}
 
Example 25
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void handleDamage(EntityDamageEvent event) {
  MatchPlayer victim = match.getParticipant(event.getEntity());
  if (victim == null) return;

  DamageInfo damageInfo = match.needModule(TrackerMatchModule.class).resolveDamage(event);
  if (!canDamage(event.getCause(), victim, damageInfo)) {
    event.setCancelled(true);
  }
}
 
Example 26
Source Project: PGM   Source File: CombatLogTracker.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onParticipationStop(PlayerParticipationStopEvent event) {
  if (event.getMatch().isRunning()
      && this.getImminentDeath(event.getPlayer().getBukkit()) != null) {
    event.cancel(TranslatableComponent.of("leave.err.combatLog"));
    event.setCancelled(true);
  }
}
 
Example 27
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPotionSplash(final PotionSplashEvent event) {
  for (LivingEntity entity : event.getAffectedEntities()) {
    if (entity instanceof Player && match.getParticipant(entity) == null) {
      event.setIntensity(entity, 0);
    }
  }
}
 
Example 28
Source Project: PGM   Source File: SpawnMatchModule.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler
public void matchEnd(final MatchFinishEvent event) {
  // Copy states so they can transition without concurrent modification
  for (State state : ImmutableList.copyOf(states.values())) {
    state.onEvent(event);
  }
}
 
Example 29
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void updateMonitoredHealth(final EntityRegainHealthEvent event) {
  if (event.getEntity() instanceof Player) {
    Player player = (Player) event.getEntity();
    if (player.getHealth() == player.getMaxHealth()) return;
    this.scheduleCheck((Player) event.getEntity());
  }
}
 
Example 30
@EventHandler
public void onEntityInteract(PlayerInteractEntityEvent event) {
    if (event.isCancelled()) {
        return;
    }

    Player player = event.getPlayer();
    if (Main.isPlayerInGame(player)) {
        GamePlayer gPlayer = Main.getPlayerGameProfile(player);
        Game game = gPlayer.getGame();
        if (game.getStatus() == GameStatus.WAITING || gPlayer.isSpectator) {
            event.setCancelled(true);
        }
    }
}