Java Code Examples for org.bukkit.event.block.BlockPlaceEvent#getPlayer()

The following examples show how to use org.bukkit.event.block.BlockPlaceEvent#getPlayer() . 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: 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 2
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 3
Source File: SignEditListener.java    From NyaaUtils with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
    Block block = event.getBlock();
    ItemStack item = event.getItemInHand();
    if (block != null && item != null &&
            isSign(item.getType()) &&
            isSign(block.getType())) {
        Player player = event.getPlayer();
        if ((player.isOp() && player.getGameMode().equals(GameMode.CREATIVE)) ||
                !item.hasItemMeta() || !(item.getItemMeta() instanceof BlockStateMeta) ||
                !player.hasPermission("nu.se.player")) {
            return;
        }
        SignContent c = SignContent.fromItemStack(item);
        if (!c.getContent().isEmpty()) {
            signContents.put(event.getPlayer().getUniqueId(), c);
        }
    }
}
 
Example 4
Source File: BuildEvent.java    From MCAuthenticator with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPlace(BlockPlaceEvent event) {
    Player player = event.getPlayer();
    User u = instance.getCache().get(player.getUniqueId());

    if (u != null && u.authenticated()) return;

    event.setCancelled(true);
}
 
Example 5
Source File: ChestProtectListener.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(ignoreCancelled = true)
void onBlockPlace(BlockPlaceEvent event) {
	Block block = event.getBlock();
	Material type = block.getType();
	Player player = event.getPlayer();
	if (Utils.isChest(type)) {
		if (plugin.getProtectedChests().isChestProtected(block, player)) {
			Log.debug("Cancelled placing of chest block by '" + player.getName() + "' at '"
					+ Utils.getLocationString(block) + "': Protected chest nearby");
			event.setCancelled(true);
		}
	} else if (type == Material.HOPPER) {
		if (plugin.getProtectedChests().isProtectedChestAroundHopper(block, player)) {
			Log.debug("Cancelled placing of hopper block by '" + player.getName() + "' at '"
					+ Utils.getLocationString(block) + "': Protected chest nearby");
			event.setCancelled(true);
		}
	} else if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.ACTIVATOR_RAIL) {
		Block upperBlock = block.getRelative(BlockFace.UP);
		if (Utils.isChest(upperBlock.getType()) && plugin.getProtectedChests().isChestProtected(upperBlock, player)) {
			Log.debug("Cancelled placing of rail block by '" + player.getName() + "' at '"
					+ Utils.getLocationString(block) + "': Protected chest nearby");
			event.setCancelled(true);
			return;
		}
	}
}
 
Example 6
Source File: RegionInteractListener.java    From NovaGuilds with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) { //PLACING
	Player player = event.getPlayer();
	NovaPlayer nPlayer = PlayerManager.getPlayer(player);

	if(RegionManager.get(event.getBlock()) != null && (!plugin.getRegionManager().canInteract(player, event.getBlock()) || (!nPlayer.getPreferences().getBypass() && !nPlayer.hasPermission(GuildPermission.BLOCK_PLACE)))) {
		event.setCancelled(true);
		Message.CHAT_REGION_DENY_INTERACT.send(player);
	}
}
 
Example 7
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);
		}
	}
}
  }
 
Example 8
Source File: TrapListener.java    From BedwarsRel with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onPlace(BlockPlaceEvent place) {
  if (place.isCancelled()) {
    return;
  }

  Player player = place.getPlayer();
  Game game = BedwarsRel.getInstance().getGameManager().getGameOfPlayer(player);

  if (game == null) {
    return;
  }

  if (game.getState() != GameState.RUNNING) {
    return;
  }

  Team team = game.getPlayerTeam(player);
  if (team == null) {
    place.setCancelled(true);
    place.setBuild(false);
    return;
  }

  Trap trap = new Trap();
  trap.create(game, team, place.getBlockPlaced().getLocation());
  game.getRegion().addPlacedUnbreakableBlock(place.getBlockPlaced(), null);
}
 
