org.bukkit.event.block.BlockPlaceEvent Java Examples

The following examples show how to use org.bukkit.event.block.BlockPlaceEvent. 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: BlockPlaceListener.java    From IridiumSkyblock with GNU General Public License v2.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMonitorBlockPlace(BlockPlaceEvent event) {
    try {
        final Block block = event.getBlock();
        final Location location = block.getLocation();
        final IslandManager islandManager = IridiumSkyblock.getIslandManager();
        final Island island = islandManager.getIslandViaLocation(location);
        if (island == null) return;

        if (!Utils.isBlockValuable(block)) return;

        final Material material = block.getType();
        final XMaterial xmaterial = XMaterial.matchXMaterial(material);
        island.valuableBlocks.compute(xmaterial.name(), (name, original) -> {
            if (original == null) return 1;
            return original + 1;
        });
        if (island.updating)
            island.tempValues.add(location);

        Bukkit.getScheduler().runTask(IridiumSkyblock.getInstance(), island::calculateIslandValue);
    } catch (Exception e) {
        IridiumSkyblock.getInstance().sendErrorMessage(e);
    }
}
 
Example #2
Source File: MiningCertainTaskType.java    From Quests with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
    QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId(), true);
    QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile();

    for (Quest quest : super.getRegisteredQuests()) {
        if (questProgressFile.hasStartedQuest(quest)) {
            QuestProgress questProgress = questProgressFile.getQuestProgress(quest);

            for (Task task : quest.getTasksOfType(super.getType())) {
                TaskProgress taskProgress = questProgress.getTaskProgress(task.getId());

                if (taskProgress.isCompleted()) {
                    continue;
                }

                if (task.getConfigValue("reverse-if-placed") != null && ((boolean) task.getConfigValue("reverse-if-placed"))) {
                    if (matchBlock(task, event.getBlock())) {
                        increment(task, taskProgress, -1);
                    }
                }
            }
        }
    }
}
 
Example #3
Source File: Scaffold.java    From AACAdditionPro with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPreBlockPlace(final BlockPlaceEvent event)
{
    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    // Not bypassed
    if (User.isUserInvalid(user, this.getModuleType())) {
        return;
    }

    // To prevent too fast scaffolding -> Timeout
    if (user.getTimestampMap().recentlyUpdated(TimestampKey.SCAFFOLD_TIMEOUT, timeout)) {
        event.setCancelled(true);
        InventoryUtils.syncUpdateInventory(user.getPlayer());
    }
}
 
Example #4
Source File: ProtectionsTests.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void blockPlaceShouldNotBeCancelledByOwner() {
    RegionsTests.loadRegionTypeCobble();
    Player player = mock(Player.class);
    UUID uuid = new UUID(1, 2);
    BlockPlaceEvent event = mock(BlockPlaceEvent.class);
    when(event.getBlockPlaced()).thenReturn(block);
    when(event.getPlayer()).thenReturn(player);
    when(player.getUniqueId()).thenReturn(uuid);

    HashMap<UUID, String> owners = new HashMap<>();
    owners.put(uuid, Constants.OWNER);
    Location regionLocation = new Location(Bukkit.getWorld("world"), 0,0,0);
    RegionManager.getInstance().addRegion(new Region("cobble", owners, regionLocation, RegionsTests.getRadii(), new HashMap<String, String>(),0));

    ProtectionHandler protectionHandler = new ProtectionHandler();

    protectionHandler.onBlockPlace(event);
    assertFalse(event.isCancelled());
}
 
Example #5
Source File: AnglePattern.java    From AACAdditionPro with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected int process(User user, BlockPlaceEvent event)
{
    final BlockFace placedFace = event.getBlock().getFace(event.getBlockAgainst());
    final Vector placedVector = new Vector(placedFace.getModX(), placedFace.getModY(), placedFace.getModZ());

    // If greater than 90
    if (user.getPlayer().getLocation().getDirection().angle(placedVector) > MAX_ANGLE) {
        if (++user.getScaffoldData().angleFails >= this.violationThreshold) {
            message = "Scaffold-Verbose | Player: " + user.getPlayer().getName() + " placed a block with a suspicious angle.";
            return 3;
        }
    }
    else if (user.getScaffoldData().angleFails > 0) {
        user.getScaffoldData().angleFails--;
    }
    return 0;
}
 
