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: Warzone   File: RegenModule.java   Source Code and License 7 votes vote down vote up
@EventHandler
public void onRegen(EntityRegainHealthEvent event) {
    if (event.getEntityType() != EntityType.PLAYER || event.getRegainReason() != EntityRegainHealthEvent.RegainReason.SATIATED) return;
    event.setCancelled(true);

    Player player = (Player) event.getEntity();
    long currentTime = System.currentTimeMillis() / 1000;

    if (currentTime - getLastHealTime(player) < 3)
        return;

    double maxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue();

    if (player.getHealth() < maxHealth) {
        player.setHealth(clamp(player.getHealth() + 1, 0.0, maxHealth));
        healTimes.put(player.getUniqueId(), currentTime);
    }

    float exhToApply = (float) 3;

    Bukkit.getScheduler().runTaskLater(TGM.get(), () -> {
        //This is because bukkit doesn't stop the exhaustion change when cancelling the event
        player.setExhaustion(player.getExhaustion() + exhToApply);
        //debug("Exhaustion before: " + previousExh + " Now: " + p.getExhaustion() + "Saturation: " + p.getSaturation(), p);
    }, 1L);
}
 
Example 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
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 35
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 36
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 37
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 38
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 39
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 40
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();
 }
}