Example 9
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 10
Source File: PlayerBlockModifyEventHandler.java    From SuperVanish with Mozilla Public License 2.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onPlace(BlockPlaceEvent e) {
    try {
        if (plugin.getSettings().getBoolean("RestrictiveOptions.PreventBlockPlacing")) {
            Player p = e.getPlayer();
            Collection<UUID> vanishedPlayers = plugin.getVanishStateMgr().getOnlineVanishedPlayers();
            if (vanishedPlayers.contains(p.getUniqueId()) && !p.hasPermission("sv.placeblocks")) {
                e.setCancelled(true);
                plugin.sendMessage(e.getPlayer(), "BlockPlaceDenied", e.getPlayer());
            }
        }
    } catch (Exception er) {
        plugin.logException(er);
    }
}
 
Example 11
Source File: PlaceEvent.java    From Survival-Games with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
  public void onBlockPlace(BlockPlaceEvent event) {
      Player p = event.getPlayer();
      int id  = GameManager.getInstance().getPlayerGameId(p);

      if(id == -1){
          int gameblockid = GameManager.getInstance().getBlockGameId(event.getBlock().getLocation());
          if(gameblockid != -1){
              if(GameManager.getInstance().getGame(gameblockid).getGameMode() != Game.GameMode.DISABLED){
                  event.setCancelled(true);
              }
          }
          return;
      }


      Game g = GameManager.getInstance().getGame(id);
      if(g.isPlayerInactive(p)){
          return;
      }
      if(g.getMode() == Game.GameMode.DISABLED){
          return;
      }
      if(g.getMode() != Game.GameMode.INGAME){
          event.setCancelled(true);
          return;

      }

      if(allowedPlace.contains(event.getBlock().getType())) {
      	event.setCancelled(false);
}else {
	event.setCancelled(true);
}
  }
 
Example 12
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 onBlockPlace(BlockPlaceEvent event) {
    Player player = event.getPlayer();
    if (GameManager.getInstance().isSpectator(player)) {
        event.setCancelled(true);
    }
}
 
Example 13
Source File: CivilianListener.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority=EventPriority.LOW, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
    ItemStack is = event.getItemInHand();
    if (event.getPlayer() == null || !CVItem.isCivsItem(is)) {
        return;
    }
    CivItem civItem = CivItem.getFromItemStack(is);
    Civilian civilian = CivilianManager.getInstance().getCivilian(event.getPlayer().getUniqueId());
    if (!civItem.isPlaceable()) {
        event.setCancelled(true);
        event.getPlayer().sendMessage(Civs.getPrefix() + LocaleManager.getInstance()
                .getTranslationWithPlaceholders(event.getPlayer(),
                "not-allowed-place").replace("$1", civItem.getDisplayName()));
        return;
    }
    if (civItem instanceof TownType) {
        Town town = TownManager.getInstance().getTownAt(event.getBlockPlaced().getLocation());
        if (town != null) {
            TownManager.getInstance().placeTown(event.getPlayer(), town.getName(), town);
        }
        event.setCancelled(true);
        return;
    }
    CVItem cvItem = CVItem.createFromItemStack(is);
    if (cvItem.getLore() == null || cvItem.getLore().isEmpty()) {
        ArrayList<String> lore = new ArrayList<>();
        lore.add(civilian.getUuid().toString());
        lore.add(cvItem.getDisplayName());
        lore.addAll(Util.textWrap(civilian, Util.parseColors(civItem.getDescription(civilian.getLocale()))));
        cvItem.setLore(lore);
    }
    BlockLogger blockLogger = BlockLogger.getInstance();
    blockLogger.putBlock(Region.idToLocation(Region.blockLocationToString(event.getBlock().getLocation())), cvItem);
}
 
