Java Code Examples for org.bukkit.event.EventHandler

The following are top voted examples for showing how to use org.bukkit.event.EventHandler. 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: EscapeLag   File: NoCrowdEntity.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onSpawn(CreatureSpawnEvent event) {
	if (ConfigOptimize.NoCrowdedEntityenable) {
		Chunk chunk = event.getEntity().getLocation().getChunk();
		Entity[] entities = chunk.getEntities();

		for (Entity e : entities) {
			EntityType type = e.getType();
			int count = 0;
			if (ConfigOptimize.NoCrowdedEntityTypeList.contains("*")
					|| ConfigOptimize.NoCrowdedEntityTypeList.contains(type.name())) {
				count++;
				if (count > ConfigOptimize.NoCrowdedEntityPerChunkLimit && e.getType() != EntityType.PLAYER) {
					e.remove();
				}
			}
		}
	}
}
 
Example 2
Project: Ace   File: RankListener.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onChat(AsyncPlayerChatEvent event){
    if(plugin.getConfig().getString("chatformat").equals("true")){
        Player player = event.getPlayer();
        String message = event.getMessage();
        event.setCancelled(true);
        String playerNameWithPrefixSuffix = player.getName() + ": ";
        try {
            playerNameWithPrefixSuffix = ChatColor.translateAlternateColorCodes('&', (!RankManager.getRankPrefix(player).equals(" ")?RankManager.getRankPrefix(player) : "") + RankManager.getRankNameColor(player) +" "+ player.getName() +(!RankManager.getRankSuffix(player).equals(" ")? " "+ RankManager.getRankSuffix(player) : "") + ChatColor.GRAY + ": ");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        for(Player p : event.getRecipients()){
            p.sendMessage(playerNameWithPrefixSuffix + ChatColor.WHITE + message);
        }
    }
}
 
Example 3
Project: Kineticraft   File: Flight.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onMove(PlayerMoveEvent evt) {
    Player p = evt.getPlayer();
    Block b = p.getLocation().getBlock();
    if (isImmune(p) // Verify we should get an alert from this player.
            || Utils.isSameBlock(evt.getFrom(), evt.getTo()) // Check they've moved at least to the next block.
            || !checkNearby(b)) // Check if a block is nearby them.
        return;

    double yDif = evt.getTo().getY() - evt.getFrom().getY();
    double ascentMax = 0.8D;
    if (p.hasPotionEffect(PotionEffectType.JUMP))
        ascentMax += (double) p.getPotionEffect(PotionEffectType.JUMP).getAmplifier() / 10;

    detections.detect(new Detection(p),
            yDif == 0 && !checkNearby(evt.getFrom(), Material.WATER_LILY, Material.CARPET), // Hover.
            yDif > ascentMax, // If they sharply ascend.
            yDif == -.125D); // Glide (Unsure if this works.)
}
 
Example 4
Project: libtrails   File: ColorfulExample.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onBowShot(EntityShootBowEvent e) {
    if (e.getEntity() instanceof Player &&
            e.getProjectile() instanceof Arrow) {
        Bukkit.getScheduler().runTaskLater(this, () -> {
            if (!e.getProjectile().isDead()) {
                EntityTrail t = new EntityTrail(this, e.getProjectile(),
                        new CircumferenceSupplier(particle, 1.2f, 0.9f, 0.0f, 1)
                        .rotateY(tick -> tick * (2.0f * (float) Math.PI / 20))
                        , 1);
                trails.put(e.getProjectile(), t);
                t.begin();
            }
        }, 5L);
    }
}
 
Example 5
Project: ProjectAres   File: WoolMatchModule.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void handleWoolCrafting(PrepareItemCraftEvent event) {
    ItemStack result = event.getRecipe().getResult();
    InventoryHolder holder = event.getInventory().getHolder();

    if (holder instanceof Player) {
        MatchPlayer playerHolder = this.match.getPlayer((Player) holder);

        if (playerHolder != null && result != null && result.getType() == Material.WOOL) {
            for(MonumentWool wool : this.wools) {
                if(wool.getDefinition().isObjectiveWool(result)) {
                    if(!wool.getDefinition().isCraftable()) {
                        playerHolder.sendMessage(ChatColor.RED + PGMTranslations.t("match.wool.craftDisabled", playerHolder, BukkitUtils.woolMessage(wool.getDyeColor())));
                        event.getInventory().setResult(null);
                    }
                }
            }
        }
    }
}
 
Example 6
Project: HCFCore   File: InvincibilityTimer.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
    Entity entity = event.getEntity();
    if (entity instanceof Player) {
        Player attacker = BukkitUtils.getFinalAttacker(event, true);
        if (attacker == null)
            return;

        long remaining;
        Player player = (Player) entity;
        if ((remaining = getRemaining(player)) > 0L) {
            event.setCancelled(true);
            attacker.sendMessage(ChatColor.RED + player.getName() + " has their " + getDisplayName() + ChatColor.RED + " timer for another " + ChatColor.BOLD
                    + DurationFormatter.getRemaining(remaining, true, false) + ChatColor.RED + '.');

            return;
        }

        if ((remaining = getRemaining(attacker)) > 0L) {
            event.setCancelled(true);
            attacker.sendMessage(ChatColor.RED + "You cannot attack players whilst your " + getDisplayName() + ChatColor.RED + " timer is active [" + ChatColor.BOLD
                    + DurationFormatter.getRemaining(remaining, true, false) + ChatColor.RED + " remaining]. Use '" + ChatColor.GOLD + PVP_COMMAND + ChatColor.RED + "' to allow pvp.");
        }
    }
}
 
