Java Code Examples for org.bukkit.entity.Player#isSneaking()

The following examples show how to use org.bukkit.entity.Player#isSneaking() . 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
Source File: EntityInteract.java    From FunnyGuilds with Apache License 2.0 6 votes vote down vote up
@EventHandler
public void onInteract(PlayerInteractEntityEvent event) {
    MessageConfiguration messages = FunnyGuilds.getInstance().getMessageConfiguration();
    PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();
    Player eventCaller = event.getPlayer();
    Entity clickedEntity = event.getRightClicked();

    if (clickedEntity instanceof Player) {
        Player clickedPlayer = (Player) clickedEntity;
        if (!config.infoPlayerEnabled || (config.infoPlayerSneaking && !eventCaller.isSneaking())
                        || informationMessageCooldowns.cooldown(eventCaller, TimeUnit.SECONDS, config.infoPlayerCooldown)) {
            return;
        }

        if (config.infoPlayerCommand) {
            playerExecutor.execute(eventCaller, new String[]{clickedPlayer.getName()});
        } else {
            playerExecutor.sendInfoMessage(messages.playerRightClickInfo, User.get(clickedPlayer), eventCaller);
        }
    }
}
 
Example 2
Source File: SilentOpenChest.java    From SuperVanish with Mozilla Public License 2.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onChestInteract(PlayerInteractEvent e) {
    Player p = e.getPlayer();
    if (!plugin.getVanishStateMgr().isVanished(p.getUniqueId())) return;
    if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
    if (p.getGameMode() == GameMode.SPECTATOR) return;
    //noinspection deprecation
    if (p.isSneaking() && p.getItemInHand() != null
            && (p.getItemInHand().getType().isBlock() || p.getItemInHand().getType() == ITEM_FRAME)
            && p.getItemInHand().getType() != Material.AIR)
        return;
    Block block = e.getClickedBlock();
    if (block == null) return;
    if (block.getType() == ENDER_CHEST) {
        e.setCancelled(true);
        p.openInventory(p.getEnderChest());
        return;
    }
    if (!(block.getType() == CHEST || block.getType() == TRAPPED_CHEST
            || plugin.getVersionUtil().isOneDotXOrHigher(11) && shulkerBoxes.contains(block.getType())))
        return;
    StateInfo stateInfo = StateInfo.extract(p);
    playerStateInfoMap.put(p, stateInfo);
    p.setGameMode(GameMode.SPECTATOR);
}
 
Example 3
Source File: Power.java    From MineTinker with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean canUsePower(Player player, ItemStack tool) {
	if (!player.hasPermission("minetinker.modifiers.power.use")) {
		return false;
	}

	if (HAS_POWER.get(player).get()) {
		return false;
	}

	if (toggleable) {
		if (player.isSneaking()) {
			return false;
		}
	}

	return modManager.hasMod(tool, this);
}
 
Example 4
Source File: InteractListener.java    From TradePlus with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onInteract(PlayerInteractAtEntityEvent event) {
  if (event.getRightClicked() instanceof Player) {
    Long last = lastTrigger.get(event.getPlayer().getUniqueId());
    if (last != null && System.currentTimeMillis() < last + 5000L) return;
    Player player = event.getPlayer();
    Player interacted = (Player) event.getRightClicked();
    String action = pl.getConfig().getString("action", "").toLowerCase();
    if ((action.contains("sneak") || action.contains("crouch") || action.contains("shift"))
        && !player.isSneaking()) return;
    if (action.contains("right")) {
      event.setCancelled(true);
      Bukkit.getPluginManager()
          .callEvent(
              new PlayerCommandPreprocessEvent(
                  event.getPlayer(), "/trade " + interacted.getName()));
      lastTrigger.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
    }
  }
}
 
