Reduced the complexity of these commands.

By splitting up the methods, it makes it easier to understand and spot
bugs.
This commit is contained in:
Tastybento 2018-02-11 15:22:03 -08:00
parent 9f43f1e6fa
commit 54dd9e87d4
10 changed files with 238 additions and 315 deletions

View File

@ -11,7 +11,6 @@ import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginIdentifiableCommand;
@ -31,7 +30,6 @@ import us.tastybento.bskyblock.util.Util;
*/
public abstract class CompositeCommand extends Command implements PluginIdentifiableCommand, BSBCommand {
private static final boolean DEBUG = false;
/**
* True if the command is for the player only (not for the console)
*/
@ -109,9 +107,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
if (!getSubCommand("help").isPresent() && !label.equals("help")) {
new DefaultHelpCommand(this);
}
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: registering command " + label);
}
}
/**
@ -121,9 +116,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
*/
public CompositeCommand(String label, String... aliases) {
super(label);
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: top level command registering..." + label);
}
setAliases(new ArrayList<>(Arrays.asList(aliases)));
parent = null;
setUsage("");
@ -147,15 +139,9 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
*/
@Override
public boolean execute(CommandSender sender, String label, String[] args) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: executing command " + label);
}
// Get the User instance for this sender
User user = User.getInstance(sender);
CompositeCommand cmd = getCommandFromArgs(args);
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: Command = " + cmd.getLabel() + " onlyplayer = " + cmd.isOnlyPlayer() + " permission = " + cmd.getPermission());
}
// Check for console and permissions
if (cmd.onlyPlayer && !(sender instanceof Player)) {
user.sendMessage("general.errors.use-in-game");
@ -285,22 +271,13 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
* @return CompositeCommand or null if none found
*/
public Optional<CompositeCommand> getSubCommand(String label) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: label = " + label);
}
for (Map.Entry<String, CompositeCommand> entry : subCommands.entrySet()) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: " + entry.getKey());
}
if (entry.getKey().equalsIgnoreCase(label)) {
return Optional.of(subCommands.get(label));
}
}
// Try aliases
for (Map.Entry<String, CompositeCommand> entry : subCommandAliases.entrySet()) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: alias " + entry.getKey());
}
if (entry.getKey().equalsIgnoreCase(label)) {
return Optional.of(subCommandAliases.get(label));
}
@ -415,20 +392,11 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
List<String> options = new ArrayList<>();
// Get command object based on args entered so far
CompositeCommand cmd = getCommandFromArgs(args);
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: subCommand = " + cmd.getLabel() + " onlyplayer = " + cmd.isOnlyPlayer() + " permission = " + cmd.getPermission());
}
// Check for console and permissions
if (cmd.onlyPlayer && !(sender instanceof Player)) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: returning, only for player");
}
return options;
}
if (!cmd.getPermission().isEmpty() && !sender.hasPermission(cmd.getPermission())) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: failed perm check");
}
return options;
}
// Add any tab completion from the subcommand
@ -454,14 +422,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
}
String lastArg = (args.length != 0 ? args[args.length - 1] : "");
if (DEBUG) {
String arguments = "";
for (String arg : args) {
arguments += "'" + arg + "' ";
}
Bukkit.getLogger().info("DEBUG: tab complete for " + arguments);
Bukkit.getLogger().info("DEBUG: result = " + Util.tabLimit(options, lastArg));
}
return Util.tabLimit(options, lastArg);
}

View File