Example 14
Source File: LWCBlockListener.java    From Modern-LWC with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
    if (!LWC.ENABLED) {
        return;
    }

    LWC lwc = plugin.getLWC();
    Player player = event.getPlayer();
    Block block = event.getBlockPlaced();

    ProtectionCache cache = lwc.getProtectionCache();
    String cacheKey = cache.cacheKey(block.getLocation());

    // In the event they place a block, remove any known nulls there
    if (cache.isKnownNull(cacheKey)) {
        cache.remove(cacheKey);
    }

    // check if the block is blacklisted
    if (blacklistedBlocks.contains(block.getType())) {
        // it's blacklisted, check for a protected chest
        for (Protection protection : lwc.findAdjacentProtectionsOnAllSides(block)) {
            if (protection != null) {
                if (!lwc.canAccessProtection(player, protection)
                        || (protection.getType() == Protection.Type.DONATION
                        && !lwc.canAdminProtection(player, protection))) {
                    // they can't access the protection ..
                    event.setCancelled(true);
                    return;
                }
            }
        }
    }
}
 
Example 15
Source File: BlockPlaceListener.java    From IridiumSkyblock with GNU General Public License v2.0 4 votes vote down vote up
@EventHandler
public void onBlockPlace(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;

        final Player player = event.getPlayer();
        final User user = User.getUser(player);

        final Material material = block.getType();
        final XMaterial xmaterial = XMaterial.matchXMaterial(material);
        final Config config = IridiumSkyblock.getConfiguration();
        final Integer max = config.limitedBlocks.get(xmaterial);
        if (max != null) {
            if (island.valuableBlocks.getOrDefault(xmaterial.name(), 0) >= max) {
                player.sendMessage(Utils.color(IridiumSkyblock.getMessages().blockLimitReached
                        .replace("%prefix%", config.prefix)));
                event.setCancelled(true);
                return;
            }
        }

        if (user.islandID == island.getId()) {
            for (Mission mission : IridiumSkyblock.getMissions().missions) {
                final Map<String, Integer> levels = island.getMissionLevels();
                levels.putIfAbsent(mission.name, 1);

                final MissionData level = mission.levels.get(levels.get(mission.name));
                if (level == null) continue;
                if (level.type != MissionType.BLOCK_PLACE) continue;

                final List<String> conditions = level.conditions;

                if (
                        conditions.isEmpty()
                                ||
                                conditions.contains(xmaterial.name())
                                ||
                                conditions.contains(((Crops) block.getState().getData()).getState().toString())
                )
                    island.addMission(mission.name, 1);
            }
        }

        if (!island.getPermissions(user).placeBlocks)
            event.setCancelled(true);
    } catch (Exception e) {
        IridiumSkyblock.getInstance().sendErrorMessage(e);
    }
}
 
Example 16
Source File: BlocksPlacedListener.java    From Statz with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(final BlockPlaceEvent event) {

    final PlayerStat stat = PlayerStat.BLOCKS_PLACED;

    // Get player
    final Player player = event.getPlayer();

    // Do general check
    if (!plugin.doGeneralCheck(player, stat))
        return;

    Block blockPlaced = event.getBlockPlaced();
    final String worldName = blockPlaced.getWorld().getName();

    PlayerStatSpecification specification = new BlocksPlacedSpecification(player.getUniqueId(), 1,
            worldName, blockPlaced.getType());

    // Update value to new stat.
    plugin.getDataManager().setPlayerInfo(player.getUniqueId(), stat, specification.constructQuery());

}
 