Example 5
Source File: Drilling.java    From MineTinker with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean canUseDrilling(Player player, ItemStack tool) {
	if (!player.hasPermission("minetinker.modifiers.drilling.use")) {
		return false;
	}

	if (HAS_DRILLING.get(player).get()) {
		return false;
	}

	if (toggleable) {
		if (player.isSneaking()) {
			return false;
		}
	}

	return modManager.hasMod(tool, this);
}
 
Example 6
Source File: BrushListener.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(final PlayerInteractEvent event) {
    Player bukkitPlayer = event.getPlayer();
    if (bukkitPlayer.isSneaking()) {
        if (event.getAction() == Action.PHYSICAL) {
            return;
        }
        FawePlayer<Object> fp = FawePlayer.wrap(bukkitPlayer);
        com.sk89q.worldedit.entity.Player player = fp.getPlayer();
        LocalSession session = fp.getSession();
        Tool tool = session.getTool(player);
        if (tool instanceof ResettableTool) {
            if (((ResettableTool) tool).reset()) {
                event.setCancelled(true);
            }
        }
    }
}
 
Example 7
Source File: InteractListener.java    From SaneEconomy with GNU General Public License v3.0 5 votes vote down vote up
private void doBuy(SignShop shop, Player player) {
    EconomyManager ecoMan = this.plugin.getSaneEconomy().getEconomyManager();
    int quantity = player.isSneaking() ? 1 : shop.getQuantity();

    ShopTransaction shopTransaction = shop.makeTransaction(ecoMan.getCurrency(), player, TransactionDirection.BUY, quantity);

    /* No buy limits for now!
    if (!plugin.getLimitManager().shouldAllowTransaction(shopTransaction)) {
        MessageUtils.sendMessage(player, "You have reached your buying limit for the time being. Try back in an hour or so.");
        return;
    }

    plugin.getLimitManager().setRemainingLimit(player, ShopTransaction.TransactionDirection.BUY, shop.getItem(), plugin.getLimitManager().getRemainingLimit(player, ShopTransaction.TransactionDirection.BUY, shop.getItem()) - quantity);
    */

    Transaction ecoTransaction = shopTransaction.makeEconomyTransaction();
    TransactionResult result = ecoMan.transact(ecoTransaction);

    if (result.getStatus() != TransactionResult.Status.SUCCESS) {
        this.plugin.getMessenger().sendMessage(player, "An error occurred attempting to perform that transaction: {1}", result.getStatus());
        return;
    }

    ItemStack stack = new ItemStack(shop.getItemStack()); /* Clone it so we don't modify the stack size in the shop */
    stack.setAmount(quantity);
    player.getInventory().addItem(stack);

    this.plugin.getMessenger().sendMessage(player, "You have bought {1} {2} for {3}.", quantity, shop.getItemStack().getType().name(), ecoMan.getCurrency().formatAmount(shopTransaction.getPrice()));
    LOGGER.info(String.format("%s just bought %d %s for %s.", player.getName(), quantity, shop.getItemStack().getType().name(), ecoMan.getCurrency().formatAmount(shopTransaction.getPrice())));
}
 
Example 8
Source File: MultiTool.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
protected ItemUseHandler getItemUseHandler() {
    return e -> {
        Player p = e.getPlayer();
        ItemStack item = e.getItem();
        e.cancel();

        int index = selectedMode.getOrDefault(p.getUniqueId(), 0);

        if (!p.isSneaking()) {
            if (removeItemCharge(item, COST)) {
                SlimefunItem sfItem = modes.get(index).getItem();

                if (sfItem != null) {
                    sfItem.callItemHandler(ItemUseHandler.class, handler -> handler.onRightClick(e));
                }
            }
        }
        else {
            index = nextIndex(index);

            SlimefunItem selectedItem = modes.get(index).getItem();
            String itemName = selectedItem != null ? selectedItem.getItemName() : "Unknown";
            SlimefunPlugin.getLocalization().sendMessage(p, "messages.mode-change", true, msg -> msg.replace("%device%", "Multi Tool").replace("%mode%", ChatColor.stripColor(itemName)));
            selectedMode.put(p.getUniqueId(), index);
        }
    };
}
 