@ -14,15 +14,15 @@ import org.apache.commons.lang.math.NumberUtils;
*/
public class DefaultHelpCommand extends CompositeCommand {
// TODO: make this a setting
private static final int MAX_DEPTH = 2;
private static final String USAGE_PLACEHOLDER = "[usage]";
private static final String PARAMS_PLACEHOLDER = "[parameters]";
private static final String DESC_PLACEHOLDER = "[description]";
private static final String HELP_SYNTAX_REF = "commands.help.syntax";
private static final String HELP = "help";
public DefaultHelpCommand(CompositeCommand parent) {
super(parent, "help");
super(parent, HELP);
}
@Override
@ -51,46 +51,56 @@ public class DefaultHelpCommand extends CompositeCommand {
if (depth == 0) {
user.sendMessage("commands.help.header");
}
//if (args.isEmpty()) {
if (depth < MAX_DEPTH) {
if (!parent.getLabel().equals("help")) {
if (!parent.getLabel().equals(HELP)) {
// Get elements
String usage = parent.getUsage().isEmpty() ? "" : user.getTranslation(parent.getUsage());
String params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters());
String desc = getDescription().isEmpty() ? "" : user.getTranslation(getDescription());
// Show the help
if (user.isPlayer()) {
// Player. Check perms
if (user.hasPermission(parent.getPermission())) {
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
} else {
// No permission, nothing to see here. If you don't have permission, you cannot see any sub commands
return true;
}
} else if (!parent.isOnlyPlayer()) {
// Console. Only show if it is a console command
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
}
}
// Increment the depth
int newDepth = depth + 1;
// Run through any subcommands and get their help
for (CompositeCommand subCommand : parent.getSubCommands().values()) {
// Ignore the help command
if (!subCommand.getLabel().equals("help")) {
// Every command should have help because every command has a default help
Optional<CompositeCommand> sub = subCommand.getSubCommand("help");
if (sub.isPresent()) {
sub.get().execute(user, Arrays.asList(String.valueOf(newDepth)));
}
}
}
}
if (showPrettyHelp(user, usage, params, desc)) {
// No more to show
return true;
}
}
// Increment the depth and run through any subcommands and get their help too
runSubCommandHelp(user, depth + 1);
}
if (depth == 0) {
user.sendMessage("commands.help.end");
}
return true;
}
private void runSubCommandHelp(User user, int newDepth) {
for (CompositeCommand subCommand : parent.getSubCommands().values()) {
// Ignore the help command
if (!subCommand.getLabel().equals(HELP)) {
// Every command should have help because every command has a default help
Optional<CompositeCommand> sub = subCommand.getSubCommand(HELP);
if (sub.isPresent()) {
sub.get().execute(user, Arrays.asList(String.valueOf(newDepth)));
}
}
}
}
private boolean showPrettyHelp(User user, String usage, String params, String desc) {
// Show the help
if (user.isPlayer()) {
// Player. Check perms
if (user.hasPermission(parent.getPermission())) {
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
} else {
// No permission, nothing to see here. If you don't have permission, you cannot see any sub commands
return true;
}
} else if (!parent.isOnlyPlayer()) {
// Console. Only show if it is a console command
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
}
return false;
}
}

View File

@ -38,24 +38,23 @@ public class CustomIslandMultiHomeHelp extends CompositeCommand {
String usage = parent.getUsage().isEmpty() ? "" : user.getTranslation(parent.getUsage());
String params = "";
String desc = getDescription().isEmpty() ? "" : user.getTranslation(getDescription());
// Player. Check perms
if (user.hasPermission(getPermission())) {
int maxHomes = Util.getPermValue(user.getPlayer(), Constants.PERMPREFIX + "island.maxhomes", getSettings().getMaxHomes());
if (maxHomes > 1) {
params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters());
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);
} else {
// No params
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);
}
return true;
} else {
return true;
}
showPrettyHelp(user, usage, params, desc);
return true;
}
return false;
}
private void showPrettyHelp(User user, String usage, String params, String desc) {
// Player. Check perms
if (user.hasPermission(getPermission())) {
int maxHomes = Util.getPermValue(user.getPlayer(), Constants.PERMPREFIX + "island.maxhomes", getSettings().getMaxHomes());
if (maxHomes > 1) {
params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters());
}
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);
}
}
}

View File