Example #6
Source File: BlockObjective.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
    String playerID = PlayerConverter.getID(event.getPlayer());
    // if the player has this objective, the event isn't canceled,
    // the block is correct and conditions are met
    if (containsPlayer(playerID) && selector.match(event.getBlock()) && checkConditions(playerID)) {
        // add the block to the total amount
        BlockData playerData = (BlockData) dataMap.get(playerID);
        playerData.add();
        // complete the objective
        if (playerData.getAmount() == neededAmount) {
            completeObjective(playerID);
        } else if (notify && playerData.getAmount() % notifyInterval == 0) {
            // or maybe display a notification
            if (playerData.getAmount() > neededAmount) {
                Config.sendNotify(playerID, "blocks_to_break",
                        new String[]{String.valueOf(playerData.getAmount() - neededAmount)},
                        "blocks_to_break,info");
            } else {
                Config.sendNotify(playerID, "blocks_to_place",
                        new String[]{String.valueOf(neededAmount - playerData.getAmount())},
                        "blocks_to_place,info");
            }
        }
    }
}
 
Example #7
Source File: AncientAltarListener.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent e) {
    if (altar == null || altar.isDisabled()) {
        return;
    }

    Block pedestal = e.getBlockPlaced().getRelative(BlockFace.DOWN);

    if (pedestal.getType() == Material.DISPENSER) {
        String id = BlockStorage.checkID(pedestal);

        if (id != null && id.equals(SlimefunItems.ANCIENT_PEDESTAL.getItemId())) {
            SlimefunPlugin.getLocalization().sendMessage(e.getPlayer(), "messages.cannot-place", true);
            e.setCancelled(true);
        }
    }
}
 
Example #8
Source File: LockListener.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlace(BlockPlaceEvent e) {

    final Block b = e.getBlock();

    if (b.getType() != Material.HOPPER) {
        return;
    }

    final Player p = e.getPlayer();

    if (!Util.isOtherShopWithinHopperReach(b, p)) {
        return;
    }

    if (QuickShop.getPermissionManager().hasPermission(p, "quickshop.other.open")) {
        MsgUtil.sendMessage(p, MsgUtil.getMessage("bypassing-lock", p));
        return;
    }

    MsgUtil.sendMessage(p, MsgUtil.getMessage("that-is-locked", p));
    e.setCancelled(true);
}
 
Example #9
Source File: RegionManager.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
private boolean regionNotAllowedInFeudalTown(BlockPlaceEvent event, Player player, Town town) {
    if (town != null) {
        Government government = GovernmentManager.getInstance().getGovernment(town.getGovernmentType());
        if (government.getGovernmentType() == GovernmentType.FEUDALISM) {
            boolean isOwner = town.getRawPeople().containsKey(player.getUniqueId()) &&
                    town.getRawPeople().get(player.getUniqueId()).contains(Constants.OWNER);
            if (!isOwner) {
                player.sendMessage(Civs.getPrefix() + LocaleManager.getInstance()
                        .getTranslationWithPlaceholders(player, "cant-build-feudal"));
                event.setCancelled(true);
                return true;
            }
        }
    }
    return false;
}
 
Example #10
Source File: BlockListener.java    From Carbon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSpongePlace(BlockPlaceEvent event) {
	if (event.getBlock().getState().getData().toString().equals("SPONGE(0)") && (isTouching(event.getBlock(), Material.WATER) || isTouching(event.getBlock(), Material.STATIONARY_WATER))) {
		int count = 0;
		for (int i = 1; i < 8; i++)
			for (int x = -i; x <= i; x++)
				for (int y = -i; y <= i; y++)
					for (int z = -i; z <= i; z++) {
						int a = event.getBlock().getX() + x;
						int b = event.getBlock().getY() + y;
						int c = event.getBlock().getZ() + z;
						if (event.getBlock().getWorld().getBlockAt(a, b, c).getType().equals(Material.WATER) || (event.getBlock().getWorld().getBlockAt(a, b, c).getType().equals(Material.STATIONARY_WATER))) {
							event.getBlock().getWorld().getBlockAt(a, b, c).setType(Material.AIR);
							event.getBlock().setData((byte) 1);
							count++;
							if (count >= 65)
								return;
						}
					}
	}
}
 