Example 9
Source File: DebugFishListener.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onDebug(PlayerInteractEvent e) {
    if (e.getAction() == Action.PHYSICAL || e.getHand() != EquipmentSlot.HAND) {
        return;
    }

    Player p = e.getPlayer();

    if (p.isOp() && SlimefunUtils.isItemSimilar(e.getItem(), SlimefunItems.DEBUG_FISH, true)) {
        e.setCancelled(true);

        if (e.getAction() == Action.LEFT_CLICK_BLOCK) {
            if (p.isSneaking()) {
                if (BlockStorage.hasBlockInfo(e.getClickedBlock())) {
                    BlockStorage.clearBlockInfo(e.getClickedBlock());
                }
            }
            else {
                e.setCancelled(false);
            }
        }
        else if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
            if (p.isSneaking()) {
                Block b = e.getClickedBlock().getRelative(e.getBlockFace());
                b.setType(Material.PLAYER_HEAD);
                SkullBlock.setFromHash(b, HeadTexture.MISSING_TEXTURE.getTexture());
            }
            else if (BlockStorage.hasBlockInfo(e.getClickedBlock())) {
                sendInfo(p, e.getClickedBlock());
            }
        }
    }
}
 
Example 10
Source File: SpectatorEvents.java    From Survival-Games with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerClickEvent(PlayerInteractEvent event) {
    Player player = event.getPlayer();
    try{
        if(GameManager.getInstance().isSpectator(player) && player.isSneaking() && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR)||
                GameManager.getInstance().isSpectator(player) && player.isSneaking() && (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_AIR)){
            Player[]players = GameManager.getInstance().getGame(GameManager.getInstance().getPlayerSpectateId(player)).getPlayers()[0];
            Game g = GameManager.getInstance().getGame(GameManager.getInstance().getPlayerSpectateId(player));

            int i = g.getNextSpec().get(player);
            if((event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR)){
                i++;
            }
            else if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_AIR){
                i--;
            }
            if(i>players.length-1){
                i = 0;
            }
            if(i<0){
                i = players.length-1;
            }
            g.getNextSpec().put(player, i);
            Player tpto = players[i];
            Location l = tpto.getLocation();
            l.setYaw(0);
            l.setPitch(0);
            player.teleport(l);
            player.sendMessage(ChatColor.AQUA+"You are now spectating "+tpto.getName());
        }
        else if (GameManager.getInstance().isSpectator(player)) {
            event.setCancelled(true);
        }
    }
    catch(Exception e){e.printStackTrace();}
}
 
Example 11
Source File: AssassinsBlade.java    From ce with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean effect(Event event, final Player player) {
	if(event instanceof PlayerInteractEvent) {
		if(!player.hasMetadata("ce.assassin"))
			if(player.isSneaking())
					  player.setMetadata("ce.assassin", new FixedMetadataValue(main, null));
					  player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, InvisibilityDuration, 0, true), true);
					  player.sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + "You hide in the shadows.");
					  new BukkitRunnable() {
						  @Override
						  public void run() {
							  if(player.hasMetadata("ce.assassin")) {
								  player.removeMetadata("ce.assassin", main);
								  player.sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + "You are no longer hidden!");
							  }
						  }
					  }.runTaskLater(main, InvisibilityDuration);
					  return true;
				  }
	if(event instanceof EntityDamageByEntityEvent) {
		EntityDamageByEntityEvent e = ((EntityDamageByEntityEvent) event);
		if(e.getDamager() == player && player.hasMetadata("ce.assassin")) {
			  e.setDamage(e.getDamage() * AmbushDmgMultiplier);
			  player.removeMetadata("ce.assassin", main);
			  player.removePotionEffect(PotionEffectType.INVISIBILITY);
			  EffectManager.playSound(e.getEntity().getLocation(), "BLOCK_PISTON_EXTEND", 0.4f, 0.1f);
			  player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, WeaknessLength, WeaknessLevel, false), true);
			  player.sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + "You are no longer hidden!");
	   }
	}
	 return false;
}
 