@ -6,11 +6,14 @@ import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachmentInfo;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
@ -28,9 +31,6 @@ public abstract class AbstractIslandTeamCommand extends CompositeCommand {
protected static Set<UUID> leavingPlayers = new HashSet<>();
protected static Set<UUID> kickingPlayers = new HashSet<>();
// TODO: It would be good if these could be auto-provided
protected User user;
public AbstractIslandTeamCommand(CompositeCommand command, String label, String... aliases) {
super(command, label,aliases);
}
@ -43,4 +43,43 @@ public abstract class AbstractIslandTeamCommand extends CompositeCommand {
protected void setResetWaitTime(final Player player) {
resetWaitTime.put(player.getUniqueId(), Calendar.getInstance().getTimeInMillis() + getSettings().getResetWait() * 1000);
}
protected int getMaxTeamSize(User user) {
return getMaxPermSize(user, "team.maxsize.", getSettings().getMaxTeamSize());
}
protected int getMaxRangeSize(User user) {
return getMaxPermSize(user, "island.range.", getSettings().getIslandProtectionRange());
}
/**
* Get the max size based on permissions
* @param playerUUID
* @return the max permission for this perm
*/
private int getMaxPermSize(User user, String perm, int maxSize) {
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + perm)) {
if (perms.getPermission().contains(Constants.PERMPREFIX + perm + "*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + perm);
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
maxSize = Math.max(maxSize, Integer.valueOf(spl[1]));
}
}
}
}
// Do some sanity checking
if (maxSize < 1) {
maxSize = 1;
}
}
return maxSize;
}
}

View File

@ -4,9 +4,6 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
@ -15,8 +12,6 @@ import us.tastybento.bskyblock.api.events.team.TeamEvent;
public class IslandTeamCommand extends AbstractIslandTeamCommand {
private static final boolean DEBUG = false;
public IslandTeamCommand(CompositeCommand islandCommand) {
super(islandCommand, "team");
}
@ -36,47 +31,15 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
@Override
public boolean execute(User user, List<String> args) {
UUID playerUUID = user.getUniqueId();
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: executing team command for " + playerUUID);
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands()
.getIsland(playerUUID))
.reason(TeamEvent.Reason.INFO)
.involvedPlayer(playerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return true;
if (fireEvent(playerUUID)) {
// Cancelled
return false;
}
UUID teamLeaderUUID = getTeamLeader(user);
Set<UUID> teamMembers = getMembers(user);
if (teamLeaderUUID.equals(playerUUID)) {
int maxSize = getSettings().getMaxTeamSize();
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "team.maxsize.*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "team.maxsize.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
maxSize = Math.max(maxSize, Integer.valueOf(spl[1]));
}
}
}
}
// Do some sanity checking
if (maxSize < 1) {
maxSize = 1;
}
}
int maxSize = getMaxTeamSize(user);
if (teamMembers.size() < maxSize) {
user.sendMessage("commands.island.team.invite.you-can-invite", "[number]", String.valueOf(maxSize - teamMembers.size()));
} else {
@ -86,4 +49,16 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
return true;
}
private boolean fireEvent(UUID playerUUID) {
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands()
.getIsland(playerUUID))
.reason(TeamEvent.Reason.INFO)
.involvedPlayer(playerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
return event.isCancelled();
}
}

View File