Example 7
Project: VanillaPlus   File: CPManager.java   Source Code and License 6 votes vote down vote up
@EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void onCommand(PlayerCommandPreprocessEvent event){
	if(event.getMessage().isEmpty()){
		event.setMessage("/help");
		return;
	}
	Command cmd = commandMap.get(event.getMessage().replaceFirst("/", "").split(" ")[0].toLowerCase());
	if(cmd == null){
		event.setMessage("/help");
		return;
	}
	if(!cmd.testPermissionSilent(event.getPlayer()))
		if(!(cmd instanceof LinkCommand)){
			event.setMessage("/help");
		}
}
 
Example 8
Project: VanillaPlus   File: PlayerManager.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void playerLeave(PlayerQuitEvent event){
	event.setQuitMessage("");
	VPPlayer player = getPlayer(event.getPlayer());
	player.setMenu(null);
	VPPLeaveEvent e = new  VPPLeaveEvent(player);
	if(getMsgPerm().has(player))
		e.setMessage(leave);
	e.save(player.save());
	player.setOffline();
	Bukkit.getServer().getPluginManager().callEvent(e);
	//TODO send removed event
	if(e.getMessage() != null)
		e.getMessage().addSReplacement(PlaceH.SENDER.get(), player).send();
	if(e.save())
		save(player, false);
}
 
Example 9
Project: Crescent   File: BehaviourListeners.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
	final Player player = event.getPlayer();

	final Material from = event.getFrom().getBlock().getRelative(BlockFace.DOWN).getType();

	final Behaviour behaviour = Profile.getProfile(player.getUniqueId()).getBehaviour();

	final long current = System.currentTimeMillis();

	if (player.isSprinting()) {
		behaviour.getMotion().setLastSprint(current);
	}
	if (player.isFlying()) {
		behaviour.getMotion().setLastFly(current);
	}

	if (from.isSolid() || behaviour.getMotion().getLastY() == -1.0 || !behaviour.getMotion().isDescending()) {
		behaviour.getMotion().setLastY(player.getLocation().getY());
	}

	if (!behaviour.isOnGround()) {
		behaviour.getMotion().setLastYDiff(event.getTo().getY() - event.getFrom().getY());
	}
}
 
Example 10
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 11
Project: KingdomFactions   File: KingdomMenu.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler
public void onClick(PlayerInteractEvent e) {
	if (e.getAction() == Action.PHYSICAL)
		return;
	if (e.getPlayer().getItemInHand() == null)
		return;
	if (!e.getPlayer().getItemInHand().getType().equals(Material.COMPASS))
		return;
	if (!e.getPlayer().getItemInHand().hasItemMeta())
		return;
	if (!e.getPlayer().getItemInHand().getItemMeta().getDisplayName()
			.equalsIgnoreCase(ChatColor.RED + "Selecteer jouw kingdom"))
		return;
	setKindomMenu(PlayerModule.getInstance().getPlayer(e.getPlayer()));
	e.setCancelled(true);
}
 
Example 12
Project: Hub   File: ParkourListener.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerMove(PlayerMoveEvent event)
{
    if (this.cooldown.contains(event.getPlayer().getUniqueId()))
        return;

    this.cooldown.add(event.getPlayer().getUniqueId());

    this.hub.getServer().getScheduler().runTask(this.hub, () ->
    {
        this.cooldown.remove(event.getPlayer().getUniqueId());
        Parkour parkour = this.hub.getParkourManager().getPlayerParkour(event.getPlayer().getUniqueId());

        if (parkour != null && event.getTo().getBlockY() <= parkour.getMinimalHeight())
            parkour.failPlayer(event.getPlayer());
    });
}
 
Example 13
Project: MT_Communication   File: WalkieTalkieListener.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onWalkieTalkieInteract(PlayerInteractEvent e) {
	if (e.getPlayer().getInventory().getItemInMainHand().getType() != Material.REDSTONE_COMPARATOR)
		return;
	if (e.getHand() == EquipmentSlot.OFF_HAND)
		return;

	WalkieTalkie wt = new WalkieTalkie(main,
			main.getPlayerManager().getPlayer(e.getPlayer()).getCurrentWalkieTalkieFrequency());

	// Left click to tune frequency.
	if (e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK) {
		if (e.getPlayer().isSneaking()) {
			wt.decreaseFrequency(e.getPlayer());
		} else {
			wt.increaseFrequency(e.getPlayer());
		}
	}

}
 
