Add preset commands and signs

This commit is contained in:
Phoenix616 2019-03-25 21:16:05 +01:00
parent 59bcf6e79a
commit 7c5f658de1
7 changed files with 256 additions and 40 deletions

View File

@ -19,6 +19,8 @@ package de.themoep.randomteleport;
*/
import de.themoep.randomteleport.hook.HookManager;
import de.themoep.randomteleport.listeners.SignListener;
import de.themoep.randomteleport.searcher.RandomSearcher;
import de.themoep.randomteleport.searcher.options.NotFoundException;
import de.themoep.randomteleport.searcher.options.OptionParser;
import de.themoep.randomteleport.searcher.options.PlayerNotFoundException;
@ -29,6 +31,7 @@ import de.themoep.randomteleport.searcher.validators.BlockValidator;
import de.themoep.randomteleport.searcher.validators.ProtectionValidator;
import de.themoep.randomteleport.searcher.validators.WorldborderValidator;
import de.themoep.utils.lang.bukkit.LanguageManager;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
@ -37,10 +40,13 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class RandomTeleport extends JavaPlugin {
@ -53,6 +59,7 @@ public class RandomTeleport extends JavaPlugin {
private Material[] saveBlocks;
private Material[] unsaveBlocks;
private Set<String> signVariables;
public void onEnable() {
hookManager = new HookManager(this);
@ -60,6 +67,7 @@ public class RandomTeleport extends JavaPlugin {
initOptionParsers();
initValidators();
getCommand("randomteleport").setExecutor(new RandomTeleportCommand(this));
getServer().getPluginManager().registerEvents(new SignListener(this), this);
}
public void loadConfig() {
@ -85,6 +93,7 @@ public class RandomTeleport extends JavaPlugin {
})
.filter(Objects::nonNull)
.toArray(Material[]::new);
signVariables = getConfig().getStringList("sign-variables").stream().map(String::toLowerCase).collect(Collectors.toSet());
lang = new LanguageManager(this, getConfig().getString("lang"));
lang.setPlaceholderPrefix("{");
lang.setPlaceholderSuffix("}");
@ -223,4 +232,68 @@ public class RandomTeleport extends JavaPlugin {
optionParsers.add(parser);
}
/**
* Check whether or not a sign line matches the configured variables
* @param line The line to match
* @return <tt>true</tt> if it matches; <tt>false</tt> if not
*/
public boolean matchesSignVariable(String line) {
return signVariables.contains(line.toLowerCase());
}
/**
* Create and run a searcher using specified args the same way the command does
* @param sender The sender of the command
* @param center The center location for the searcher
* @param args The arguments to parse
* @return Returns the searcher that is running
* @throws IllegalArgumentException Thrown when arguments couldn't be handled properly
*/
public RandomSearcher parseAndRun(CommandSender sender, Location center, String[] args) {
RandomSearcher searcher = new RandomSearcher(this, sender, center, Integer.parseInt(args[0]), Integer.parseInt(args[1]));
String[] optionArgs = Arrays.copyOfRange(args, 2, args.length);
for (OptionParser parser : getOptionParsers()) {
parser.parse(searcher, optionArgs);
}
searcher.getTargets().forEach(p -> sendMessage(p, "search", "world", searcher.getCenter().getWorld().getName()));
searcher.search().thenApply(targetLoc -> {
searcher.getTargets().forEach(p -> {
p.teleport(targetLoc);
sendMessage(p, "teleport",
"world", center.getWorld().getName(),
"x", String.valueOf(center.getBlockX()),
"y", String.valueOf(center.getBlockY()),
"z", String.valueOf(center.getBlockZ())
);
});
return true;
}).exceptionally(ex -> {
sendMessage(sender, "error.location");
sender.sendMessage(ex.getMessage());
searcher.getTargets().forEach(p -> sendMessage(p, "error.location"));
return true;
});
return searcher;
}
/**
* Run a preset
* @param sender The sender that executed the preset
* @param preset The preset ID to run
* @param target The player targeted by the teleporter
* @param center The center for the search
* @return The RandomSearcher instance that is searching
*/
public RandomSearcher runPreset(CommandSender sender, String preset, Player target, Location center) {
String cmd = getConfig().getString("presets." + preset) + " -p " + target.getName();
if (cmd.startsWith("/")) {
cmd = cmd.substring(1);
}
if (cmd.startsWith("rtp ")) {
cmd = cmd.substring(4);
}
return parseAndRun(sender, center, cmd.split(" "));
}
}

View File

@ -18,8 +18,6 @@ package de.themoep.randomteleport;
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import de.themoep.randomteleport.searcher.RandomSearcher;
import de.themoep.randomteleport.searcher.options.OptionParser;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
@ -27,8 +25,9 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.logging.Level;
public class RandomTeleportCommand implements CommandExecutor {
private final RandomTeleport plugin;
@ -39,46 +38,62 @@ public class RandomTeleportCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 1) {
if ("reload".equalsIgnoreCase(args[0])) {
if (args.length == 0) {
if (sender instanceof Player) {
runPreset("default", sender, (Player) sender, ((Player) sender).getLocation());
return true;
}
} else if (args.length == 1) {
if ("--reload".equalsIgnoreCase(args[0])) {
plugin.loadConfig();
plugin.sendMessage(sender, "reloaded");
return true;
} else if ("--stat".equalsIgnoreCase(args[0])) {
//TODO: teleporter and searcher statistics
} else if (sender instanceof Player) {
runPreset(args[0].toLowerCase(), sender, (Player) sender, ((Player) sender).getLocation());
return true;
}
} else if (args.length > 1) {
} else {
try {
RandomSearcher searcher = new RandomSearcher(plugin, sender, getLocation(sender), Integer.parseInt(args[0]), Integer.parseInt(args[1]));
String[] optionArgs = Arrays.copyOfRange(args, 2, args.length);
for (OptionParser parser : plugin.getOptionParsers()) {
parser.parse(searcher, optionArgs);
}
searcher.getTargets().forEach(p -> plugin.sendMessage(p, "search", "world", searcher.getCenter().getWorld().getName()));
searcher.search().thenApply(location -> {
searcher.getTargets().forEach(p -> {
p.teleport(location);
plugin.sendMessage(p, "teleport",
"world", location.getWorld().getName(),
"x", String.valueOf(location.getBlockX()),
"y", String.valueOf(location.getBlockY()),
"z", String.valueOf(location.getBlockZ())
);
});
return true;
}).exceptionally(ex -> {
plugin.sendMessage(sender, "error.location");
sender.sendMessage(ex.getMessage());
return true;
});
plugin.parseAndRun(sender, getLocation(sender), args);
return true;
} catch (IllegalArgumentException e) {
if (args.length == 2) {
Player target = plugin.getServer().getPlayer(args[1]);
if (target == null) {
plugin.sendMessage(sender, "error.player-not-found", "what", args[1]);
return true;
}
runPreset(args[0].toLowerCase(), sender, target, target.getLocation());
return true;
}
sender.sendMessage(e.getMessage());
}
}
return false;
}
private void runPreset(String preset, CommandSender sender, Player target, Location center) {
if (!sender.hasPermission("randomteleport.presets." + preset)) {
plugin.sendMessage(sender, "error.no-permission.preset",
"preset", preset, "perm",
"randomteleport.presets." + preset
);
} else if (sender != target && !sender.hasPermission("randomteleport.tpothers")) {
plugin.sendMessage(sender, "error.no-permission.tp-others", "perm", "randomteleport.tpothers");
} else if (plugin.getConfig().getString("presets." + preset) == null) {
plugin.sendMessage(sender, "error.preset-doesnt-exist", "preset", preset);
} else {
try {
plugin.runPreset(plugin.getServer().getConsoleSender(), preset, target, center);
} catch (IllegalArgumentException e) {
plugin.sendMessage(sender, "error.preset-invalid", "preset", preset);
plugin.getLogger().log(Level.SEVERE, "Error while parsing preset " + preset, e);
}
}
}
private static Location getLocation(CommandSender sender) {
if (sender instanceof Entity) {
return ((Entity) sender).getLocation();

View File

@ -0,0 +1,98 @@
package de.themoep.randomteleport.listeners;
/*
* RandomTeleport
* Copyright (c) 2019 Max Lee aka Phoenix616 (mail@moep.tv)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import de.themoep.randomteleport.RandomTeleport;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import java.util.logging.Level;
public class SignListener implements Listener {
private final RandomTeleport plugin;
public SignListener(RandomTeleport plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true)
public void onSignCreate(SignChangeEvent event) {
if (plugin.matchesSignVariable(event.getLine(1))) {
if (!event.getPlayer().hasPermission("randomteleport.sign.create")) {
event.getBlock().breakNaturally();
plugin.sendMessage(event.getPlayer(), "sign.no-permission.create", "perm", "randomteleport.sign.create");
} else {
String preset = event.getLine(2);
plugin.sendMessage(event.getPlayer(), "sign.created", "preset", preset);
if (plugin.getConfig().getString("presets." + preset.toLowerCase()) == null) {
plugin.sendMessage(event.getPlayer(), "error.preset-doesnt-exist", "preset", preset);
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onSignDestroy(BlockBreakEvent event) {
if (event.getBlock().getType().name().contains("SIGN")) {
Sign sign = (Sign) event.getBlock().getState();
if (plugin.matchesSignVariable(sign.getLine(1))) {
if (!event.getPlayer().hasPermission("randomteleport.sign.destroy")) {
event.setCancelled(true);
plugin.sendMessage(event.getPlayer(), "sign.no-permission.destroy", "perm", "randomteleport.sign.destroy");
} else {
plugin.sendMessage(event.getPlayer(), "sign.destroyed", "preset", sign.getLine(2));
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
if (event.getHand() == EquipmentSlot.HAND && event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock().getType().name().contains("SIGN")) {
Sign sign = (Sign) event.getClickedBlock().getState();
if (plugin.matchesSignVariable(sign.getLine(1))) {
String preset = sign.getLine(2).toLowerCase();
if (event.getPlayer().hasPermission("randomteleport.sign.preset." + preset)) {
if (plugin.getConfig().getString("presets." + preset) == null) {
plugin.sendMessage(event.getPlayer(), "error.preset-doesnt-exist", "preset", preset);
} else {
try {
plugin.runPreset(plugin.getServer().getConsoleSender(), preset, event.getPlayer(), event.getClickedBlock().getLocation());
} catch (IllegalArgumentException e) {
plugin.sendMessage(event.getPlayer(), "error.preset-invalid", "preset", preset);
plugin.getLogger().log(Level.SEVERE, "Error while parsing preset " + preset, e);
}
}
} else {
plugin.sendMessage(event.getPlayer(), "sign.no-permission.use",
"preset", preset,
"perm", "randomteleport.sign.use"
);
}
}
}
}
}

View File

@ -52,6 +52,8 @@ public class RandomSearcher {
private int cooldown;
private int checks = 0;
private CompletableFuture<Location> future = null;
public RandomSearcher(RandomTeleport plugin, CommandSender initiator, Location center, int minRadius, int maxRadius) {
this.plugin = plugin;
this.initiator = initiator;
@ -201,7 +203,7 @@ public class RandomSearcher {
* @return A CompletableFuture for when the search task is complete
*/
public CompletableFuture<Location> search() {
CompletableFuture<Location> future = new CompletableFuture<>();
future = new CompletableFuture<>();
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> checkRandom(future));
return future;
}
@ -244,4 +246,12 @@ public class RandomSearcher {
public CommandSender getInitiator() {
return initiator;
}
/**
* Get the currently running search future
* @return The currently running search future or null if none is running
*/
public CompletableFuture<Location> getFuture() {
return future;
}
}

View File

@ -62,11 +62,15 @@ unsave-blocks:
- end_rod
- end_gateway
# Just write your command as you would use it ingame here
# Don't use the -p parameter, this will get added automaticly with the senders name/the specified playername
sign-variables:
- "[RTP]"
- "[RandomTP]"
# Just write your command arguments as you would use it ingame behind /rtp
# Don't use the -p parameter, this will get added automatically with the senders name/the specified playername
presets:
# Triggered when you use /rtp without any additional paramters
default: "/rtp 100 1000 -f"
default: "100 1000 -f"
# add more to use /rtp <rtpname>, player needs "randomteleport.presets.<rtpname>"
# <rtpname>: "/rtp 1 2"
test: "rtp 10 200 -f"
test: "10 200 -f"

View File

@ -2,6 +2,13 @@ reloaded: "&eReloaded the config. Some settings might require a server restart!"
search: "&7RandomTeleport searches for a safe place in world {worldname}. . ."
teleport: "&7RandomTeleport teleported you to X: {x} Y: {y} Z: {z}!"
setspawnpoint: "&7Your Respawnpoint has been set to your current location!"
sign:
created: "&aRandomTeleport preset sign &e{preset}&a created!"
destroyed: "&aRandomTeleport preset sign &e{preset}&a destroyed!"
no-permission:
destroy: "&cYou don't have permission to destroy RandomTeleport preset signs! &o({perm})"
create: "&cYou don't have permission to create RandomTeleport preset signs! &o({perm})"
use: "&cYou don't have permission to use the preset &6{preset}&c! &o({perm})"
error:
location: "&4Error: &cRandomTeleport could not find a save location!"
cooldown: "&cYou have to wait {cooldown_text}before using this RandomTeleport again!"
@ -9,3 +16,9 @@ error:
not-found: "&cCould not find &f{what}&c!"
player-not-found: "&cCould not find a player with the name &f{what}&c!"
world-not-found: "&cCould not find a world with the name &f{what}&c!"
preset-doesnt-exist: "&cThe RandomTeleport preset &6{preset}&c does not exist!"
preset-invalid: "&cThe preset &6{preset}&c is not setup correctly! Please contact an admin."
no-permission:
general: "&cYou don't have permission to do that! &o({perm})"
preset: "&cYou don't have permission to use the preset &6{preset}&c! &o({perm})"
tp-others: "&cYou don't have permission to teleport other players! &o({perm})"

View File

@ -25,8 +25,8 @@ commands:
> -c, -cooldown <seconds> - cooldown in seconds after which the player can use this teleporter again
> -f,-force - teleport even if there is no dirt/grass/sand/gravel, only checks for lava/water/cactus, ignores WorldGuard/Faction regions
> -f,-force [<blocks|regions>] - only ignore blocks or regions
/<command> stat - shows a statistic of the teleports since the last restart
/<command> reload - reloads the config
/<command> --stat - shows a statistic of the teleports since the last restart
/<command> --reload - reloads the config
permissions:
randomteleport.use:
description: Gives permission to the command
@ -56,5 +56,8 @@ permissions:
description: Gives permission to use all presets with a rightclick on a preset sign
default: op
randomteleport.sign.create:
description: Allows to create and destroy preset signs ([rtp] or [RandomTP] on the 2nd line and the preset name on the 3rd)
description: Allows creating preset signs ([rtp] or [RandomTP] on the 2nd line and the preset name on the 3rd)
default: op
randomteleport.sign.destroy:
description: Allows destroying preset signs ([rtp] or [RandomTP] on the 2nd line and the preset name on the 3rd)
default: op