Example #11
Source File: NetherPortals.java    From askyblock with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prevents placing of blocks
 * 
 * @param e - event
 */
@EventHandler(priority = EventPriority.LOW)
public void onPlayerBlockPlace(final BlockPlaceEvent e) {
    if (DEBUG2)
        plugin.getLogger().info("DEBUG: " + e.getEventName());
    if (!Settings.newNether) {
        if (e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_nether")
                || e.getPlayer().getWorld().getName().equalsIgnoreCase(Settings.worldName + "_the_end")) {
            if (VaultHelper.checkPerm(e.getPlayer(), Settings.PERMPREFIX + "mod.bypassprotect")) {
                return;
            }
            if (!awayFromSpawn(e.getPlayer()) && !e.getPlayer().isOp()) {
                e.setCancelled(true);
            }
        }
    }
}
 
Example #12
Source File: BlockTransformEvent.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get whether the {@link Block} was probably transformed by a player.
 *
 * @return Whether the event is considered "manual."
 */
public final boolean isManual() {
  final Event event = getCause();

  if (event instanceof BlockPlaceEvent
      || event instanceof BlockBreakEvent
      || event instanceof PlayerBucketEmptyEvent
      || event instanceof PlayerBucketFillEvent) return true;

  if (event instanceof BlockIgniteEvent) {
    BlockIgniteEvent igniteEvent = (BlockIgniteEvent) event;
    if (igniteEvent.getCause() == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL
        && igniteEvent.getIgnitingEntity() != null) {
      return true;
    }
  }

  if (event instanceof ExplosionPrimeByEntityEvent
      && ((ExplosionPrimeByEntityEvent) event).getPrimer() instanceof Player) {
    return true;
  }

  return false;
}
 
Example #13
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void regionShouldBeCreatedWithAllGroupReqs() {
    loadRegionTypeCobble3();

    BlockPlaceEvent event3 = mock(BlockPlaceEvent.class);
    when(event3.getBlockPlaced()).thenReturn(TestUtil.block3);
    ItemStack cobbleStack = TestUtil.createItemStack(Material.COBBLESTONE);
    doReturn(cobbleStack).when(event3).getItemInHand();
    BlockPlaceEvent event2 = mock(BlockPlaceEvent.class);
    when(event2.getBlockPlaced()).thenReturn(TestUtil.block2);
    when(event2.getItemInHand()).thenReturn(cobbleStack);
    BlockPlaceEvent event1 = mock(BlockPlaceEvent.class);
    when(event1.getPlayer()).thenReturn(TestUtil.player);
    when(event1.getBlockPlaced()).thenReturn(TestUtil.blockUnique);
    List<String> lore = new ArrayList<>();
    lore.add(TestUtil.player.getUniqueId().toString());
    lore.add("Civs Cobble");
    doReturn(TestUtil.mockItemStack(Material.CHEST, 1, "Civs Cobble", lore)).when(event1).getItemInHand();

    RegionListener regionListener = new RegionListener();
    regionListener.onBlockPlace(event2);
    regionListener.onBlockPlace(event3);
    regionListener.onBlockPlace(event1);
    assertEquals("cobble", RegionManager.getInstance().getRegionAt(TestUtil.blockUnique.getLocation()).getType());
}
 