Example 14
Project: PVPAsWantedManager   File: JailManager.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void PlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event){
	if(!Config.getConfig("jail.eventManager.command.enabled").equals("true"))return;
	if(event.getPlayer() == null && !(event.getPlayer() instanceof Player)) return;
	Player player = event.getPlayer();
	if(isJailPlayer(player)){
		String cmd = event.getMessage().split(" ")[0].replace("/", "");
		ArrayList<String> list = Config.getList("jail.eventManager.command.whiteList");
		if(list !=null){
			for(int i=0;i < list.size();){
				if(cmd.equalsIgnoreCase(list.get(i)))return;
				i++;
			}
		}
   		playerTeleportJail(player);
		event.setCancelled(true);
	}
}
 
Example 15
Project: mczone   File: Events.java   Source Code and License 6 votes vote down vote up
@EventHandler
  public void onBlockBreak(BlockBreakEvent event) {
if (Walls.getSpectators().contains(event.getPlayer().getName())) {
	event.setCancelled(true);
	return;
}
  	
      if (State.PVP)
          return;
      
      Block b = event.getBlock();
      if (b == null)
          return;
      Team team = Team.getTeam(event.getPlayer());
      if (b.getX() < team.getMin().getX() + 1 || b.getZ() < team.getMin().getZ() + 1) {
          event.setCancelled(true);
      }
      if (b.getX() > team.getMax().getX() - 1 || b.getZ() > team.getMax().getZ() - 1) {
          event.setCancelled(true);
      }
  }
 
Example 16
Project: EscapeLag   File: AntiCrashChat.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void ChatCheckCrash(AsyncPlayerChatEvent event){
    if (!ConfigPatch.noCrashChat) return;
    
    Player player = event.getPlayer();
    String message = event.getMessage();
    if(message.contains("İ")){
        event.setCancelled(true);
        AzureAPI.log(player, ConfigPatch.AntiCrashChatSpecialStringWarnMessage);
    }
    if(HasEss == true){
        if(message.contains("&")){
            event.setCancelled(true);
            AzureAPI.log(player, ConfigPatch.AntiCrashChatSpecialStringWarnMessage);
        }
    }
}
 
Example 17
Project: Hub   File: DoubleJumpListener.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerMove(PlayerMoveEvent event)
{
    if (event.getPlayer().getGameMode() != GameMode.ADVENTURE)
        return;

    if (event.getPlayer().getAllowFlight())
        return;

    if (this.hub.getPlayerManager().isBusy(event.getPlayer()))
        return;

    if (((LivingEntity) event.getPlayer()).isOnGround())
    {
        event.getPlayer().setAllowFlight(true);
        this.allowed.add(event.getPlayer().getUniqueId());
    }
}
 
Example 18
Project: DungeonGen   File: Passageway.java   Source Code and License 6 votes vote down vote up
/**Event handler for a player pressing the button of this Passageway. Will callback to DunGen to generate the next DunGen part.
 * Also moves all other players to this Passageway.
 * @param event
 */
@EventHandler(priority = EventPriority.MONITOR)
public void onNextRoomButtonPress(PlayerInteractEvent event) {
    //Player p = event.getPlayer();
    if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
        Block clicked = event.getClickedBlock();
        if (   clicked.getType() == Material.STONE_BUTTON 
        	&& modVolume.contains(BukkitUtil.toVector(clicked.getLocation())) ) {
        	
        	unregister(); // button cannot be pushed twice
        	// If double button push appears more often, then use flag here
        	// Here we need the activePlayers list. This is not present in the entry, so don't teleport during STARTUP phase.
        	// This might be solvable better somehow...
        	
        	// only teleport if the dungeon runs, not during entry startup state
        	if (parent.state == State.RUNNING) 
	        	for (Player p : parent.activePlayers) {
	        		if (!modVolume.contains(BukkitUtil.toVector(p.getLocation()))) {
	        			p.teleport(BukkitUtil.toLocation(parent.world, toGlobal(respawnLoc).add(0.5, 0, 0.5)));
	        		}
	        	}
        	
        	parent.genNextRoom();
        }
    }
}
 
Example 19
Project: FactionsXL   File: SaturationMenu.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onClick(InventoryClickEvent event) {
    HumanEntity player = event.getWhoClicked();
    Inventory inventory = event.getClickedInventory();
    if (inventory == null || !gui.getTitle().equals(inventory.getTitle())) {
        return;
    }
    event.setCancelled(true);
    PageGUI.playSound(event);
    ItemStack button = inventory.getItem(event.getSlot());
    if (button == null) {
        return;
    }
    Resource resource = getResource(gui);
    int current = faction.getConsumableResources().get(resource);
    if (button.equals(GUIButton.BACK)) {
        faction.getPopulationMenu().openDemands(player);
        return;
    } else if (button.equals(DENY_BUTTON)) {
        faction.getConsumableResources().put(resource, current - 1);
    } else if (button.equals(GRANT_BUTTON)) {
        faction.getConsumableResources().put(resource, current + 1);
    }
    update(resource);
}
 