Example 12
Source File: EventFilterMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
ClickType convertClick(ClickType clickType, Player player) {
    if(clickType == ClickType.RIGHT && player.isSneaking()) {
        return ClickType.SHIFT_RIGHT;
    } else {
        return clickType;
    }
}
 
Example 13
Source File: InteractListener.java    From SaneEconomy with GNU General Public License v3.0 5 votes vote down vote up
private void doSell(SignShop shop, Player player) { // TODO: Selling enchanted items
    EconomyManager ecoMan = this.plugin.getSaneEconomy().getEconomyManager();
    int quantity = player.isSneaking() ? 1 : shop.getQuantity();
    BigDecimal price = shop.getSellPrice(quantity);

    if (!player.getInventory().containsAtLeast(new ItemStack(shop.getItemStack()), quantity)) {
        this.plugin.getMessenger().sendMessage(player, "You do not have {1} {2}!", quantity, shop.getItemStack().getType().name());
        return;
    }

    ShopTransaction shopTransaction = shop.makeTransaction(ecoMan.getCurrency(), player, TransactionDirection.SELL, quantity);

    if (!this.plugin.getLimitManager().shouldAllowTransaction(shopTransaction)) {
        this.plugin.getMessenger().sendMessage(player, "You have reached your selling limit for the time being. Try back in an hour or so.");
        return;
    }

    this.plugin.getLimitManager().setRemainingLimit(player, TransactionDirection.SELL, shop.getItem(), this.plugin.getLimitManager().getRemainingLimit(player, TransactionDirection.SELL, shop.getItem()) - quantity);


    ItemStack stack = new ItemStack(shop.getItemStack()); /* Clone it so we don't modify the stack size in the shop */
    stack.setAmount(quantity);
    player.getInventory().removeItem(stack); // FIXME: This does not remove items with damage values that were detected by contains()

    ecoMan.transact(shopTransaction.makeEconomyTransaction());

    this.plugin.getMessenger().sendMessage(player, "You have sold {1} {2} for {3}.", quantity, shop.getItemStack().getType().name(), ecoMan.getCurrency().formatAmount(price));
    LOGGER.info(String.format("%s just sold %d %s for %s.", player.getName(), quantity, shop.getItemStack().getType().name(), ecoMan.getCurrency().formatAmount(price)));
}
 
Example 14
Source File: ShadowDive.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
	Iterator<Player> iterator = activePlayers.iterator();
	//noinspection WhileLoopReplaceableByForEach
	while (iterator.hasNext()) {
		Player p = iterator.next();
		Location loc = p.getLocation();
		byte lightlevel = p.getWorld().getBlockAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()).getLightLevel();
		if (!p.isSneaking() || lightlevel > requiredLightLevel || p.hasPotionEffect(PotionEffectType.GLOWING)) {
			showPlayer(p);
			ChatWriter.sendActionBar(p, ChatColor.RED + ShadowDive.instance().getName() + ": "
					+ LanguageManager.getString("Modifier.Shadow-Dive.LightToHigh", p));
		} else if (PlayerInfo.isCombatTagged(p)) {
			showPlayer(p);
			ChatWriter.sendActionBar(p, ChatColor.RED + ShadowDive.instance().getName() + ": "
					+ LanguageManager.getString("Modifier.Shadow-Dive.InCombat", p));
		} else {
			for(Player pl : Bukkit.getOnlinePlayers()) {
				if (pl.equals(p)) continue;
				if (pl.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
					pl.showPlayer(MineTinker.getPlugin(), p);
				} else {
					pl.hidePlayer(MineTinker.getPlugin(), p);
				}
			}
		}
	}
}
 