Example #14
Source File: GeyserBukkitBlockPlaceListener.java    From Geyser with MIT License 6 votes vote down vote up
@EventHandler
public void place(final BlockPlaceEvent event) {
    for (GeyserSession session : connector.getPlayers().values()) {
        if (event.getPlayer() == Bukkit.getPlayer(session.getPlayerEntity().getUsername())) {
            LevelSoundEventPacket placeBlockSoundPacket = new LevelSoundEventPacket();
            placeBlockSoundPacket.setSound(SoundEvent.PLACE);
            placeBlockSoundPacket.setPosition(Vector3f.from(event.getBlockPlaced().getX(), event.getBlockPlaced().getY(), event.getBlockPlaced().getZ()));
            placeBlockSoundPacket.setBabySound(false);
            String javaBlockId;
            if (isLegacy) {
                javaBlockId = BlockTranslator.getJavaIdBlockMap().inverse().get(GeyserBukkitWorldManager.getLegacyBlock(session,
                        event.getBlockPlaced().getX(), event.getBlockPlaced().getY(), event.getBlockPlaced().getZ(), isViaVersion));
            } else {
                javaBlockId = event.getBlockPlaced().getBlockData().getAsString();
            }
            placeBlockSoundPacket.setExtraData(BlockTranslator.getBedrockBlockId(BlockTranslator.getJavaIdBlockMap().get(javaBlockId)));
            placeBlockSoundPacket.setIdentifier(":");
            session.sendUpstreamPacket(placeBlockSoundPacket);
            session.setLastBlockPlacePosition(null);
            session.setLastBlockPlacedId(null);
            break;
        }
    }
}
 
Example #15
Source File: FeatureEmulation.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
	Player player = event.getPlayer();
	Connection connection = ProtocolSupportAPI.getConnection(player);
	if (
		(connection != null) &&
		(connection.getVersion().getProtocolType() == ProtocolType.PC) &&
		connection.getVersion().isBefore(ProtocolVersion.MINECRAFT_1_9)
	) {
		BlockDataEntry blockdataentry = MinecraftBlockData.get(MaterialAPI.getBlockDataNetworkId(event.getBlock().getBlockData()));
		player.playSound(
			event.getBlock().getLocation(),
			blockdataentry.getBreakSound(),
			SoundCategory.BLOCKS,
			(blockdataentry.getVolume() + 1.0F) / 2.0F,
			blockdataentry.getPitch() * 0.8F
		);
	}
}
 
Example #16
Source File: BlockListenerTest.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldAllowPlaceEvent() {
    // given
    Player player = mock(Player.class);
    BlockPlaceEvent event = mock(BlockPlaceEvent.class);
    given(event.getPlayer()).willReturn(player);
    given(listenerService.shouldCancelEvent(player)).willReturn(false);

    // when
    listener.onBlockPlace(event);

    // then
    verify(event).getPlayer();
    verifyNoMoreInteractions(event);
}
 
Example #17
Source File: IslandGuard.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets spawners to their type
 * @param e - event
 */
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onSpawnerBlockPlace(final BlockPlaceEvent e) {
    if (DEBUG)
        plugin.getLogger().info("DEBUG: block place");
    if (inWorld(e.getPlayer()) && Util.playerIsHolding(e.getPlayer(), Material.MOB_SPAWNER)) {
        if (DEBUG)
            plugin.getLogger().info("DEBUG: in world");
        // Get item in hand
        for (ItemStack item : Util.getPlayerInHandItems(e.getPlayer())) {
            if (item.getType().equals(Material.MOB_SPAWNER) && item.hasItemMeta() && item.getItemMeta().hasLore()) {
                if (DEBUG)
                    plugin.getLogger().info("DEBUG: spawner in hand with lore");
                List<String> lore = item.getItemMeta().getLore();
                if (!lore.isEmpty()) {
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: lore is not empty");
                    for (EntityType type : EntityType.values()) {
                        if (lore.get(0).equals(Util.prettifyText(type.name()))) {
                            // Found the spawner type
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: found type");
                            e.getBlock().setType(Material.MOB_SPAWNER);
                            CreatureSpawner cs = (CreatureSpawner)e.getBlock().getState();
                            cs.setSpawnedType(type);
                        }
                    }
                    // Spawner type not found - do anything : it may be another plugin's spawner
                }
            }
        }
    }
}
 
Example #18
Source File: GameMap.java    From AnnihilationPro with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void blockPlaceCheck(BlockPlaceEvent event)
{
	if(event.getPlayer().getGameMode() != GameMode.CREATIVE)
	{
		Block b = event.getBlock();
		UnplaceableBlock block = this.unplaceableBlocks.get(b.getType());
		if(block != null)
		{
			if(block.isData((byte)-1) || block.isData(b.getData()))
				event.setCancelled(true);
		}
	}
}
 