@ -7,9 +7,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.OfflinePlayer;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
@ -84,64 +82,45 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
user.sendMessage("commands.island.team.invite.already-on-team");
return false;
}
Set<UUID> teamMembers = getMembers(user);
// Check if player has space on their team
int maxSize = getSettings().getMaxTeamSize();
// Dynamic team sizes with permissions
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "team.maxsize.*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "team.maxsize.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
maxSize = Math.max(maxSize, Integer.valueOf(spl[1]));
}
}
}
}
// Do some sanity checking
if (maxSize < 1) {
maxSize = 1;
}
return invite(user,invitedPlayer);
}
}
private boolean invite(User user, User invitedPlayer) {
Set<UUID> teamMembers = getMembers(user);
// Check if player has space on their team
int maxSize = getMaxTeamSize(user);
if (teamMembers.size() < maxSize) {
// If that player already has an invite out then retract it.
// Players can only have one invite one at a time - interesting
if (inviteList.containsValue(user.getUniqueId())) {
inviteList.inverse().remove(user.getUniqueId());
user.sendMessage("commands.island.team.invite.removing-invite");
}
if (teamMembers.size() < maxSize) {
// If that player already has an invite out then retract it.
// Players can only have one invite one at a time - interesting
if (inviteList.containsValue(playerUUID)) {
inviteList.inverse().remove(playerUUID);
user.sendMessage("commands.island.team.invite.removing-invite");
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands().getIsland(playerUUID))
.reason(TeamEvent.Reason.INVITE)
.involvedPlayer(invitedPlayerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return true;
}
// Put the invited player (key) onto the list with inviter (value)
// If someone else has invited a player, then this invite will overwrite the previous invite!
inviteList.put(invitedPlayerUUID, playerUUID);
user.sendMessage("commands.island.team.invite.invitation-sent", NAME_PLACEHOLDER, args.get(0));
// Send message to online player
invitedPlayer.sendMessage("commands.island.team.invite.name-has-invited-you", NAME_PLACEHOLDER, user.getName());
invitedPlayer.sendMessage("commands.island.team.invite.to-accept-or-reject", "[label]", getLabel());
if (getPlayers().hasIsland(invitedPlayer.getUniqueId())) {
invitedPlayer.sendMessage("commands.island.team.invite.you-will-lose-your-island");
}
return true;
} else {
user.sendMessage("commands.island.team.invite.errors.island-is-full");
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands().getIsland(user.getUniqueId()))
.reason(TeamEvent.Reason.INVITE)
.involvedPlayer(invitedPlayer.getUniqueId())
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return false;
}
// Put the invited player (key) onto the list with inviter (value)
// If someone else has invited a player, then this invite will overwrite the previous invite!
inviteList.put(invitedPlayer.getUniqueId(), user.getUniqueId());
user.sendMessage("commands.island.team.invite.invitation-sent", NAME_PLACEHOLDER, invitedPlayer.getName());
// Send message to online player
invitedPlayer.sendMessage("commands.island.team.invite.name-has-invited-you", NAME_PLACEHOLDER, user.getName());
invitedPlayer.sendMessage("commands.island.team.invite.to-accept-or-reject", "[label]", getLabel());
if (getPlayers().hasIsland(invitedPlayer.getUniqueId())) {
invitedPlayer.sendMessage("commands.island.team.invite.you-will-lose-your-island");
}
return true;
} else {
user.sendMessage("commands.island.team.invite.errors.island-is-full");
return false;
}
}

View File

@ -6,9 +6,6 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
@ -45,7 +42,6 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
showHelp(this, user);
return false;
}
//getPlugin().getLogger().info("DEBUG: arg[0] = " + args.get(0));
UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player");
@ -78,9 +74,16 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
if (event.isCancelled()) {
return false;
}
makeLeader(user, targetUUID);
getIslands().save(true);
return true;
}
private void makeLeader(User user, UUID targetUUID) {
// target is the new leader
getIslands().getIsland(playerUUID).setOwner(targetUUID);
Island island = getIslands().getIsland(user.getUniqueId());
island.setOwner(targetUUID);
user.sendMessage("commands.island.team.setowner.name-is-the-owner", "[name]", getPlayers().getName(targetUUID));
// Check if online
@ -88,54 +91,18 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
target.sendMessage("commands.island.team.setowner.you-are-the-owner");
if (target.isOnline()) {
// Check if new leader has a lower range permission than the island size
boolean hasARangePerm = false;
int range = getSettings().getIslandProtectionRange();
// Check for zero protection range
Island islandByOwner = getIslands().getIsland(targetUUID);
if (islandByOwner.getProtectionRange() == 0) {
getPlugin().getLogger().warning("Player " + user.getName() + "'s island had a protection range of 0. Setting to default " + range);
islandByOwner.setProtectionRange(range);
int range = getMaxRangeSize(user);
// Range can go up or down
if (range != island.getProtectionRange()) {
user.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
target.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
getPlugin().getLogger().info(
"Makeleader: Island protection range changed from " + island.getProtectionRange() + " to "
+ range + " for " + user.getName() + " due to permission.");
}
for (PermissionAttachmentInfo perms : target.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "island.range.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "island.range.*")) {
// Ignore
break;
} else {
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "island.range.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
island.setProtectionRange(range);
} else {
hasARangePerm = true;
range = Math.max(range, Integer.valueOf(spl[1]));
}
}
}
}
}
// Only set the island range if the player has a perm to override the default
if (hasARangePerm) {
// Do some sanity checking
if (range % 2 != 0) {
range--;
}
// Get island range
// Range can go up or down
if (range != islandByOwner.getProtectionRange()) {
user.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
target.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
getPlugin().getLogger().info(
"Makeleader: Island protection range changed from " + islandByOwner.getProtectionRange() + " to "
+ range + " for " + user.getName() + " due to permission.");
}
islandByOwner.setProtectionRange(range);
}
}
getIslands().save(true);
return true;
}
@Override