Example 20
Project: HCFCore   File: SubclaimWandListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = false, priority = EventPriority.NORMAL)
public void onPlayerDrop(PlayerDropItemEvent event) {
    Item item = event.getItemDrop();
    if (isSubclaimWand(item.getItemStack())) {
        item.remove();
        plugin.getClaimHandler().clearClaimSelection(event.getPlayer());
    }
}
 
Example 21
Project: mczone   File: GeneralEvents.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onPlayerDropItem(PlayerPickupItemEvent event) {
	Gamer g = Gamer.get(event.getPlayer());
	event.setCancelled(true);
	if (g.getVariable("edit") != null) {
		if ((boolean) g.getVariable("edit"))
			event.setCancelled(false);
	}
}
 
Example 22
Project: HCFCore   File: HungerFixListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled=true, priority= EventPriority.MONITOR)
/*    */   public void onPlayerJoin(PlayerJoinEvent event)
/*    */   {
/* 77 */     EntityPlayer entityPlayer = ((CraftPlayer)event.getPlayer()).getHandle();
/* 78 */     entityPlayer.knockbackReductionX = 0.6F;
/* 79 */     entityPlayer.knockbackReductionY = 0.55F;
/* 80 */     entityPlayer.knockbackReductionZ = 0.6F;
/*    */   }
 
Example 23
Project: HCFCore   File: ArmorFixListener.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onItemDamage(PlayerItemDamageEvent event)
{
  ItemStack stack = event.getItem();
  if ((stack != null) && (ALLOWED.contains(stack.getType())) && 
    (ThreadLocalRandom.current().nextInt(3) != 0)) {
    event.setCancelled(true);
  }
}
 
Example 24
Project: NavyCraft2-Lite   File: MoveCraft_PlayerListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerDeath(PlayerDeathEvent event) {
	String deathMsg = event.getDeathMessage();

	String[] msgWords = deathMsg.split("\\s");
	if (msgWords.length == 5) {
		if (msgWords[1].equalsIgnoreCase("was") && msgWords[3].equalsIgnoreCase("by")) {
			Player p = plugin.getServer().getPlayer(msgWords[4]);
			if ((p != null) && PermissionInterface.CheckEnabledWorld(p.getLocation())) {
				int newExp = 100;
				
				plugin.getServer().broadcastMessage(ChatColor.GREEN + p.getName() + " receives " + ChatColor.YELLOW
						+ newExp + ChatColor.GREEN + " rank points!");
				
				syp = (Shipyard)plugin.getServer().getPluginManager().getPlugin("NavyCraft-Shipyard");
				if( syp != null ) {
					syp.rewardExpPlayer(newExp, p);
					syp.checkRankWorld(p, newExp, p.getWorld());
					syp.saveExperience();
				}
			}
		}
	}

	if (!NavyCraft.playerKits.isEmpty() && NavyCraft.playerKits.contains(event.getEntity().getName())) {
		NavyCraft.playerKits.remove(event.getEntity().getName());
	}
}
 
Example 25
Project: BedwarsXP   File: NewEventListeners.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onPlayerDeath(PlayerDeathEvent e) {
	Game bw = io.github.bedwarsrel.BedwarsRel.Main.getInstance()
			.getGameManager().getGameOfPlayer(e.getEntity());
	if (bw == null) {
		return;
	}
	if (!Config.isGameEnabledXP(bw.getName())) {
		return;
	}
	Player p = e.getEntity();
	int dropped = 0;
	if (Config.isDirect) {
		dropped = (int) (Config.Death);
	} else {
		dropped = (int) (p.getLevel() * (Config.Death));
	}
	BedwarsXPPlayerDeathDropExpEvent event = new BedwarsXPPlayerDeathDropExpEvent(
			bw.getName(), p, dropped);
	Bukkit.getPluginManager().callEvent(event);
	dropped = event.getDroppedXP();
	int to = XPManager.getXP(bw.getName(), p) - dropped;
	if (to < 0) {
		to = 0;
	}
	e.setNewLevel(to);
	XPManager.setXP(bw.getName(), p, to);
}
 
Example 26
Project: ProjectAres   File: TeamListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onParticipationUnregister(EntrantUnregisterEvent event) {
    for (MatchPlayer player : event.getTeam().getPlayers()) {
        player.getBukkit().kickPlayer(
                ChatColor.RED + "You are no longer competing on this tournament server.\n" +
                        ChatColor.RED + "Thanks for participating!"
        );
    }
}
 