Example 15
Source File: VeinMinerListener.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onBlockBreak(BlockBreakEvent e){
    Player player = e.getPlayer();

    if (!player.isSneaking()){
        return;
    }

    Block block = e.getBlock();
    ItemStack tool = player.getItemInHand();

    if (block.getType() == UniversalMaterial.GLOWING_REDSTONE_ORE.getType()){
        block.setType(Material.REDSTONE_ORE);
    }

    if (!UniversalMaterial.isCorrectTool(block.getType(), player.getItemInHand().getType())){
        return;
    }

    // find all surrounding blocks
    Vein vein = new Vein(block);
    vein.process();

    player.getWorld().dropItem(player.getLocation().getBlock().getLocation().add(.5,.5,.5), vein.getDrops(getVeinMultiplier(vein.getDropType())));

    if (vein.getTotalXp() != 0){
        UhcItems.spawnExtraXp(player.getLocation(), vein.getTotalXp());
    }

    // Process blood diamonds.
    if (isActivated(Scenario.BLOODDIAMONDS) && vein.getDropType() == Material.DIAMOND){
        player.getWorld().playSound(player.getLocation(), UniversalSound.PLAYER_HURT.getSound(), 1, 1);

        if (player.getHealth() < vein.getOres()){
            player.setHealth(0);
        }else {
            player.setHealth(player.getHealth() - vein.getOres());
        }
    }

    int newDurability = tool.getDurability()-vein.getOres();
    if (newDurability<1) newDurability = 1;

    tool.setDurability((short) newDurability);
    player.setItemInHand(tool);
}
 