Example #19
Source File: PlayerEvents.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onBlockPlaceEvent(BlockPlaceEvent event)
{
    final Player player = event.getPlayer();
    if (!blockLimitsEnabled || !plugin.getWorldManager().isSkyAssociatedWorld(player.getWorld())) {
        return; // Skip
    }

    IslandInfo islandInfo = plugin.getIslandInfo(event.getBlock().getLocation());
    if (islandInfo == null) {
        return;
    }
    Material type = event.getBlock().getType();
    BlockLimitLogic.CanPlace canPlace = plugin.getBlockLimitLogic().canPlace(type, islandInfo);
    if (canPlace == BlockLimitLogic.CanPlace.UNCERTAIN) {
        event.setCancelled(true);
        final String key = "usb.block-limits";
        if (!PatienceTester.isRunning(player, key)) {
            PatienceTester.startRunning(player, key);
            player.sendMessage(tr("\u00a74{0} is limited. \u00a7eScanning your island to see if you are allowed to place more, please be patient", ItemStackUtil.getItemName(new ItemStack(type))));
            plugin.fireAsyncEvent(new IslandInfoEvent(player, islandInfo.getIslandLocation(), new Callback<IslandScore>() {
                @Override
                public void run() {
                    player.sendMessage(tr("\u00a7e... Scanning complete, you can try again"));
                    PatienceTester.stopRunning(player, key);
                }
            }));
        }
        return;
    }
    if (canPlace == BlockLimitLogic.CanPlace.NO) {
        event.setCancelled(true);
        player.sendMessage(tr("\u00a74You''ve hit the {0} limit!\u00a7e You can''t have more of that type on your island!\u00a79 Max: {1,number}", ItemStackUtil.getItemName(new ItemStack(type)), plugin.getBlockLimitLogic().getLimit(type)));
        return;
    }
    plugin.getBlockLimitLogic().incBlockCount(islandInfo.getIslandLocation(), type);
}
 
Example #20
Source File: UnitMaterial.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void onBlockPlaced(BlockPlaceEvent event) {
	event.setCancelled(true);
	CivMessage.sendError(event.getPlayer(), "Cannot place this item");
	event.getPlayer().updateInventory();
}
 
Example #21
Source File: PaperPatch.java    From ViaVersion with MIT License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlace(BlockPlaceEvent e) {
    if (isOnPipe(e.getPlayer())) {
        Location location = e.getPlayer().getLocation();
        Location diff = location.clone().subtract(e.getBlock().getLocation().add(0.5D, 0, 0.5D));
        Material block = e.getBlockPlaced().getType();
        if (isPlacable(block)) {
            return;
        }
        if (location.getBlock().equals(e.getBlock())) {
            e.setCancelled(true);
        } else {
            if (location.getBlock().getRelative(BlockFace.UP).equals(e.getBlock())) {
                e.setCancelled(true);
            } else {
                // Within radius of block
                if (Math.abs(diff.getX()) <= 0.8 && Math.abs(diff.getZ()) <= 0.8D) {
                    // Are they on the edge / shifting ish
                    if (diff.getY() <= 0.1D && diff.getY() >= -0.1D) {
                        e.setCancelled(true);
                        return;
                    }
                    BlockFace relative = e.getBlockAgainst().getFace(e.getBlock());
                    // Are they towering up, (handles some latency)
                    if (relative == BlockFace.UP) {
                        if (diff.getY() < 1D && diff.getY() >= 0D) {
                            e.setCancelled(true);
                        }
                    }
                }
            }
        }
    }
}
 
Example #22
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void regionShouldNotBeCreatedWithoutAllReqs() {
    loadRegionTypeCobble2();

    BlockPlaceEvent event1 = mock(BlockPlaceEvent.class);
    when(event1.getPlayer()).thenReturn(TestUtil.player);
    when(event1.getBlockPlaced()).thenReturn(TestUtil.blockUnique);
    doReturn(TestUtil.createUniqueItemStack(Material.CHEST, "Civs Cobble")).when(event1).getItemInHand();
    RegionListener regionListener = new RegionListener();
    regionListener.onBlockPlace(event1);
    assertNull(RegionManager.getInstance().getRegionAt(TestUtil.blockUnique.getLocation()));
}
 