Example 27
Project: HCFCore   File: InvincibilityTimer.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPotionSplash(PotionSplashEvent event) {
    ThrownPotion potion = event.getPotion();
    if (potion.getShooter() instanceof Player && BukkitUtils.isDebuff(potion)) {
        for (LivingEntity livingEntity : event.getAffectedEntities()) {
            if (livingEntity instanceof Player) {
                if (getRemaining((Player) livingEntity) > 0L) {
                    event.setIntensity(livingEntity, 0);
                }
            }
        }
    }
}
 
Example 28
Project: Kineticraft   File: Commands.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onServerCommand(ServerCommandEvent evt) {
    evt.setCancelled(handleCommand(evt.getSender(), CommandType.SLASH, CommandType.SLASH.getPrefix() + evt.getCommand()) // Handle console commands.
            || handleCommand(evt.getSender(), CommandType.COMMAND_BLOCK, evt.getCommand())); // Command Block commands.

    if (evt.getCommand().startsWith("/ ")) {
        sendStaffChat(evt.getSender(), evt.getCommand().substring(2));
        evt.setCancelled(true);
    }
}
 
Example 29
Project: ProjectAres   File: OwnedMobTracker.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMobDispense(BlockDispenseEntityEvent event) {
    if(event.getEntity() instanceof LivingEntity) {
        ParticipantState owner = blocks().getOwner(event.getBlock());
        if(owner != null) {
            entities().trackEntity(event.getEntity(), new MobInfo((LivingEntity) event.getEntity(), owner));
        }
    }
}
 
Example 30
Project: mczone   File: GeneralEvents.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onSignClick(PlayerInteractEvent event) {
	if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR)
		return;
	
	Block b = event.getClickedBlock();
	if (b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN) {
		Sign sign = (Sign) b.getState();
		SignClickEvent ev = new SignClickEvent(event.getPlayer(), sign, event.getClickedBlock(), event.getAction() == Action.RIGHT_CLICK_BLOCK);
		Bukkit.getServer().getPluginManager().callEvent(ev);
	}
}
 
Example 31
Project: ProjectAres   File: WoolMatchModule.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void placementCheck(final BlockTransformEvent event) {
    if(this.match.getWorld() != event.getWorld()) return;

    final MonumentWool wool = this.findMonumentWool(BlockUtils.center(event.getNewState()).toVector());
    if(wool == null) return;

    if(event.getNewState().getType() == Material.AIR) { // block is being destroyed
        if(isValidWool(wool.getDyeColor(), event.getOldState())) {
            event.setCancelled(true);
        }
        return;
    }

    // default to cancelled; only uncancel if player is placing the correct color wool (see below)
    event.setCancelled(true);

    ParticipantState player = ParticipantBlockTransformEvent.getPlayerState(event);
    if(player != null) { // wool can only be placed by a player
        BaseComponent woolName = BukkitUtils.woolName(wool.getDyeColor());
        if(!isValidWool(wool.getDyeColor(), event.getNewState())) {
            player.getAudience().sendWarning(new TranslatableComponent("match.wool.placeWrong", woolName), true);
        } else if(wool.getOwner() != player.getParty()) {
            player.getAudience().sendWarning(new TranslatableComponent("match.wool.placeOther", wool.getOwner().getComponentName(), woolName), true);
        } else {
            event.setCancelled(false);
            wool.markPlaced();
            this.match.callEvent(new GoalStatusChangeEvent(wool));
            this.match.callEvent(new PlayerWoolPlaceEvent(player, wool, event.getNewState()));
            this.match.callEvent(new GoalCompleteEvent(wool,
                                                       true,
                                                       c -> false,
                                                       c -> c.equals(wool.getOwner()),
                                                       ImmutableList.of(new Contribution(player, 1))));
        }
    }
}
 
Example 32
Project: HCFCore   File: FactionListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onFactionRename(FactionRenameEvent event) {
    Faction faction = event.getFaction();
    if (faction instanceof PlayerFaction) {
        for (Player player : Bukkit.getOnlinePlayers()) {
            Relation relation = faction.getRelation(player);
            String msg = ChatColor.YELLOW + "The faction " + relation.toChatColour() + event.getOriginalName() + ChatColor.GRAY + " has been " + ChatColor.AQUA + "renamed" + ChatColor.GRAY
                    + " to " + relation.toChatColour() + event.getNewName() + ChatColor.GRAY + '.';
            player.sendMessage(msg);
        }
    }
}
 