Example 16
Source File: EntityToggleGlideListener.java    From ViaVersion with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void entityToggleGlide(EntityToggleGlideEvent event) {
    if (!(event.getEntity() instanceof Player)) return;

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

    // Cancelling can only be done by updating the player's metadata
    if (event.isGliding() && event.isCancelled()) {
        PacketWrapper packet = new PacketWrapper(0x44, null, getUserConnection(player));
        try {
            packet.write(Type.VAR_INT, player.getEntityId());

            byte bitmask = 0;
            // Collect other metadata for the mitmask
            if (player.getFireTicks() > 0) {
                bitmask |= 0x01;
            }
            if (player.isSneaking()) {
                bitmask |= 0x02;
            }
            // 0x04 is unused
            if (player.isSprinting()) {
                bitmask |= 0x08;
            }
            if (swimmingMethodExists && player.isSwimming()) {
                bitmask |= 0x10;
            }
            if (player.hasPotionEffect(PotionEffectType.INVISIBILITY)) {
                bitmask |= 0x20;
            }
            if (player.isGlowing()) {
                bitmask |= 0x40;
            }

            // leave 0x80 as 0 to stop gliding
            packet.write(Types1_14.METADATA_LIST, Arrays.asList(new Metadata(0, MetaType1_14.Byte, bitmask)));
            packet.send(Protocol1_15To1_14_4.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 17
Source File: TauntListener.java    From SkyWarsReloaded with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void pressedTauntKey(PlayerToggleSneakEvent e) {
	Player player = e.getPlayer();
       GameMap gameMap = MatchManager.get().getPlayerMap(player);
       if (gameMap == null) {
       	return;
       }
	String uuid = e.getPlayer().getUniqueId().toString();
	if (!player.isSneaking()) {
		if (lastHandSwap.containsKey(uuid)) {
			if (System.currentTimeMillis() - lastHandSwap.get(uuid) < 500) {
				if (lastTaunt.containsKey(uuid)) {
					if (System.currentTimeMillis() - lastTaunt.get(uuid) < SkyWarsReloaded.getCfg().getCooldown()*1000) {
						int cooldown = (int) ((SkyWarsReloaded.getCfg().getCooldown()*1000 - (System.currentTimeMillis() - lastTaunt.get(uuid)))/1000);
						int seconds = (cooldown % 60) + 1;
						int minutes = (cooldown-(seconds - 1)) / 60;
						String cooldownText = "";
						if (minutes > 0) {
							cooldownText = cooldownText + minutes + " Minutes ";
						} 
						if (seconds > 0) {
							cooldownText = cooldownText + seconds + " Seconds";
						}
						
						e.getPlayer().sendMessage(new Messaging.MessageFormatter().setVariable("timeleft", cooldownText).format("error.cooldown"));
						return;
					} else {
						lastTaunt.remove(uuid);
					}
				}
				PlayerStat ps = PlayerStat.getPlayerStats(e.getPlayer());
				if (ps != null) {
                       String tauntName = ps.getTaunt();
                       TauntOption taunt = (TauntOption) TauntOption.getPlayerOptionByKey(tauntName);
                       if (taunt != null) {
                           if (!taunt.getKey().equals("none")) {
                               taunt.performTaunt(e.getPlayer());
                           }
                       }
                       lastHandSwap.remove(uuid);
                       lastTaunt.put(uuid, System.currentTimeMillis());
                   }
			} else {
				lastHandSwap.put(uuid, System.currentTimeMillis());
			}
		} else {
			lastHandSwap.put(uuid, System.currentTimeMillis());
		}
	}	
}
 
Example 18
Source File: ElytraEnhanceListener.java    From NyaaUtils with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void playerMove(PlayerMoveEvent e) {
    Player player = e.getPlayer();
    if (player.isGliding() &&
            plugin.cfg.elytra_enhance_enabled &&
            !plugin.cfg.disabled_world.contains(player.getWorld().getName()) &&
            player.getLocation().getBlock().isEmpty() &&
            player.getEyeLocation().getBlock().isEmpty() &&
            !disableFuelMode.contains(player.getUniqueId()) &&
            !player.isSneaking()) {
        if (!FuelMode.contains(player.getUniqueId()) &&
                player.getVelocity().length() >= 0.75 &&
                plugin.fuelManager.getFuelAmount(player, false) > 0) {
            FuelMode.add(player.getUniqueId());
        }
        if (duration.containsKey(player.getUniqueId()) &&
                duration.get(player.getUniqueId()) >= System.currentTimeMillis()) {
            player.setVelocity(player.getEyeLocation().getDirection().multiply(plugin.cfg.elytra_max_velocity));
        }
        if (FuelMode.contains(player.getUniqueId()) &&
                player.getVelocity().length() <= plugin.cfg.elytra_min_velocity &&
                player.getLocation().getBlockY() <= plugin.cfg.elytra_boost_max_height &&
                player.getLocation().getPitch() < 50) {
            if (player.getInventory().getChestplate() != null &&
                    player.getInventory().getChestplate().getType() == Material.ELYTRA) {
                int durability = player.getInventory().getChestplate().getType().getMaxDurability() -
                                         ((Damageable)player.getInventory().getChestplate().getItemMeta()).getDamage();
                if (durability <= plugin.cfg.elytra_durability_notify) {
                    player.sendMessage(I18n.format("user.elytra_enhance.durability_notify", durability));
                }
            }
            if (!plugin.fuelManager.useFuel(player)) {
                FuelMode.remove(player.getUniqueId());
                if (duration.containsKey(player.getUniqueId())) {
                    duration.remove(player.getUniqueId());
                }
                return;
            } else {
                duration.put(player.getUniqueId(), System.currentTimeMillis() + (plugin.cfg.elytra_power_duration * 1000));
                player.setVelocity(player.getEyeLocation().getDirection().multiply(plugin.cfg.elytra_max_velocity));
            }
            int fuelAmount = plugin.fuelManager.getFuelAmount(player, false);
            if (fuelAmount <= plugin.cfg.elytra_fuel_notify) {
                player.sendMessage(I18n.format("user.elytra_enhance.fuel_notify", fuelAmount));
            }
        }
        return;
    } else if (FuelMode.contains(player.getUniqueId())) {
        FuelMode.remove(player.getUniqueId());
    }
}
 
Example 19
Source File: SignsFeature.java    From AreaShop with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
	Block block = event.getClickedBlock();
	if (block == null) {
		return;
	}

	// Only listen to left and right clicks on blocks
	if (!(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) {
		return;
	}

	// Only care about clicking blocks
	if(!Materials.isSign(block.getType())) {
		return;
	}

	// Check if this sign belongs to a region
	RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
	if(regionSign == null) {
		return;
	}

	// Ignore players that are in sign link mode (which will handle the event itself)
	Player player = event.getPlayer();
	if(plugin.getSignlinkerManager().isInSignLinkMode(player)) {
		return;
	}

	// Get the clicktype
	GeneralRegion.ClickType clickType = null;
	if(player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
		clickType = GeneralRegion.ClickType.SHIFTLEFTCLICK;
	} else if(!player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
		clickType = GeneralRegion.ClickType.LEFTCLICK;
	} else if(player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
		clickType = GeneralRegion.ClickType.SHIFTRIGHTCLICK;
	} else if(!player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
		clickType = GeneralRegion.ClickType.RIGHTCLICK;
	}

	boolean ran = regionSign.runSignCommands(player, clickType);

	// Only cancel event if at least one command has been executed
	event.setCancelled(ran);
}
 
Example 20
Source File: Evasive.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void effect(MTEntityDamageByEntityEvent event) {
	if (!event.getPlayer().equals(event.getEvent().getEntity())) {
		return; //when event was not triggered by the armor
	}

	Player player = event.getPlayer();
	ItemStack tool = event.getTool();

	if (!player.hasPermission("minetinker.modifiers.evasive.use")) {
		return;
	}

	if (!modManager.hasMod(tool, this)) {
		return;
	}

	//cooldown checker
	Long time = System.currentTimeMillis();
	if (this.cooldownInSeconds > 0) {
		Long cd = cooldownTracker.get(player.getUniqueId().toString());
		if (cd != null) { //was on cooldown
			if (time - cd > this.cooldownInSeconds * 1000 || player.getGameMode() == GameMode.CREATIVE) {
				cooldownTracker.remove(player.getUniqueId().toString());
			} else {
				ChatWriter.logModifier(player, event, this, tool, "Cooldown");
				return; //still on cooldown
			}
		}
	}

	//calculating chance
	Random rand = new Random();
	int level = modManager.getModLevel(tool, this);

	double chance = this.percentPerLevel * level;
	String chanceCalculation = "Chance(" + chance;
	if (player.isSneaking()) {
		chance *= this.sneakMultiplier;
		chanceCalculation += " ->(Sneak) " + chance;
	}
	if (player.isSprinting()) {
		chance *= this.sprintMultiplier;
		chanceCalculation += " ->(Sprint) " + chance;
	}
	if (event.getEvent().getDamager() instanceof Player) {
		chance *= this.pvpMultiplier;
		chanceCalculation += " ->(PvP) " + chance;
	} else if (event.getEvent().getDamager() instanceof Arrow) {
		if (((Arrow) event.getEvent().getDamager()).getShooter() instanceof Player) {
			chance *= this.pvpMultiplier;
			chanceCalculation += " ->(PvP) " + chance;
		}
	}

	chanceCalculation += ")";

	int c = rand.nextInt(100);

	if (c > chance) {
		ChatWriter.logModifier(player, event, this, tool, chanceCalculation, "Failed(" + c + "/" + chance + ")");
		return;
	}


	if (this.cooldownInSeconds > 0)
		cooldownTracker.put(player.getUniqueId().toString(), time);

	event.setCancelled(true);
	if (getConfig().getBoolean("Sound", true))
		player.getWorld().playSound(player.getLocation(), Sound.ENTITY_BAT_TAKEOFF, 1.0f, 1.0f);

	ChatWriter.logModifier(player, event, this, tool, chanceCalculation, "Success(" + c + "/" + chance + ")");
}