use of org.bukkit.event.player.PlayerInteractEvent in project Citizens2 by CitizensDev.
the class GuidedWaypointProvider method createEditor.
@Override
public WaypointEditor createEditor(final CommandSender sender, CommandContext args) {
if (!(sender instanceof Player)) {
Messaging.sendErrorTr(sender, Messages.COMMAND_MUST_BE_INGAME);
return null;
}
final Player player = (Player) sender;
return new WaypointEditor() {
private final EntityMarkers<Waypoint> markers = new EntityMarkers<Waypoint>();
private boolean showPath;
@Override
public void begin() {
showPath();
Messaging.sendTr(player, Messages.GUIDED_WAYPOINT_EDITOR_BEGIN);
}
private void createWaypointMarkers() {
for (Waypoint waypoint : Iterables.concat(available, helpers)) {
markers.createMarker(waypoint, waypoint.getLocation().clone().add(0, 1, 0));
}
}
private void createWaypointMarkerWithData(Waypoint element) {
Entity entity = markers.createMarker(element, element.getLocation().clone().add(0, 1, 0));
if (entity == null)
return;
entity.setMetadata("citizens.waypointhashcode", new FixedMetadataValue(CitizensAPI.getPlugin(), element.hashCode()));
}
@Override
public void end() {
Messaging.sendTr(player, Messages.GUIDED_WAYPOINT_EDITOR_END);
markers.destroyMarkers();
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
if (event.getMessage().equalsIgnoreCase("toggle path")) {
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
togglePath();
}
});
} else if (event.getMessage().equalsIgnoreCase("clear")) {
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
available.clear();
helpers.clear();
if (showPath)
markers.destroyMarkers();
}
});
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (!event.getPlayer().equals(player) || event.getAction() == Action.PHYSICAL || event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null || Util.isOffHand(event))
return;
if (event.getPlayer().getWorld() != npc.getEntity().getWorld())
return;
event.setCancelled(true);
Location at = event.getClickedBlock().getLocation();
Waypoint element = new Waypoint(at);
if (player.isSneaking()) {
available.add(element);
Messaging.send(player, Messages.GUIDED_WAYPOINT_EDITOR_ADDED_AVAILABLE);
} else {
helpers.add(element);
Messaging.send(player, Messages.GUIDED_WAYPOINT_EDITOR_ADDED_GUIDE);
}
createWaypointMarkerWithData(element);
rebuildTree();
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (!event.getRightClicked().hasMetadata("citizens.waypointhashcode") || Util.isOffHand(event))
return;
int hashcode = event.getRightClicked().getMetadata("citizens.waypointhashcode").get(0).asInt();
Iterator<Waypoint> itr = Iterables.concat(available, helpers).iterator();
while (itr.hasNext()) {
if (itr.next().hashCode() == hashcode) {
itr.remove();
break;
}
}
}
private void showPath() {
for (Waypoint element : Iterables.concat(available, helpers)) {
createWaypointMarkerWithData(element);
}
}
private void togglePath() {
showPath = !showPath;
if (showPath) {
createWaypointMarkers();
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_SHOWING_MARKERS);
} else {
markers.destroyMarkers();
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_NOT_SHOWING_MARKERS);
}
}
};
}
use of org.bukkit.event.player.PlayerInteractEvent in project Glowstone by GlowstoneMC.
the class BlockPlacementHandler method handleRightClickBlock.
static void handleRightClickBlock(GlowPlayer player, ItemStack holding, EquipmentSlot slot, GlowBlock clicked, BlockFace face, Vector clickedLoc) {
// call interact event
PlayerInteractEvent event = EventFactory.getInstance().onPlayerInteract(player, Action.RIGHT_CLICK_BLOCK, slot, clicked, face);
// attempt to use interacted block
// DEFAULT is treated as ALLOW, and sneaking is always considered
boolean useInteractedBlock = event.useInteractedBlock() != Result.DENY;
if (useInteractedBlock && (!player.isSneaking() || bothHandsEmpty(player))) {
BlockType blockType = ItemTable.instance().getBlock(clicked.getType());
if (blockType != null) {
useInteractedBlock = blockType.blockInteract(player, clicked, face, clickedLoc);
} else {
ConsoleMessages.Info.Block.UNKNOWN_CLICKED.log(clicked.getType());
}
} else {
useInteractedBlock = false;
}
// follows ALLOW/DENY: default to if no block was interacted with
if (selectResult(event.useItemInHand(), !useInteractedBlock)) {
ItemType type = ItemTable.instance().getItem(holding.getType());
if (holding.getType() != Material.AIR && type.getContext().isBlockApplicable()) {
type.rightClickBlock(player, clicked, face, holding, clickedLoc, slot);
}
}
// make sure the player's up to date
// in case something is unimplemented or otherwise screwy on our side
revert(player, clicked);
revert(player, clicked.getRelative(face));
// if there's been a change in the held item, make it valid again
if (!InventoryUtil.isEmpty(holding) && holding.getType().getMaxDurability() > 0 && holding.getDurability() > holding.getType().getMaxDurability()) {
holding.setAmount(holding.getAmount() - 1);
holding.setDurability((short) 0);
}
if (holding.getAmount() <= 0) {
player.getInventory().setItem(slot, InventoryUtil.createEmptyStack());
} else {
// Set the item in `slot` to `holding`, as it was cloned before its amount was
// decremented.
player.getInventory().setItem(slot, holding);
}
}
use of org.bukkit.event.player.PlayerInteractEvent in project Glowstone by GlowstoneMC.
the class DiggingHandler method handle.
@Override
public void handle(GlowSession session, DiggingMessage message) {
GlowPlayer player = session.getPlayer();
GlowWorld world = player.getWorld();
EventFactory eventFactory = EventFactory.getInstance();
GlowBlock block = world.getBlockAt(message.getX(), message.getY(), message.getZ());
BlockFace face = BlockPlacementHandler.convertFace(message.getFace());
ItemStack holding = player.getItemInHand();
if (block.getRelative(face).getType() == Material.FIRE) {
block.getRelative(face).breakNaturally();
// returns to avoid breaking block in creative
return;
}
boolean blockBroken = false;
boolean revert = false;
Material material = block.getType();
switch(message.getState()) {
case START_DIGGING:
if (block.equals(player.getDigging()) || block.isLiquid()) {
return;
}
// call interact event
Action action = Action.LEFT_CLICK_BLOCK;
Block eventBlock = block;
if (player.getLocation().distanceSquared(block.getLocation()) > 36 || ExtraMaterialTags.AIR_VARIANTS.isTagged(material)) {
action = Action.LEFT_CLICK_AIR;
eventBlock = null;
}
PlayerInteractEvent interactEvent = eventFactory.onPlayerInteract(player, action, EquipmentSlot.HAND, eventBlock, face);
// attempt to use item in hand, that is, dig up the block
if (!BlockPlacementHandler.selectResult(interactEvent.useItemInHand(), true)) {
// the event was cancelled, get out of here
revert = true;
} else if (player.getGameMode() != GameMode.SPECTATOR) {
player.setDigging(null);
// emit damage event - cancel by default if holding a sword
boolean instaBreak = player.getGameMode() == GameMode.CREATIVE || block.getMaterialValues().getHardness() == 0;
BlockDamageEvent damageEvent = new BlockDamageEvent(player, block, player.getItemInHand(), instaBreak);
if (player.getGameMode() == GameMode.CREATIVE && holding != null && EnchantmentTarget.WEAPON.includes(holding.getType())) {
damageEvent.setCancelled(true);
}
eventFactory.callEvent(damageEvent);
// follow orders
if (damageEvent.isCancelled()) {
revert = true;
} else {
// in creative, break even if denied in the event, or the block
// can never be broken (client does not send DONE_DIGGING).
blockBroken = damageEvent.getInstaBreak();
if (!blockBroken) {
// TODO: add a delay here based on hardness
player.setDigging(block);
}
}
}
break;
case DiggingMessage.CANCEL_DIGGING:
player.setDigging(null);
break;
case DiggingMessage.FINISH_DIGGING:
// untrusted)
break;
case DiggingMessage.STATE_DROP_ITEM:
player.dropItemInHand(false);
return;
case DiggingMessage.STATE_DROP_ITEMSTACK:
player.dropItemInHand(true);
return;
case DiggingMessage.STATE_SHOT_ARROW_FINISH_EATING:
final ItemStack usageItem = player.getUsageItem();
if (usageItem != null) {
if (Objects.equals(usageItem, holding)) {
ItemType type = ItemTable.instance().getItem(usageItem.getType());
if (type != null && type instanceof ItemTimedUsage) {
((ItemTimedUsage) type).endUse(player, usageItem);
} else {
// todo: inform the player that this item cannot be consumed/used
}
} else {
// todo: verification against malicious clients
// todo: inform player their item is wrong
}
}
return;
case DiggingMessage.SWAP_ITEM_IN_HAND:
ItemStack main = player.getInventory().getItemInMainHand();
ItemStack off = player.getInventory().getItemInOffHand();
PlayerSwapHandItemsEvent event = EventFactory.getInstance().callEvent(new PlayerSwapHandItemsEvent(player, off, main));
if (!event.isCancelled()) {
player.getInventory().setItemInOffHand(main);
player.getInventory().setItemInMainHand(off);
player.updateInventory();
}
return;
default:
return;
}
if (blockBroken && !revert) {
// fire the block break event
BlockBreakEvent breakEvent = eventFactory.callEvent(new BlockBreakEvent(block, player));
if (breakEvent.isCancelled()) {
BlockPlacementHandler.revert(player, block);
return;
}
MaterialData data = block.getState().getData();
if (ExtraMaterialTags.BISECTED_BLOCKS.isTagged(material)) {
if (block.getRelative(BlockFace.DOWN).getType() == material) {
block = block.getRelative(BlockFace.DOWN);
}
}
BlockType blockType = ItemTable.instance().getBlock(material);
if (blockType != null) {
blockType.blockDestroy(player, block, face);
}
// destroy the block
if (!block.isEmpty() && !block.isLiquid() && (player.getGameMode() != GameMode.CREATIVE || blockType instanceof BlockContainer) && world.getGameRuleMap().getBoolean(GameRules.DO_TILE_DROPS)) {
Collection<ItemStack> drops = blockType.getDrops(block, holding);
if (blockType instanceof BlockContainer && player.getGameMode() == GameMode.CREATIVE) {
drops = ((BlockContainer) blockType).getContentDrops(block);
}
for (ItemStack drop : drops) {
GlowItem item = world.dropItemNaturally(block.getLocation(), drop);
item.setPickupDelay(30);
item.setBias(player);
}
}
player.addExhaustion(0.005f);
// STEP_SOUND actually is the block break particles
world.playEffectExceptTo(block.getLocation(), Effect.STEP_SOUND, block.getType().getId(), 64, player);
GlowBlockState state = block.getState();
block.setType(Material.AIR);
if (blockType != null) {
blockType.afterDestroy(player, block, face, state);
}
} else if (revert) {
// replace the block that wasn't really dug
BlockPlacementHandler.revert(player, block);
} else if (!ExtraMaterialTags.AIR_VARIANTS.isTagged(material)) {
BlockType blockType = ItemTable.instance().getBlock(material);
blockType.leftClickBlock(player, block, holding);
}
}
use of org.bukkit.event.player.PlayerInteractEvent in project Bukkit by Bukkit.
the class TimedRegisteredListenerTest method testEventClass.
@Test
public void testEventClass() throws EventException {
Listener listener = new Listener() {
};
EventExecutor executor = new EventExecutor() {
public void execute(Listener listener, Event event) {
}
};
TestPlugin plugin = new TestPlugin("Test");
PlayerInteractEvent interactEvent = new PlayerInteractEvent(null, null, null, null, null);
PlayerMoveEvent moveEvent = new PlayerMoveEvent(null, null, null);
BlockBreakEvent breakEvent = new BlockBreakEvent(null, null);
TimedRegisteredListener trl = new TimedRegisteredListener(listener, executor, EventPriority.NORMAL, plugin, false);
// Ensure that the correct event type is reported for a single event
trl.callEvent(interactEvent);
assertThat(trl.getEventClass(), is((Object) PlayerInteractEvent.class));
// Ensure that no superclass is used in lieu of the actual event, after two identical event types
trl.callEvent(interactEvent);
assertThat(trl.getEventClass(), is((Object) PlayerInteractEvent.class));
// Ensure that the closest superclass of the two events is chosen
trl.callEvent(moveEvent);
assertThat(trl.getEventClass(), is((Object) PlayerEvent.class));
// As above, so below
trl.callEvent(breakEvent);
assertThat(trl.getEventClass(), is((Object) Event.class));
// In the name of being thorough, check that it never travels down the hierarchy again.
trl.callEvent(breakEvent);
assertThat(trl.getEventClass(), is((Object) Event.class));
trl = new TimedRegisteredListener(listener, executor, EventPriority.NORMAL, plugin, false);
trl.callEvent(breakEvent);
assertThat(trl.getEventClass(), is((Object) BlockBreakEvent.class));
// Test moving up the class hierarchy by more than one class at a time
trl.callEvent(moveEvent);
assertThat(trl.getEventClass(), is((Object) Event.class));
}
use of org.bukkit.event.player.PlayerInteractEvent in project Citizens2 by CitizensDev.
the class WanderWaypointProvider method createEditor.
@Override
public WaypointEditor createEditor(final CommandSender sender, CommandContext args) {
return new WaypointEditor() {
boolean editingRegions = false;
EntityMarkers<Location> markers = new EntityMarkers<Location>();
@Override
public void begin() {
Messaging.sendTr(sender, Messages.WANDER_WAYPOINTS_BEGIN);
if (currentGoal != null) {
currentGoal.pause();
}
}
@Override
public void end() {
Messaging.sendTr(sender, Messages.WANDER_WAYPOINTS_END);
editingRegions = false;
if (currentGoal != null) {
currentGoal.unpause();
}
}
private String formatLoc(Location location) {
return String.format("[[%d]], [[%d]], [[%d]]", location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
if (!event.getPlayer().equals(sender))
return;
String message = event.getMessage().toLowerCase();
if (message.startsWith("xrange") || message.startsWith("yrange")) {
event.setCancelled(true);
int range = 0;
try {
range = Integer.parseInt(message.split(" ", 2)[1]);
if (range <= 0) {
range = 0;
}
if (message.startsWith("xrange")) {
xrange = range;
} else {
yrange = range;
}
if (currentGoal != null) {
currentGoal.setXYRange(xrange, yrange);
}
recalculateTree();
} catch (Exception ex) {
}
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
Messaging.sendTr(sender, Messages.WANDER_WAYPOINTS_RANGE_SET, xrange, yrange);
}
});
} else if (message.startsWith("regions")) {
event.setCancelled(true);
editingRegions = !editingRegions;
if (editingRegions) {
for (Location regionCentre : regionCentres) {
Entity entity = markers.createMarker(regionCentre, regionCentre);
entity.setMetadata("wandermarker", new FixedMetadataValue(CitizensAPI.getPlugin(), regionCentre));
}
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
Messaging.sendTr(sender, Messages.WANDER_WAYPOINTS_REGION_EDITING_START);
}
});
} else {
markers.destroyMarkers();
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (!event.getPlayer().equals(sender) || event.getAction() == Action.PHYSICAL || !npc.isSpawned() || event.getPlayer().getWorld() != npc.getEntity().getWorld() || Util.isOffHand(event))
return;
if (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_AIR) {
if (event.getClickedBlock() == null)
return;
event.setCancelled(true);
Location at = event.getClickedBlock().getLocation().add(0, 1, 0);
if (!regionCentres.contains(at)) {
regionCentres.add(at);
Entity entity = markers.createMarker(at, at);
entity.setMetadata("wandermarker", new FixedMetadataValue(CitizensAPI.getPlugin(), at));
Messaging.sendTr(sender, Messages.WANDER_WAYPOINTS_ADDED_REGION, formatLoc(at), regionCentres.size());
recalculateTree();
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (!sender.equals(event.getPlayer()) || !editingRegions || Util.isOffHand(event))
return;
if (!event.getRightClicked().hasMetadata("wandermarker"))
return;
regionCentres.remove(event.getRightClicked().getMetadata("wandermarker").get(0).value());
Messaging.sendTr(sender, Messages.WANDER_WAYPOINTS_REMOVED_REGION, formatLoc((Location) event.getRightClicked().getMetadata("wandermarker").get(0).value()), regionCentres.size());
recalculateTree();
}
};
}
Aggregations