Example 33
Project: bskyblock   File: IslandGuard.java   Source Code and License 5 votes vote down vote up
/**
 * Prevents mobs spawning at spawn or in an island
 *
 * @param e
 */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onMobSpawn(final CreatureSpawnEvent e) {
    if (DEBUG2) {
        plugin.getLogger().info("on Mob spawn" + e.getEventName());
    }
    // if grid is not loaded yet, return.
    if (plugin.getIslands() == null) {
        return;
    }
    // If not in the right world, return
    if (!Util.inWorld(e.getEntity())) {
        return;
    }
    // Deal with natural spawning
    if (e.getEntity() instanceof Monster || e.getEntity() instanceof Slime) {
        if (!actionAllowed(e.getLocation(), SettingsFlag.MONSTER_SPAWN)) {
            if (DEBUG2)
                plugin.getLogger().info("Natural monster spawn cancelled.");
            // Mobs not allowed to spawn
            e.setCancelled(true);
            return;
        }
    }
    if (e.getEntity() instanceof Animals) {
        if (!actionAllowed(e.getLocation(), SettingsFlag.ANIMAL_SPAWN)) {
            // Animals are not allowed to spawn
            if (DEBUG2)
                plugin.getLogger().info("Natural animal spawn cancelled.");
            e.setCancelled(true);
        }
    }
}
 
Example 34
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 35
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 PlayerBucketFillEvent event) {
    if (!isWithinBorder(event.getBlockClicked().getLocation())) {
        event.setCancelled(true);
        event.getPlayer().sendMessage(ChatColor.RED + "You cannot fill buckets past the border.");
    }
}
 