Example 17
Source File: EntityLimits.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prevents placing of blocks
 *
 * @param e - event
 */
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerBlockPlace(final BlockPlaceEvent e) {
    if (DEBUG) {
        plugin.getLogger().info("DEBUG: " + e.getEventName());
        if (e.getPlayer() == null) {
            plugin.getLogger().info("DEBUG: player is null");
        } else {
            plugin.getLogger().info("DEBUG: block placed by " + e.getPlayer().getName());
        }
        plugin.getLogger().info("DEBUG: Block is " + e.getBlock().toString());
    }

    if (Settings.allowedFakePlayers.contains(e.getPlayer().getName())) return;

    // plugin.getLogger().info(e.getEventName());
    if (IslandGuard.inWorld(e.getPlayer())) {
        // This permission bypasses protection
        if (e.getPlayer().isOp() || VaultHelper.checkPerm(e.getPlayer(), Settings.PERMPREFIX + "mod.bypassprotect")) {
            return;
        }
        //plugin.getLogger().info("DEBUG: checking is inside protection area");
        Island island = plugin.getGrid().getProtectedIslandAt(e.getBlock().getLocation());
        // Outside of island protection zone
        if (island == null) {
            if (!Settings.defaultWorldSettings.get(SettingsFlag.PLACE_BLOCKS)) {
                Util.sendMessage(e.getPlayer(), ChatColor.RED + plugin.myLocale(e.getPlayer().getUniqueId()).islandProtected);
                e.setCancelled(true);
            }
            return;
        }
        if (actionAllowed(e.getPlayer(), e.getBlock().getLocation(), SettingsFlag.PLACE_BLOCKS))  {
            // Check how many placed
            //plugin.getLogger().info("DEBUG: block placed " + e.getBlock().getType());
            String type = e.getBlock().getType().toString();
            if (!e.getBlock().getState().getClass().getName().endsWith("CraftBlockState")
                    // Not all blocks have that type of class, so we have to do some explicit checking...
                    || e.getBlock().getType().equals(Material.REDSTONE_COMPARATOR_OFF)
                    || type.endsWith("BANNER") // Avoids V1.7 issues
                    || e.getBlock().getType().equals(Material.ENDER_CHEST)
                    || e.getBlock().getType().equals(Material.ENCHANTMENT_TABLE)
                    || e.getBlock().getType().equals(Material.DAYLIGHT_DETECTOR)
                    || e.getBlock().getType().equals(Material.FLOWER_POT)){
                // tile entity placed
                if (Settings.limitedBlocks.containsKey(type) && Settings.limitedBlocks.get(type) > -1) {
                    int count = island.getTileEntityCount(e.getBlock().getType(),e.getBlock().getWorld());
                    //plugin.getLogger().info("DEBUG: count is "+ count);
                    if (Settings.limitedBlocks.get(type) <= count) {
                        Util.sendMessage(e.getPlayer(), ChatColor.RED + (plugin.myLocale(e.getPlayer().getUniqueId()).entityLimitReached.replace("[entity]",
                                Util.prettifyText(type))).replace("[number]", String.valueOf(Settings.limitedBlocks.get(type))));
                        e.setCancelled(true);
                        return;
                    }
                }
            }
        } else {
            // Visitor
            Util.sendMessage(e.getPlayer(), ChatColor.RED + plugin.myLocale(e.getPlayer().getUniqueId()).islandProtected);
            e.setCancelled(true);
        }
    }
}
 