Example #23
Source File: ChestListener.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
void onBlockPlace(BlockPlaceEvent event) {
	Block block = event.getBlock();
	if (Utils.isChest(block.getType())) {
		plugin.onChestPlacement(event.getPlayer(), block);
	}
}
 
Example #24
Source File: ItemShortcut.java    From Minepacks with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onBlockPlace(BlockPlaceEvent event)
{
	if(isItemShortcut(event.getItemInHand()))
	{
		event.getPlayer().performCommand(openCommand);
		event.setCancelled(true);
	}
}
 
Example #25
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void strangeRegionShapeShouldBuildProperly() {
    loadRegionTypeRectangle();

    BlockPlaceEvent event3 = mock(BlockPlaceEvent.class);
    when(event3.getBlockPlaced()).thenReturn(TestUtil.block8);
    ItemStack cobbleStack = TestUtil.createItemStack(Material.COBBLESTONE);
    doReturn(cobbleStack).when(event3).getItemInHand();
    BlockPlaceEvent event2 = mock(BlockPlaceEvent.class);
    when(event2.getBlockPlaced()).thenReturn(TestUtil.block7);
    doReturn(cobbleStack).when(event2).getItemInHand();
    BlockPlaceEvent event1 = mock(BlockPlaceEvent.class);
    when(event1.getPlayer()).thenReturn(TestUtil.player);
    when(event1.getBlockPlaced()).thenReturn(TestUtil.blockUnique4);
    List<String> lore = new ArrayList<>();
    lore.add(TestUtil.player.getUniqueId().toString());
    lore.add("Civs Cobble");
    ItemStack itemStack = TestUtil.mockItemStack(Material.CHEST, 1, "Civs Cobble", lore);
    doReturn(itemStack).when(event1).getItemInHand();


    RegionListener regionListener = new RegionListener();
    regionListener.onBlockPlace(event2);
    regionListener.onBlockPlace(event3);
    regionListener.onBlockPlace(event1);

    assertNotNull(RegionManager.getInstance().getRegionAt(TestUtil.blockUnique4.getLocation()));
}
 
Example #26
Source File: WoolObjective.java    From CardinalPGM with MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event) {
    if (event.getBlock().equals(place.getBlock())) {
        if (event.getBlock().getType().equals(Material.WOOL)) {
            if (((Wool) event.getBlock().getState().getData()).getColor().equals(color)) {
                if (Teams.getTeamByPlayer(event.getPlayer()).orNull() == team) {
                    this.complete = true;
                    if (this.show)
                        ChatUtil.getGlobalChannel().sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.WHITE + "{0}", new LocalizedChatMessage(ChatConstant.UI_OBJECTIVE_PLACED, team.getColor() + event.getPlayer().getName() + ChatColor.WHITE, team.getCompleteName() + ChatColor.WHITE, MiscUtil.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.WHITE)));
                    Fireworks.spawnFireworks(place.getCenterBlock().getAlignedVector(), 3, 6, MiscUtil.convertChatColorToColor(MiscUtil.convertDyeColorToChatColor(color)), 1);
                    ObjectiveCompleteEvent compEvent = new ObjectiveCompleteEvent(this, event.getPlayer());
                    Bukkit.getServer().getPluginManager().callEvent(compEvent);
                    event.setCancelled(false);
                } else {
                    event.setCancelled(true);
                    if (this.show)
                        ChatUtil.sendWarningMessage(event.getPlayer(), "You may not complete the other team's objective.");
                }
            } else {
                event.setCancelled(true);
                if (this.show)
                    ChatUtil.sendWarningMessage(event.getPlayer(), new LocalizedChatMessage(ChatConstant.ERROR_BLOCK_PLACE, MiscUtil.convertDyeColorToChatColor(color) + color.name().toUpperCase().replaceAll("_", " ") + " WOOL" + ChatColor.RED));
            }
        } else {
            event.setCancelled(true);
            if (this.show)
                ChatUtil.sendWarningMessage(event.getPlayer(), new LocalizedChatMessage(ChatConstant.ERROR_BLOCK_PLACE, MiscUtil.convertDyeColorToChatColor(color) + color.name().toUpperCase().replaceAll("_", " ") + " WOOL" + ChatColor.RED));
        }
    }
}
 