Example 36
Project: DubtrackUtils   File: EventListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL)
public void onChat(AsyncPlayerChatEvent event) {
	if (config.getBoolean("settings.chat.game-to-dub")) {
		try {
			dtu.getRoom().sendMessage(config.getString("lang.chat.game-to-dub")
					.replaceAll("%user%", event.getPlayer().getDisplayName())
					.replaceAll("%message%", event.getMessage()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
Example 37
Project: EscapeLag   File: AutoSave.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void JoinTaskGiver(PlayerJoinEvent e) {
    if (ConfigOptimize.AutoSaveenable == false) {
        return;
    }
    final Player p = e.getPlayer();
    TaskId.put(p, Bukkit.getScheduler().scheduleSyncRepeatingTask(EscapeLag.MainThis, new Runnable() {

        @Override
        public void run() {
            Chunk chunk = p.getLocation().getChunk();
            Chunk LastChunk = PlayerInChunkMap.get(p);
            if (LastChunk != chunk) {
                if (LastChunk == null) {
                    PlayerInChunkMap.put(p, chunk);
                    return;
                }
                if (PlayerClickedMap.containsValue(LastChunk)) {
                    return;
                }
                World world = LastChunk.getWorld();
                if (LastChunk.isLoaded() == true) {
                	world.unloadChunk(LastChunk.getX(), LastChunk.getZ(), true);
                    LastChunk.load();
                } else {
                    LastChunk.load();
                    world.unloadChunk(LastChunk.getX(), LastChunk.getZ(), true);
                }
            }
            PlayerInChunkMap.put(p, chunk);
            p.saveData();
        }
    }, ConfigOptimize.AutoSaveInterval * 20, ConfigOptimize.AutoSaveInterval * 20));
}
 
Example 38
Project: PetBlocks   File: PetDataListener.java   Source Code and License 5 votes vote down vote up
/**
 * Removes the petblock from the player when he leaves the server
 *
 * @param event playerQuitEvent
 */
@EventHandler
public void playerQuitEvent(PlayerQuitEvent event) {
    if (this.manager.headDatabasePlayers.contains(event.getPlayer())) {
        this.manager.headDatabasePlayers.remove(event.getPlayer());
    }
    if (this.spamProtection.contains(event.getPlayer())) {
        this.spamProtection.remove(event.getPlayer());
    }
    PetBlocksApi.getDefaultPetBlockController().removeByPlayer(event.getPlayer());
}
 
Example 39
Project: KingdomFactions   File: YesNoConfirmationModule.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onClose(InventoryCloseEvent e) {
 KingdomFactionsPlayer player = PlayerModule.getInstance().getPlayer(e.getPlayer());
 if(player == null) return;
 if(player.hasYesNoConfirmation()) {
  player.getYesNoConfirmation().callClose();
 }
}
 
Example 40
Project: ProjectAres   File: RestartListener.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onMatchUnload(MatchUnloadEvent event) {
    if(deferral != null && deferral.request().priority() >= ServerDoc.Restart.Priority.NORMAL) {
        logger.info("Resuming restart because the match unloaded");
        deferral.resume();
        deferral = null;
    }
}
 
Example 41
Project: Warzone   File: InfectionModule.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onTeamChange(TeamChangeEvent event) {
    if (teamManager.getTeamById("humans").getMembers().size() == 0 && match.getMatchStatus().equals(MatchStatus.MID)) {
        TGM.get().getMatchManager().endMatch(teamManager.getTeamById("infected"));
    }
    event.getPlayerContext().getPlayer().setGameMode(GameMode.ADVENTURE);

    if (event.getTeam().getId().equalsIgnoreCase("infected")) {
        event.getPlayerContext().getPlayer().addPotionEffects(Collections.singleton(new PotionEffect(PotionEffectType.JUMP, 50000, 1, true, false)));
    }
}
 
Example 42
Project: ProjectAres   File: CombatLogTracker.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerDamage(EntityDamageEvent event) {
    if(event.getDamage() <= 0) return;

    if(!(event.getEntity() instanceof Player)) return;
    Player player = (Player) event.getEntity();

    if(player.getGameMode() == GameMode.CREATIVE) return;

    if(player.isDead()) return;

    if(player.getNoDamageTicks() > 0) return;

    if(getResistanceFactor(player) <= 0) return;

    switch(event.getCause()) {
        case ENTITY_EXPLOSION:
        case BLOCK_EXPLOSION:
        case CUSTOM:
        case FALL:
        case FALLING_BLOCK:
        case LIGHTNING:
        case MELTING:
        case SUICIDE:
        case THORNS:
            return; // Skip damage causes that are not particularly likely to be followed by more damage

        case FIRE:
        case FIRE_TICK:
        case LAVA:
            if(hasFireResistance(player)) return;
            break;
    }

    // Record the player's damage with a timestamp
    this.recentDamage.put(player, new Damage(Instant.now(), event));
}
 
Example 43
Project: HCFCore   File: ScoreboardHandler.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled=true, priority=EventPriority.MONITOR)
public void onPlayerLeftFaction(PlayerLeftFactionEvent event)
{
  Optional<Player> optional = event.getPlayer();
  if (optional.isPresent())
  {
    Player player = (Player)optional.get();
    Collection<Player> players = event.getFaction().getOnlinePlayers();
    getPlayerBoard(event.getUniqueID()).addUpdates(players);
    for (Player target : players) {
      getPlayerBoard(target.getUniqueId()).addUpdate(player);
    }
  }
}
 
Example 44
Project: ZorahPractice   File: PlayerListener.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onPickup(PlayerPickupItemEvent event) {
    Player player = event.getPlayer();
    PracticeProfile profile = DataAccessor.getPlayerProfile(player);

    if (profile.getStatus() != PlayerStatus.PLAYING) {
        event.setCancelled(true);
    }
}
 
Example 45
Project: NavyCraft2-Lite   File: MoveCraft_BlockListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onBlockDispense(final BlockDispenseEvent event) {
	if (!event.isCancelled()) {
		if (PermissionInterface.CheckEnabledWorld(event.getBlock().getLocation()) && (event.getItem().getType() == Material.EMERALD)) {
			event.setCancelled(true);
		}

	}
	
	if(!event.isCancelled())
		AimCannonPlayerListener.onBlockDispense(event);
}
 
Example 46
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 47
Project: HCFCore   File: CombatLogListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled=true, priority=EventPriority.MONITOR)
public void onPlayerLogin(PlayerLoginEvent event)
{
    LoggerEntity currentLogger = (LoggerEntity)this.loggers.remove(event.getPlayer().getUniqueId());
    if (currentLogger != null) {
        currentLogger.destroy();
    }
}
 
Example 48
Project: PetBlocks   File: PetBlockListener.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onInventoryOpenEvent(InventoryOpenEvent event) {
    final Player player = (Player) event.getPlayer();
    if (this.manager.carryingPet.contains(player)) {
        event.setCancelled(true);
        event.getPlayer().closeInventory();
    }
}
 
Example 49
Project: Warzone   File: Monument.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onBlockBurn(BlockBurnEvent event) {
    if (region.contains(event.getBlock().getLocation())) {
        if (materials == null || materials.contains(event.getBlock().getType())) {
            event.setCancelled(true);
        }
    }
}
 
Example 50
Project: SmartInvs   File: InventoryManager.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOW)
public void onPluginDisable(PluginDisableEvent e) {
    new HashSet<>(inventories.entrySet()).forEach(entry -> {
        SmartInventory inv = entry.getValue();

        inv.getListeners().stream()
                .filter(listener -> listener.getType() == PluginDisableEvent.class)
                .forEach(listener -> ((InventoryListener<PluginDisableEvent>) listener).accept(e));

        inv.close(entry.getKey());
    });
}
 
Example 51
Project: SurvivalAPI   File: SurvivalTeamSelector.java   Source Code and License 5 votes vote down vote up
/**
 * Event fired when a player rename his team
 *
 * @param event Event
 */
@EventHandler
public void onSignChange(SignChangeEvent event)
{
    if (this.game.getStatus().equals(Status.IN_GAME))
    {
        event.getHandlers().unregister(this);
        return;
    }

    if (!this.game.getStatus().equals(Status.IN_GAME))
    {
        SurvivalTeam team = this.game.getPlayerTeam(event.getPlayer().getUniqueId());
        String name = event.getLine(0);
        name = name.trim();

        if (!name.isEmpty())
        {
            team.setTeamName(name);
            event.getPlayer().sendMessage(this.game.getCoherenceMachine().getGameTag() + " " + ChatColor.GREEN + "Le nom de votre équipe est désormais : " + team.getChatColor() + team.getTeamName());
            this.openGui(event.getPlayer(), new GuiSelectTeam());
        }
        else
        {
            event.getPlayer().sendMessage(this.game.getCoherenceMachine().getGameTag() + " " + ChatColor.RED + "Le nom de l'équipe ne peut être vide.");
            this.openGui(event.getPlayer(), new GuiSelectTeam());
        }
        this.game.getPlugin().getServer().getScheduler().runTaskLater(this.game.getPlugin(), () ->
        {
            event.getBlock().setType(Material.AIR);
            event.getBlock().getRelative(BlockFace.DOWN).setType(Material.AIR);
        }, 1L);
    }
}
 
Example 52
Project: SurvivalAPI   File: ChunkListener.java   Source Code and License 5 votes vote down vote up
/**
 * Listen when world loaded
 */

@EventHandler
public void onWorldLoad(WorldLoadEvent event)
{
    if (event.getWorld().equals(Bukkit.getWorlds().get(0)))
        SurvivalAPI.get().fireEvents(SurvivalAPI.EventType.WORLDLOADED);
}
 
Example 53
Project: RPGInventory   File: LockerListener.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onGameModeSwitch(PlayerGameModeChangeEvent event) {
    Player player = event.getPlayer();

    if (!InventoryManager.playerIsLoaded(player)) {
        return;
    }

    if (event.getNewGameMode() == GameMode.CREATIVE) {
        InventoryLocker.unlockSlots(player);
    } else if (event.getPlayer().getGameMode() == GameMode.CREATIVE) {
        InventoryLocker.lockSlots(player, true);
    }
}
 
Example 54
Project: HCFCore   File: BorderListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onBlockBreak(final BlockBreakEvent event) {
    if (!isWithinBorder(event.getBlock().getLocation())) {
        event.setCancelled(true);
        event.getPlayer().sendMessage(ChatColor.RED + "You cannot break blocks past the border.");
    }
}
 
Example 55
Project: mczone   File: VotePanelEvents.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onCompassClick(PlayerInteractEvent event) {
	if (event.getItem() == null || event.getItem().getType() != Material.EMERALD)
		return;
	Player p = event.getPlayer();
	ItemStack stack = event.getItem();
	if (stack.getItemMeta().hasDisplayName()) {
		String display = Chat.stripColor(stack.getItemMeta().getDisplayName());
		if (display.equalsIgnoreCase("voting panel")) {
			new VotePanel(p).show();
		}
	}
}
 
Example 56
Project: RealSurvival   File: BasicEvent.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void join(PlayerJoinEvent e){
	Player p=e.getPlayer();
	if(p.hasMetadata("NPC"))return;
	if(!rs.worldExists(p.getWorld().getName()))return;
	File data=new File(rs.getDataFolder()+File.separator+"PlayerDatas"+File.separator+p.getUniqueId().toString()+".yml");
	if(!data.exists()){//�������ļ��Ƿ����,������������ʼ��һ���ļ�
		try {data.createNewFile();} catch (IOException e1) {}
		PlayerData pd=new PlayerData(p.getUniqueId(),p.getWorld().getName(), rs.getSleepMax(), rs.getThirstMax(), 0, 37, 0, rs.getPhysical_strength());
		pd.savaData();
	}
	rs.addPlayerData(p, Utils.getPlayerData(p));
	return;
}
 
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 onEntityChangeBlock(final EntityChangeBlockEvent event) {
    final Entity entity = event.getEntity();
    if (entity instanceof LivingEntity && !attemptBuild(entity, event.getBlock().getLocation(), null)) {
        event.setCancelled(true);
    }
}
 
Example 58
Project: ProjectAres   File: DeathTracker.java   Source Code and License 5 votes vote down vote up
/**
 * Must run after {@link tc.oc.pgm.spawns.SpawnMatchModule#onVanillaDeath}
 */
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerDeath(PlayerDeathEvent event) {
    logger.fine("Wrapping " + event);
    MatchPlayer victim = match.getParticipant(event.getEntity());
    if(victim == null || victim.isDead()) return;

    DamageInfo info = getLastDamage(victim);
    if(info == null) info = new GenericDamageInfo(EntityDamageEvent.DamageCause.CUSTOM);

    match.callEvent(new MatchPlayerDeathEvent(event, victim, info, CombatLogTracker.isCombatLog(event)));
}
 
Example 59
Project: HCFCore   File: ProtectionListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onHangingDamageByEntity(EntityDamageByEntityEvent event) {
    Entity entity = event.getEntity();
    if (entity instanceof Hanging) {
        Player attacker = BukkitUtils.getFinalAttacker(event, false);
        if (!attemptBuild(attacker, entity.getLocation(), ChatColor.YELLOW + "You may not build in the territory of %1$s" + ChatColor.YELLOW + '.')) {
            event.setCancelled(true);
        }
    }
}
 
Example 60
Project: ProjectAres   File: TeamListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void recordMatch(MatchEndEvent event) {
    Match match = event.getMatch();
    if (match.matchState().equals(MatchState.Finished)) {
        matchManagerProvider.get().recordMatchIfQueued();
    }
}