Example 18
Source File: ChestProtectListener.java    From ShopChest with MIT License 4 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent e) {
    final Player p = e.getPlayer();
    final Block b = e.getBlockPlaced();

    if (!b.getType().equals(Material.CHEST) && !b.getType().equals(Material.TRAPPED_CHEST)) {
        return;
    }
    
    Chest c = (Chest) b.getState();
    Block b2;

    // Can't use Utils::getChestLocations since inventory holder
    // has not been updated yet in this event (for 1.13+)

    if (Utils.getMajorVersion() < 13) {
        InventoryHolder ih = c.getInventory().getHolder();
        if (!(ih instanceof DoubleChest)) {
            return;
        }

        DoubleChest dc = (DoubleChest) ih;
        Chest l = (Chest) dc.getLeftSide();
        Chest r = (Chest) dc.getRightSide();

        if (b.getLocation().equals(l.getLocation())) {
            b2 = r.getBlock();
        } else {
            b2 = l.getBlock();
        }
    } else {
        org.bukkit.block.data.type.Chest data = (org.bukkit.block.data.type.Chest) c.getBlockData();

        if (data.getType() == Type.SINGLE) {
            return;
        }

        BlockFace neighborFacing;

        switch (data.getFacing()) {
            case NORTH:
                neighborFacing = data.getType() == Type.LEFT ? BlockFace.EAST : BlockFace.WEST;
                break;
            case EAST:
                neighborFacing = data.getType() == Type.LEFT ? BlockFace.SOUTH : BlockFace.NORTH;
                break;
            case SOUTH:
                neighborFacing = data.getType() == Type.LEFT ? BlockFace.WEST : BlockFace.EAST;
                break;
            case WEST:
                neighborFacing = data.getType() == Type.LEFT ? BlockFace.NORTH : BlockFace.SOUTH;
                break;
            default:
                neighborFacing = null;
        }

        b2 = b.getRelative(neighborFacing);
    }

    final Shop shop = shopUtils.getShop(b2.getLocation());
    if (shop == null)
        return;

    plugin.debug(String.format("%s tries to extend %s's shop (#%d)", p.getName(), shop.getVendor().getName(), shop.getID()));

    ShopExtendEvent event = new ShopExtendEvent(p, shop, b.getLocation());
    Bukkit.getPluginManager().callEvent(event);
    if (event.isCancelled() && !p.hasPermission(Permissions.EXTEND_PROTECTED)) {
        e.setCancelled(true);
        p.sendMessage(LanguageUtils.getMessage(Message.NO_PERMISSION_EXTEND_PROTECTED));
        return;
    }

    if (!p.getUniqueId().equals(shop.getVendor().getUniqueId()) && !p.hasPermission(Permissions.EXTEND_OTHER)) {
        e.setCancelled(true);
        p.sendMessage(LanguageUtils.getMessage(Message.NO_PERMISSION_EXTEND_OTHERS));
        return;
    }

    if (!ItemUtils.isAir(b.getRelative(BlockFace.UP).getType())) {
        e.setCancelled(true);
        p.sendMessage(LanguageUtils.getMessage(Message.CHEST_BLOCKED));
        return;
    }

    final Shop newShop = new Shop(shop.getID(), plugin, shop.getVendor(), shop.getProduct(), shop.getLocation(), shop.getBuyPrice(), shop.getSellPrice(), shop.getShopType());

    shopUtils.removeShop(shop, true, new Callback<Void>(plugin) {
        @Override
        public void onResult(Void result) {
            newShop.create(true);
            shopUtils.addShop(newShop, true);
            plugin.debug(String.format("%s extended %s's shop (#%d)", p.getName(), shop.getVendor().getName(), shop.getID()));
        }
    });
}
 