Example #27
Source File: BlockPlaceAgainstRegion.java    From CardinalPGM with MIT License 5 votes vote down vote up
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
    if (!event.isCancelled() && region.contains(new BlockRegion(null, event.getBlock().getLocation().toVector())) && filter.evaluate(event.getPlayer(), event.getBlockPlaced(), event).equals(FilterState.DENY)) {
        event.setCancelled(true);
        event.getPlayer().closeInventory();
        ChatUtil.sendWarningMessage(event.getPlayer(), message);
    }
}
 
Example #28
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void regionShouldNotBeCreatedIfNotAllReqs() {
    loadRegionTypeCobble2();

    InventoryView transaction = mock(InventoryView.class);
    when(transaction.getPlayer()).thenReturn(TestUtil.player);
    InventoryCloseEvent inventoryCloseEvent = new InventoryCloseEvent(transaction);
    BlockPlaceEvent event3 = mock(BlockPlaceEvent.class);
    when(event3.getBlockPlaced()).thenReturn(TestUtil.block4);
    ItemStack cobbleStack = TestUtil.createItemStack(Material.COBBLESTONE);
    doReturn(cobbleStack).when(event3).getItemInHand();
    BlockPlaceEvent event2 = mock(BlockPlaceEvent.class);
    when(event2.getBlockPlaced()).thenReturn(TestUtil.block2);
    doReturn(cobbleStack).when(event2).getItemInHand();
    BlockPlaceEvent event1 = mock(BlockPlaceEvent.class);
    when(event1.getPlayer()).thenReturn(TestUtil.player);
    when(event1.getBlockPlaced()).thenReturn(TestUtil.blockUnique);
    doReturn(TestUtil.createUniqueItemStack(Material.CHEST, "Civs Cobble")).when(event1).getItemInHand();


    MenuManager.getInstance().onInventoryClose(inventoryCloseEvent);
    RegionListener regionListener = new RegionListener();
    regionListener.onBlockPlace(event2);
    regionListener.onBlockPlace(event3);
    regionListener.onBlockPlace(event1);
    assertNull(RegionManager.getInstance().getRegionAt(TestUtil.blockUnique.getLocation()));
}
 
Example #29
Source File: DWorldListener.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event) {
    Block block = event.getBlock();

    DGameWorld gameWorld = (DGameWorld) plugin.getGameWorld(block.getWorld());
    if (gameWorld == null) {
        return;
    }

    if (gameWorld.onPlace(event.getPlayer(), block, event.getBlockAgainst(), event.getItemInHand())) {
        event.setCancelled(true);
    }
}
 
Example #30
Source File: PlayerInteractListener.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
  public void onBlockPlaced(BlockPlaceEvent e) {
GameMap gMap = MatchManager.get().getPlayerMap(e.getPlayer());
if (gMap == null) {
	if (e.getBlockPlaced().getType().equals(Material.CHEST) || e.getBlock().getType().equals(Material.TRAPPED_CHEST)) {
		GameMap map = GameMap.getMap(e.getPlayer().getWorld().getName());
		if (map == null) {
			return;
		}
		if (map.isEditing()) {
			Location loc = e.getBlock().getLocation();
			Player player = e.getPlayer();
			new BukkitRunnable() {
				@Override
				public void run() {
					map.addChest((Chest) loc.getBlock().getState(), map.getChestPlacementType());
					if (map.getChestPlacementType() == ChestPlacementType.NORMAL) {
						player.sendMessage(new Messaging.MessageFormatter().setVariable("mapname", map.getDisplayName()).format("maps.addChest"));
					} else if (map.getChestPlacementType() == ChestPlacementType.CENTER) {
						player.sendMessage(new Messaging.MessageFormatter().setVariable("mapname", map.getDisplayName()).format("maps.addCenterChest"));
					}
				}
			}.runTaskLater(SkyWarsReloaded.get(), 2L);
		}
	}
}
  }