View File

@ -27,20 +27,22 @@ import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.util.teleport.SafeTeleportBuilder;
public class NetherPortals implements Listener {
private static final String ERROR_NO_PERMISSION = "errors.general.no-permission";
private final BSkyBlock plugin;
private World world;
private World nether;
private World the_end;
private World theEnd;
public NetherPortals(BSkyBlock plugin) {
this.plugin = plugin;
world = plugin.getIslandWorldManager().getIslandWorld();
nether = plugin.getIslandWorldManager().getNetherWorld();
the_end = plugin.getIslandWorldManager().getEndWorld();
theEnd = plugin.getIslandWorldManager().getEndWorld();
}
/**
* Function to check proximity to nether spawn location
* Function to check proximity to nether or end spawn location.
* Used when playing with the standard nether or end.
*
* @param location
* @return true if in the spawn area, false if not
@ -48,31 +50,31 @@ public class NetherPortals implements Listener {
private boolean awayFromSpawn(Location location) {
Vector p = location.toVector().multiply(new Vector(1, 0, 1));
Vector spawn = location.getWorld().getSpawnLocation().toVector().multiply(new Vector(1, 0, 1));
if (spawn.distanceSquared(p) < (plugin.getSettings().getNetherSpawnRadius() * plugin.getSettings().getNetherSpawnRadius())) {
plugin.getLogger().info("not away from spawn");
return false;
} else {
return true;
}
return (spawn.distanceSquared(p) < (plugin.getSettings().getNetherSpawnRadius() * plugin.getSettings().getNetherSpawnRadius())) ? false : true;
}
private boolean inWorlds(Location from) {
return (from.getWorld().equals(world) || from.getWorld().equals(nether) || from.getWorld().equals(the_end)) ? true : false;
/**
* Check if the player is in the island worlds
* @param location
* @return true if the player is
*/
private boolean inWorlds(Location location) {
return (location.getWorld().equals(world) || location.getWorld().equals(nether) || location.getWorld().equals(theEnd)) ? true : false;
}
/**
* If the player is in the standard nether or standard end or op, do nothing.
* Used to protect the standard spawn for nether or end
* @param player
* @return true if nothing needs to be done
*/
private boolean noAction(Player player) {
if (player.isOp()
|| (!player.getWorld().equals(nether) && !player.getWorld().equals(the_end))
return (player.isOp()
|| (!player.getWorld().equals(nether) && !player.getWorld().equals(theEnd))
|| (player.getWorld().equals(nether) && plugin.getSettings().isNetherIslands())
|| (player.getWorld().equals(the_end) && plugin.getSettings().isEndIslands())) {
plugin.getLogger().info("No legacy nether or end");
return true;
}
plugin.getLogger().info("Action!");
return false;
|| (player.getWorld().equals(theEnd) && plugin.getSettings().isEndIslands())) ? true: false;
}
/**
* Prevents blocks from being broken
*
@ -84,20 +86,22 @@ public class NetherPortals implements Listener {
return;
}
if (!awayFromSpawn(event.getBlock().getLocation())) {
User.getInstance(event.getPlayer()).sendMessage("errors.general.no-permission");
User.getInstance(event.getPlayer()).sendMessage(ERROR_NO_PERMISSION);
event.setCancelled(true);
}
}
// Nether portal spawn protection
/**
* Protects standard nether or end spawn from bucket abuse
* @param event
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBucketEmpty(PlayerBucketEmptyEvent event) {
if (noAction(event.getPlayer())) {
return;
}
if (!awayFromSpawn(event.getBlockClicked().getLocation())) {
User.getInstance(event.getPlayer()).sendMessage("errors.general.no-permission");
User.getInstance(event.getPlayer()).sendMessage(ERROR_NO_PERMISSION);
event.setCancelled(true);
}
}
@ -108,7 +112,6 @@ public class NetherPortals implements Listener {
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEndIslandPortal(PlayerPortalEvent event) {
plugin.getLogger().info("End portal event Is end generated? " + plugin.getSettings().isEndGenerate());
if (!event.getCause().equals(TeleportCause.END_PORTAL) || !plugin.getSettings().isEndGenerate()) {
return;
}
@ -116,17 +119,15 @@ public class NetherPortals implements Listener {
return;
}
// If entering a portal in the end, teleport home if you have one, else do nothing
if (event.getFrom().getWorld().equals(the_end)) {
plugin.getLogger().info("In end world");
if (event.getFrom().getWorld().equals(theEnd)) {
if (plugin.getIslands().hasIsland(event.getPlayer().getUniqueId())) {
event.setCancelled(true);
plugin.getIslands().homeTeleport(event.getPlayer());
}
return;
}
plugin.getLogger().info("In other world going through end portal");
// If this is island end, then go to the same location, otherwise try spawn
Location to = plugin.getSettings().isEndIslands() ? event.getFrom().toVector().toLocation(the_end) : the_end.getSpawnLocation();
Location to = plugin.getSettings().isEndIslands() ? event.getFrom().toVector().toLocation(theEnd) : theEnd.getSpawnLocation();
// Else other worlds teleport to the end
event.setCancelled(true);
new SafeTeleportBuilder(plugin)
@ -144,7 +145,6 @@ public class NetherPortals implements Listener {
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityPortal(EntityPortalEvent event) {
plugin.getLogger().info(event.getEventName());
if (inWorlds(event.getFrom())) {
// Disable entity portal transfer due to dupe glitching
event.setCancelled(true);
@ -152,7 +152,7 @@ public class NetherPortals implements Listener {
}
/**
* Prevent spawns from being blown up
* Prevent standard nether or end spawns from being blown up
*
* @param e
*/
@ -162,7 +162,7 @@ public class NetherPortals implements Listener {
return;
}
if ((event.getLocation().getWorld().equals(nether) && plugin.getSettings().isNetherIslands())
|| (event.getLocation().getWorld().equals(the_end) && plugin.getSettings().isEndIslands())) {
|| (event.getLocation().getWorld().equals(theEnd) && plugin.getSettings().isEndIslands())) {
// Not used in island worlds
return;
}
@ -186,7 +186,6 @@ public class NetherPortals implements Listener {
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onNetherPortal(PlayerPortalEvent event) {
plugin.getLogger().info(event.getEventName() + " " + event.getCause() + " nether");
if (!event.getCause().equals(TeleportCause.NETHER_PORTAL)) {
return;
}
@ -194,11 +193,9 @@ public class NetherPortals implements Listener {
return;
}
// If entering a portal in the nether, teleport to portal in overworld if there is one
if (event.getFrom().getWorld().equals(nether)) {
plugin.getLogger().info("Entered portal in nether");
if (event.getFrom().getWorld().equals(nether)) {
// If this is island nether, then go to the same vector, otherwise try spawn
Location to = plugin.getSettings().isNetherIslands() ? event.getFrom().toVector().toLocation(world) : plugin.getIslands().getIslandLocation(event.getPlayer().getUniqueId());
plugin.getLogger().info("Going to " + to);
event.setCancelled(true);
// Else other worlds teleport to the nether
new SafeTeleportBuilder(plugin)
@ -208,10 +205,8 @@ public class NetherPortals implements Listener {
.build();
return;
}
plugin.getLogger().info("Entering nether portal in overworld");
// If this is island nether, then go to the same vector, otherwise try spawn
Location to = plugin.getSettings().isNetherIslands() ? event.getFrom().toVector().toLocation(nether) : nether.getSpawnLocation();
plugin.getLogger().info("Going to " + to);
event.setCancelled(true);
// Else other worlds teleport to the nether
new SafeTeleportBuilder(plugin)
@ -223,7 +218,7 @@ public class NetherPortals implements Listener {
}
/**
* Prevents placing of blocks
* Prevents placing of blocks at standard nether or end spawns
*
* @param e
*/
@ -233,7 +228,7 @@ public class NetherPortals implements Listener {
return;
}
if (!awayFromSpawn(event.getBlock().getLocation())) {
User.getInstance(event.getPlayer()).sendMessage("errors.general.no-permission");
User.getInstance(event.getPlayer()).sendMessage(ERROR_NO_PERMISSION);
event.setCancelled(true);
}
}

View File

@ -129,9 +129,6 @@ public class Util {
* Credits to mikenon on GitHub!
*/
public static String prettifyText(String ugly) {
if (!ugly.contains("_") && (!ugly.equals(ugly.toUpperCase()))) {
return ugly;
}
String fin = "";
ugly = ugly.toLowerCase();
if (ugly.contains("_")) {

View File

@ -5,7 +5,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import org.bukkit.Bukkit;
import org.bukkit.ChunkSnapshot;
import org.bukkit.GameMode;
import org.bukkit.Location;
@ -129,23 +128,7 @@ public class SafeSpotTeleport {
do {
for (int i = x - radius; i <= x + radius; i++) {
for (int j = z - radius; j <= z + radius; j++) {
Pair<Integer, Integer> blockCoord = new Pair<>(i,j);
Pair<Integer, Integer> chunkCoord = new Pair<>(i/16, j/16);
if (!result.contains(chunkCoord)) {
// Add the chunk coord
if (!island.isPresent()) {
// If there is no island, just add it
result.add(chunkCoord);
} else {
// If there is an island, only add it if the coord is in island space
island.ifPresent(is -> {
if (is.inIslandSpace(blockCoord)) {
result.add(chunkCoord);
}
});
}
}
addChunk(result, island, new Pair<>(i,j), new Pair<>(i/16, j/16));
}
}
radius++;
@ -153,6 +136,24 @@ public class SafeSpotTeleport {
return result;
}
private void addChunk(List<Pair<Integer, Integer>> result, Optional<Island> island, Pair<Integer, Integer> blockCoord, Pair<Integer, Integer> chunkCoord) {
if (!result.contains(chunkCoord)) {
// Add the chunk coord
if (!island.isPresent()) {
// If there is no island, just add it
result.add(chunkCoord);
} else {
// If there is an island, only add it if the coord is in island space
island.ifPresent(is -> {
if (is.inIslandSpace(blockCoord)) {
result.add(chunkCoord);
}
});
}
}
}
/**
* Loops through the chunks and if a safe spot is found, fires off the teleportation
* @param chunkSnapshot
@ -268,7 +269,6 @@ public class SafeSpotTeleport {
break;
case PORTAL:
if (portal) {
Bukkit.getLogger().info("Portal found");
Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D);
// Teleport as soon as we find a portal
teleportEntity(newSpot.toLocation(world));
@ -276,27 +276,29 @@ public class SafeSpotTeleport {
}
break;
default:
// Safe
Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D);
// Check for portal
if (portal) {
if (bestSpot == null) {
Bukkit.getLogger().info("Best spot found = " + bestSpot);
// Stash the best spot
bestSpot = newSpot.toLocation(world);
return false;
}
} else {
// Regular search - teleport as soon as we find something
Bukkit.getLogger().info("Safe spot found, teleporting to new spot");
teleportEntity(newSpot.toLocation(world));
return true;
}
return safe(world, chunk, x, y, z);
}
}
}
return false;
}
private boolean safe(World world, ChunkSnapshot chunk, int x, int y, int z) {
// Safe
Vector newSpot = new Vector(chunk.getX() * 16 + x + 0.5D, y + 1, chunk.getZ() * 16 + z + 0.5D);
// Check for portal
if (portal) {
if (bestSpot == null) {
// Stash the best spot
bestSpot = newSpot.toLocation(world);
}
return false;
} else {
// Regular search - teleport as soon as we find something
teleportEntity(newSpot.toLocation(world));
return true;
}
}
}