Example 19
Source File: BlockListener.java    From QuickShop-Reremake with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlace(BlockPlaceEvent e) {

    final Material type = e.getBlock().getType();
    final Block placingBlock = e.getBlock();
    final Player player = e.getPlayer();

    if (type != Material.CHEST) {
        return;
    }
    Block chest = null;
    //Chest combine mechanic based checking
    if (player.isSneaking()) {
        Block blockAgainst = e.getBlockAgainst();
        if (blockAgainst.getType() == Material.CHEST && placingBlock.getFace(blockAgainst) != BlockFace.UP && placingBlock.getFace(blockAgainst) != BlockFace.DOWN && !(((Chest) blockAgainst.getState()).getInventory() instanceof DoubleChestInventory)) {
            chest = e.getBlockAgainst();
        } else {
            return;
        }
    } else {
        //Get all chest in vertical Location
        BlockFace placingChestFacing = ((Directional) (placingBlock.getState().getBlockData())).getFacing();
        for (BlockFace face : Util.getVerticalFacing()) {
            //just check the right side and left side
            if (face != placingChestFacing && face != placingChestFacing.getOppositeFace()) {
                Block nearByBlock = placingBlock.getRelative(face);
                if (nearByBlock.getType() == Material.CHEST
                        //non double chest
                        && !(((Chest) nearByBlock.getState()).getInventory() instanceof DoubleChestInventory)
                        //same facing
                        && placingChestFacing == ((Directional) nearByBlock.getState().getBlockData()).getFacing()) {
                    if (chest == null) {
                        chest = nearByBlock;
                    } else {
                        //when multiply chests competed, minecraft will always combine with right side
                        if (placingBlock.getFace(nearByBlock) == Util.getRightSide(placingChestFacing)) {
                            chest = nearByBlock;
                        }
                    }
                }
            }
        }
    }
    if (chest == null) {
        return;
    }

    Shop shop = getShopPlayer(chest.getLocation(), false);
    if (shop != null) {
        if (!QuickShop.getPermissionManager().hasPermission(player, "quickshop.create.double")) {
            e.setCancelled(true);
            MsgUtil.sendMessage(player, MsgUtil.getMessage("no-double-chests", player));

        } else if (!shop.getModerator().isModerator(player.getUniqueId())) {
            e.setCancelled(true);
            MsgUtil.sendMessage(player, MsgUtil.getMessage("not-managed-shop", player));
        }
    }
}
 
Example 20
Source File: BlockPlace.java    From FunnyGuilds with Apache License 2.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlace(BlockPlaceEvent event) {
    Player player = event.getPlayer();
    Block block = event.getBlock();
    Material type = block.getType();

    Location blockLocation = block.getLocation();
    if (!ProtectionSystem.build(player, blockLocation, true)) {
        return;
    }

    // always cancel to prevent breaking other protection
    // plugins or plugins using BlockPlaceEvent (eg. special ability blocks)
    event.setCancelled(true);

    // disabled bugged-blocks or blacklisted item
    if (!this.config.buggedBlocks || this.config.buggedBlocksExclude.contains(type)) {
        return;
    }

    // remove one item from the player
    ItemStack itemInHand = event.getItemInHand();
    if ((itemInHand.getAmount() - 1) == 0) {
        // wondering why? because bukkit and you probably don't want dupe glitches
        if (Reflections.USE_PRE_9_METHODS) {
            player.setItemInHand(null);
        } else {
            itemInHand.setAmount(0);
        }
    } else {
        itemInHand.setAmount(itemInHand.getAmount() - 1);
    }

    // if the player is standing on the placed block add some velocity to prevent glitching
    // side effect: velocity with +y0.4 is like equivalent to jumping while building, just hold right click, that's real fun!
    Location playerLocation = player.getLocation();
    boolean sameColumn = (playerLocation.getBlockX() == blockLocation.getBlockX()) && (playerLocation.getBlockZ() == blockLocation.getBlockZ());
    double distanceUp = (playerLocation.getY() - blockLocation.getBlockY());
    boolean upToTwoBlocks = (distanceUp > 0) && (distanceUp <= 2);
    if (sameColumn && upToTwoBlocks) {
        player.setVelocity(ANTI_GLITCH_VELOCITY);
    }

    // delay, because we cannot do {@link Block#setType(Material)} immediately
    Bukkit.getScheduler().runTask(FunnyGuilds.getInstance(), () -> {

        // fake place for bugged block
        block.setType(type);

        // start timer and return the item to the player if specified to do so
        ItemStack returnItem = event.getItemInHand().clone();
        returnItem.setAmount(1);

        Bukkit.getScheduler().runTaskLater(FunnyGuilds.getInstance(), () -> {
            event.getBlockReplacedState().update(true);
            if (!player.isOnline()) {
                return;
            }
            if (this.config.buggedBlockReturn) {
                player.getInventory().addItem(returnItem);
            }
        }, this.config.buggedBlocksTimer);

    });
}