diff --git a/.github/workflows/automatic-build.yml b/.github/workflows/automatic-build.yml index cdd07377..ca564036 100644 --- a/.github/workflows/automatic-build.yml +++ b/.github/workflows/automatic-build.yml @@ -23,7 +23,7 @@ jobs: arguments: shadowJar - name: Uploading - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: SpeedBridge-2 - path: ${{ github.workspace }}/speedbridge2-spigot-plugin/build/libs/*.jar + path: ${{ github.workspace }}/spigot/build/libs/*.jar diff --git a/.gitignore b/.gitignore index 2c995164..f1858821 100644 --- a/.gitignore +++ b/.gitignore @@ -111,6 +111,7 @@ buildNumber.properties # Common working directory run/ +run-*/ demo dep.txt memory diff --git a/build.gradle.kts b/build.gradle.kts index b19b2dd7..1a65c3c9 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -14,34 +14,6 @@ allprojects { group = "io.tofpu.speedbridge2" version = "1.1.4-" + "git rev-parse --short=8 HEAD".runCommand(rootDir) - repositories { - mavenLocal() - mavenCentral() - - maven("https://jitpack.io") - maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") - maven("https://maven.enginehub.org/repo/") - maven("https://oss.sonatype.org/content/groups/public/") - maven("https://repo.codemc.org/repository/maven-public/") - maven("https://libraries.minecraft.net") - } - - dependencies { - compileOnly("org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT") - - implementation("com.github.Revxrsal.Lamp:common:3.1.7") - - implementation("net.kyori:adventure-api:4.10.1") - implementation("net.kyori:adventure-text-minimessage:4.10.1") - - implementation("com.github.tofpu:DynamicClass:1.1") { - exclude("com.google.guava", "guava") - } - - testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0") - testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") - } - publishing { publications { create("maven") { diff --git a/image/screenshots/bridging.png b/image/screenshots/bridging.png new file mode 100644 index 00000000..26bdf338 Binary files /dev/null and b/image/screenshots/bridging.png differ diff --git a/image/screenshots/scored.png b/image/screenshots/scored.png new file mode 100644 index 00000000..46b0dfa0 Binary files /dev/null and b/image/screenshots/scored.png differ diff --git a/spigot/build.gradle.kts b/spigot/build.gradle.kts index 68a87851..f8635dbd 100644 --- a/spigot/build.gradle.kts +++ b/spigot/build.gradle.kts @@ -2,11 +2,29 @@ plugins { id("xyz.jpenilla.run-paper") version "2.0.1" } +repositories { + mavenLocal() + mavenCentral() + + maven("https://jitpack.io") + maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") + maven("https://maven.enginehub.org/repo/") + maven("https://oss.sonatype.org/content/groups/public/") + maven("https://repo.codemc.org/repository/maven-public/") + maven("https://libraries.minecraft.net") +} + dependencies { + compileOnly("org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT") + compileOnly("org.xerial:sqlite-jdbc:3.36.0.3") compileOnly("com.sk89q:worldedit:6.0.0-SNAPSHOT") - implementation("com.github.Revxrsal.Lamp:bukkit:3.1.7") + implementation("com.github.Revxrsal.Lamp:common:3.2.1") + implementation("com.github.Revxrsal.Lamp:bukkit:3.2.1") + + implementation("net.kyori:adventure-api:4.10.1") + implementation("net.kyori:adventure-text-minimessage:4.10.1") implementation("net.kyori:adventure-platform-bukkit:4.0.1") implementation("com.github.tofpu:DynamicClass:1.1") { @@ -20,22 +38,25 @@ dependencies { implementation("org.bstats:bstats-bukkit:3.0.0") - compileOnly("me.clip:placeholderapi:2.10.10") + compileOnly("me.clip:placeholderapi:2.11.6") implementation("com.github.ben-manes.caffeine:caffeine:2.9.3") implementation("com.github.cryptomorin:XSeries:8.7.1") - implementation("com.github.tofpu.MultiWorldEdit:multiworldedit-api:0eb85d6cbd") { + implementation("com.github.tofpu.MultiWorldEdit:multiworldedit-api:8930fd3caa") { exclude("de.schlichtherle", "truezip") exclude("rhino", "js") exclude("com.sk89q", "worldedit") } - implementation("com.github.tofpu:umbrella:1.20-support-SNAPSHOT") + implementation("com.github.Tofpu:toolbar:v1-SNAPSHOT") + implementation("com.github.Tofpu:dynamicclass:1.3") { + exclude("com.google.guava", "guava") + } } tasks { - named("shadowJar") { + shadowJar { archiveName = "Speedbridge2-${version}-all.jar" dependencies { @@ -56,8 +77,10 @@ tasks { } runServer { - minecraftVersion("1.8.8") -// pluginJars(project.file("libs/worldedit-bukkit-7.2.15.jar")) - pluginJars(project.file("libs/worldedit-bukkit-6.1.jar")) +// minecraftVersion("1.8.8") +// pluginJars(project.file("libs/worldedit-bukkit-6.1.jar")) +// minecraftVersion("1.20.4") + minecraftVersion("1.19.4") + pluginJars(project.file("libs/worldedit-bukkit-7.3.0.jar")) } -} \ No newline at end of file +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/SpeedBridge.java b/spigot/src/main/java/io/tofpu/speedbridge2/SpeedBridge.java index 8c2a6f0f..b3d724b4 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/SpeedBridge.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/SpeedBridge.java @@ -3,7 +3,6 @@ import io.tofpu.dynamicclass.DynamicClass; import io.tofpu.multiworldedit.MultiWorldEditAPI; import io.tofpu.speedbridge2.command.CommandManager; -import io.tofpu.speedbridge2.command.subcommand.HelpCommandGenerator; import io.tofpu.speedbridge2.model.blockmenu.BlockMenuManager; import io.tofpu.speedbridge2.model.common.Message; import io.tofpu.speedbridge2.model.common.PluginExecutor; @@ -50,6 +49,13 @@ public SpeedBridge(final JavaPlugin javaPlugin) { this.leaderboard = new Leaderboard(playerService); } + public static BukkitAudiences getAdventure() { + if (adventure == null) { + throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); + } + return adventure; + } + public void load() { // reset the world, in-case it does exist arenaManager.resetWorld(); @@ -84,7 +90,7 @@ public void enable() { if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { ExpansionHandler.INSTANCE.load(); - + log("Hooking into PlaceholderAPI..."); new PluginExpansion(javaPlugin, playerService); } @@ -133,25 +139,26 @@ public void enable() { log("Loading the messages..."); Message.load(javaPlugin.getDataFolder()); - log("Generating `/sb help` message..."); - HelpCommandGenerator.generateHelpCommand(javaPlugin); - - log("Checking for an update..."); - UpdateChecker.init(javaPlugin, 100619) - .requestUpdateCheck() - .whenComplete((updateResult, throwable) -> { - if (throwable != null) { - log("Couldn't check for an update..."); - return; - } - - if (updateResult.requiresUpdate()) { - log("You're using an outdated version of SpeedBridge!"); - log("You can download the latest version at https://www.spigotmc.org/resources/.100619/"); - } else { - log("You're using the latest version!"); - } - }); + if (ConfigurationManager.INSTANCE.getGeneralCategory().shouldCheckForUpdates()) { + log("Checking for an update..."); + UpdateChecker.init(javaPlugin, 100619) + .requestUpdateCheck() + .whenComplete((updateResult, throwable) -> { + if (throwable != null) { + log("Couldn't check for an update..."); + return; + } + + if (updateResult.requiresUpdate()) { + log("You're using an outdated version of SpeedBridge!"); + log("You can download the latest version at https://www.spigotmc.org/resources/.100619/"); + } else { + log("You're using the latest version!"); + } + }); + } else { + log("Not checking for an update as it was explicitly disabled in the config."); + } } public void shutdown() { @@ -177,11 +184,4 @@ public void shutdown() { private void log(final String content) { javaPlugin.getLogger().info(content); } - - public static BukkitAudiences getAdventure() { - if(adventure == null) { - throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); - } - return adventure; - } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/CommandManager.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/CommandManager.java index cd4f24a0..dc159cbe 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/CommandManager.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/CommandManager.java @@ -3,8 +3,10 @@ import io.tofpu.dynamicclass.DynamicClass; import io.tofpu.speedbridge2.command.condition.AbstractCommandConditionWrapper; import io.tofpu.speedbridge2.command.condition.LampConditionRegistry; +import io.tofpu.speedbridge2.command.condition.annotation.OptionalPermission; import io.tofpu.speedbridge2.command.context.AbstractLampContext; import io.tofpu.speedbridge2.command.context.LampContextRegistry; +import io.tofpu.speedbridge2.command.help.HelpGenerator; import io.tofpu.speedbridge2.command.parser.AbstractLampParser; import io.tofpu.speedbridge2.command.parser.LampParseRegistry; import io.tofpu.speedbridge2.command.subcommand.CommandCompletion; @@ -19,6 +21,7 @@ import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import io.tofpu.speedbridge2.model.player.object.CommonBridgePlayer; import io.tofpu.speedbridge2.model.player.object.SenderBridgePlayer; +import org.bukkit.Material; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import revxrsal.commands.bukkit.BukkitCommandActor; @@ -29,7 +32,10 @@ import java.util.UUID; +import static io.tofpu.speedbridge2.model.common.util.BridgeUtil.log; + public final class CommandManager { + private static final HelpGenerator helpGenerator = new HelpGenerator(); private static BukkitCommandHandler commandHandler; public static void load(final @NotNull Plugin plugin, @@ -84,16 +90,25 @@ public boolean isCustomType(final Class type) { constructTabCompleter(islandService); constructCommandConditions(); - commandHandler.register(new SpeedBridgeCommand(playerService, islandService)); + commandHandler.registerAnnotationReplacer(OptionalPermission.class, OptionalPermission.AnnotationReplacerImpl.INSTANCE); + commandHandler.registerPermissionReader(OptionalPermission.PermissionReaderImpl.INSTANCE); + + commandHandler.accept(new SpeedBridgeCommand(helpGenerator, playerService, islandService)); commandHandler.register(new SpeedBridgeDebugCommand(arenaManager)); + + log("Generating `/sb help` message..."); + helpGenerator.generate(plugin, commandHandler); + + commandHandler.registerBrigadier(); } private static void constructTabCompleter(final @NotNull IslandService islandService) { BridgeUtil.debug("Constructing tab completer..."); - commandHandler.getAutoCompleter() - .registerParameterSuggestions(Island.class, - new CommandCompletion(islandService)::islands); + CommandCompletion commandCompletion = new CommandCompletion(islandService); + commandHandler.getAutoCompleter().registerParameterSuggestions(Island.class, commandCompletion::islands); + commandHandler.getAutoCompleter().registerParameterSuggestions(Material.class, commandCompletion::materials); + commandHandler.getAutoCompleter().registerParameterSuggestions(BridgePlayer.class, commandCompletion::players); } private static void constructContext() { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/AbstractCommandConditionWrapper.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/AbstractCommandConditionWrapper.java index 7e1401d6..8b872039 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/AbstractCommandConditionWrapper.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/AbstractCommandConditionWrapper.java @@ -14,7 +14,7 @@ public abstract class AbstractCommandConditionWrapper implements CommandConditio private final Class type; public AbstractCommandConditionWrapper(final Class type, - final LampConditionRegistry registry) { + final LampConditionRegistry registry) { this.type = type; registry.register(type, this); } @@ -35,8 +35,8 @@ public final void test( } abstract void execute(@NotNull CommandActor actor, - @NotNull ExecutableCommand command, - @NotNull @Unmodifiable List arguments); + @NotNull ExecutableCommand command, + @NotNull @Unmodifiable List arguments); public Class getType() { return type; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/LampConditionRegistry.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/LampConditionRegistry.java index ffd31bf1..fdceba3e 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/LampConditionRegistry.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/LampConditionRegistry.java @@ -7,4 +7,5 @@ @AutoRegister public final class LampConditionRegistry extends AbstractLampRegistry, AbstractCommandConditionWrapper> {} + extends Annotation>, AbstractCommandConditionWrapper> { +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/MaterialType.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/MaterialType.java new file mode 100644 index 00000000..99c59e4e --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/MaterialType.java @@ -0,0 +1,14 @@ +package io.tofpu.speedbridge2.command.condition.annotation; + +import io.tofpu.speedbridge2.util.material.MaterialCategory; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface MaterialType { + MaterialCategory category(); +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/OptionalPermission.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/OptionalPermission.java new file mode 100644 index 00000000..71204b05 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/OptionalPermission.java @@ -0,0 +1,47 @@ +package io.tofpu.speedbridge2.command.condition.annotation; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import revxrsal.commands.annotation.Optional; +import revxrsal.commands.annotation.dynamic.AnnotationReplacer; +import revxrsal.commands.annotation.dynamic.Annotations; +import revxrsal.commands.bukkit.BukkitCommandActor; +import revxrsal.commands.command.CommandPermission; +import revxrsal.commands.command.trait.CommandAnnotationHolder; +import revxrsal.commands.process.PermissionReader; + +import java.lang.annotation.*; +import java.lang.reflect.AnnotatedElement; +import java.util.Collection; + +import static revxrsal.commands.util.Collections.linkedListOf; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface OptionalPermission { + String value(); + + enum AnnotationReplacerImpl implements AnnotationReplacer { + INSTANCE; + + @Override + public Collection replaceAnnotations(@NotNull AnnotatedElement element, @NotNull OptionalPermission annotation) { + Optional optional = Annotations.create(Optional.class); + return linkedListOf(optional, annotation); + } + } + + enum PermissionReaderImpl implements PermissionReader { + INSTANCE { + @Override + public @Nullable CommandPermission getPermission(@NotNull CommandAnnotationHolder command) { + OptionalPermission annotation = command.getAnnotation(OptionalPermission.class); + if (annotation == null) return null; + return actor -> { + BukkitCommandActor playerActor = (BukkitCommandActor) actor; + return playerActor.requirePlayer().hasPermission(annotation.value()); + }; + } + } + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictConsole.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictConsole.java index d897cd47..f1c1a12a 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictConsole.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictConsole.java @@ -7,4 +7,5 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) -public @interface RestrictConsole {} +public @interface RestrictConsole { +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictDummyModel.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictDummyModel.java index 6dbe5cdd..4c27974e 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictDummyModel.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/condition/annotation/RestrictDummyModel.java @@ -7,4 +7,5 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) -public @interface RestrictDummyModel {} +public @interface RestrictDummyModel { +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/context/GameIslandContext.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/context/GameIslandContext.java index 86c9f56a..8f20bed7 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/context/GameIslandContext.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/context/GameIslandContext.java @@ -8,6 +8,7 @@ import revxrsal.commands.exception.CommandErrorException; import revxrsal.commands.process.ContextResolver; + import static io.tofpu.speedbridge2.model.common.Message.INSTANCE; @AutoRegister @@ -22,14 +23,20 @@ public GameIslandContext(final LampContextRegistry registry, final PlayerService @Override public GameIsland resolve(final ContextResolver.ContextResolverContext context) { final BridgePlayer player = playerService.getIfPresent(context.actor().getUniqueId()); - if (player == null) { + boolean canBeNull = context.parameter().isOptional(); + + if (player == null && canBeNull) { + return null; + } else if (player == null) { throw new CommandErrorException(BridgeUtil.miniMessageToLegacy(INSTANCE.notLoaded)); } + final GameIsland currentGame = player.getCurrentGame(); - if (currentGame == null) { + if (currentGame == null && canBeNull) { + return null; + } else if (currentGame == null) { throw new CommandErrorException(BridgeUtil.miniMessageToLegacy(INSTANCE.notInAIsland)); } - return currentGame; } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/context/LampContextRegistry.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/context/LampContextRegistry.java index 24e7a403..5e4c3b34 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/context/LampContextRegistry.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/context/LampContextRegistry.java @@ -5,4 +5,5 @@ @AutoRegister public final class LampContextRegistry extends AbstractLampRegistry, - AbstractLampContext> {} + AbstractLampContext> { +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/HelpGenerator.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/HelpGenerator.java new file mode 100644 index 00000000..cd917017 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/HelpGenerator.java @@ -0,0 +1,43 @@ +package io.tofpu.speedbridge2.command.help; + +import io.tofpu.speedbridge2.command.help.collector.CommandCollector; +import io.tofpu.speedbridge2.command.help.styler.HelpMessageStyler; +import io.tofpu.speedbridge2.model.common.presenter.MessagePresenterHolder; +import io.tofpu.speedbridge2.model.common.util.BridgeUtil; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import revxrsal.commands.CommandHandler; + +import java.util.HashMap; +import java.util.Map; + +public class HelpGenerator implements HelpMessageProvider { + private final Map helpMessageMap = new HashMap<>(); + + private final CommandCollector commandCollector = new CommandCollector(); + private final HelpMessageStyler messageStyler = new HelpMessageStyler(); + + public void generate(Plugin plugin, CommandHandler handler) { + Map parentCommands = commandCollector.collectCommands(handler); + + for (Map.Entry entry : parentCommands.entrySet()) { + ParentCommand parentCommand = entry.getValue(); + + final MessagePresenterHolder holder = messageStyler.create(plugin, parentCommand); + Component helpMessageComponent = BridgeUtil.translateMiniMessage(holder.getResult()); + + helpMessageMap.put(parentCommand.name(), helpMessageComponent); + parentCommand.aliases().forEach(alias -> helpMessageMap.put(alias, helpMessageComponent)); + } + } + + public void showHelpMessage(String parent, final CommandSender sender) { + Component helpMessageComponent = helpMessageMap.get(parent); + if (helpMessageComponent == null) { + helpMessageComponent = Component.text(String.format("Help message unavailable for command %s", parent), NamedTextColor.RED); + } + BridgeUtil.sendMessage(sender, helpMessageComponent); + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/HelpMessageProvider.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/HelpMessageProvider.java new file mode 100644 index 00000000..52b3d708 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/HelpMessageProvider.java @@ -0,0 +1,7 @@ +package io.tofpu.speedbridge2.command.help; + +import org.bukkit.command.CommandSender; + +public interface HelpMessageProvider { + void showHelpMessage(String parent, final CommandSender sender); +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/ParentCommand.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/ParentCommand.java new file mode 100644 index 00000000..5e50277c --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/ParentCommand.java @@ -0,0 +1,29 @@ +package io.tofpu.speedbridge2.command.help; + +import revxrsal.commands.command.ExecutableCommand; + +import java.util.*; + +public class ParentCommand { + private final String name; + private final Set aliases; + private final List commands; + + public ParentCommand(String name, Collection aliases, Collection commands) { + this.name = name; + this.aliases = new LinkedHashSet<>(aliases); + this.commands = new LinkedList<>(commands); + } + + public String name() { + return name; + } + + public Collection aliases() { + return Collections.unmodifiableSet(aliases); + } + + public Collection commands() { + return Collections.unmodifiableList(commands); + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/CommandCollector.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/CommandCollector.java new file mode 100644 index 00000000..3398ec89 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/CommandCollector.java @@ -0,0 +1,99 @@ +package io.tofpu.speedbridge2.command.help.collector; + +import io.tofpu.speedbridge2.command.help.ParentCommand; +import org.jetbrains.annotations.NotNull; +import revxrsal.commands.CommandHandler; +import revxrsal.commands.command.ExecutableCommand; +import revxrsal.commands.core.CommandPath; + +import java.util.*; +import java.util.function.Consumer; + +public class CommandCollector { + + public Map collectCommands(CommandHandler handler) { + Map commandNodeMap = collectAsNode(handler); + Map parentCommandMap = new HashMap<>(); + + commandNodeMap.forEach((parent, treeCommandNode) -> { + Iterator iterator = treeCommandNode.childrenIterator(); + List subCommands = new LinkedList<>(); + iterate(parent, commandInfo -> subCommands.add(commandInfo.executableCommand()), iterator); + + parentCommandMap.put(parent, new ParentCommand(parent, treeCommandNode.data().aliases(), subCommands)); + }); + + return parentCommandMap; + } + + static void iterate(String rootPath, Consumer pathConsumer, Iterator iterator) { + while (iterator.hasNext()) { + TreeCommandNode next = iterator.next(); + CommandInfo commandEntry = next.data(); + + String subcommandName = commandEntry.name(); + String path = rootPath + " " + subcommandName; + + if (next.children().isEmpty()) { + pathConsumer.accept(commandEntry); + continue; + } + + // traverse to children's commands + Iterator childrenIterator = next.childrenIterator(); + iterate(path, pathConsumer, childrenIterator); + } + } + + @NotNull Map collectAsNode(CommandHandler handler) { + Set duplicateId = new TreeSet<>(); + + // sub command to parent mapping + Map subCommandToParentMapping = new HashMap<>(); + // this is where the parent commands are stored + Map parentCommands = new LinkedHashMap<>(); + + // this is where the commands are sorted based on size; low to high + Map sortedCommandsMap = getAndSortCommands(handler); + + for (Map.Entry entry : sortedCommandsMap.entrySet()) { + CommandPath commandPath = entry.getKey(); + ExecutableCommand executableCommand = entry.getValue(); + + int commandId = executableCommand.getId(); + duplicateId.add(commandId); + + String parent = commandPath.getParent(); + TreeCommandNode parentTreeNode = parentCommands.get(parent); + + // lets us find the 'original' command name if the subcommands were previously processed + if (parentTreeNode == null) { + parentTreeNode = subCommandToParentMapping.get(commandId); + } + + if (parentTreeNode == null) { + parentTreeNode = new TreeCommandNode(new CommandInfo(parent)); + parentCommands.put(parent, parentTreeNode); + subCommandToParentMapping.put(commandId, parentTreeNode); + } else if (duplicateId.contains(commandId)) { + parentTreeNode.data().addAlias(parent); + } + + TreeCommandNode subcommandNode = parentTreeNode; + for (String subPath : commandPath.getSubcommandPath()) { + subcommandNode = subcommandNode.path(subPath, new CommandInfo(parent)); + } + subcommandNode.data(new CommandInfo(commandPath.getName(), executableCommand)); + } + return parentCommands; + } + + static @NotNull Map getAndSortCommands(CommandHandler handler) { + Map sortedCommandsMap = new LinkedHashMap<>(); + + handler.getCommands().keySet(). + stream().sorted(Comparator.comparingInt(CommandPath::size)) + .forEachOrdered(path -> sortedCommandsMap.put(path, handler.getCommand(path))); + return sortedCommandsMap; + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/CommandInfo.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/CommandInfo.java new file mode 100644 index 00000000..f20c3511 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/CommandInfo.java @@ -0,0 +1,41 @@ +package io.tofpu.speedbridge2.command.help.collector; + +import revxrsal.commands.command.ExecutableCommand; + +import java.util.Set; +import java.util.TreeSet; + +public class CommandInfo { + private final String name; + private final Set aliases = new TreeSet<>(); + private ExecutableCommand executableCommand = null; + + public CommandInfo(String name) { + this.name = name; + } + + public CommandInfo(String name, ExecutableCommand executableCommand) { + this.name = name; + this.executableCommand = executableCommand; + } + + public void addAlias(String name) { + aliases.add(name); + } + + public void executableCommand(ExecutableCommand executableCommand) { + this.executableCommand = executableCommand; + } + + public String name() { + return name; + } + + public ExecutableCommand executableCommand() { + return executableCommand; + } + + public Set aliases() { + return aliases; + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/TreeCommandNode.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/TreeCommandNode.java new file mode 100644 index 00000000..9ab1b415 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/TreeCommandNode.java @@ -0,0 +1,30 @@ +package io.tofpu.speedbridge2.command.help.collector; + +import java.util.Iterator; + +public class TreeCommandNode extends TreeNode { + public TreeCommandNode(CommandInfo data) { + super(data); + } + + @Override + public TreeCommandNode path(String name, CommandInfo data) { + return (TreeCommandNode) path(name, new TreeCommandNode(data)); + } + + public Iterator childrenIterator() { + return new Iterator() { + final Iterator> iterator = TreeCommandNode.super.children().iterator(); + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public TreeCommandNode next() { + return (TreeCommandNode) iterator.next(); + } + }; + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/TreeNode.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/TreeNode.java new file mode 100644 index 00000000..e41e5e02 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/collector/TreeNode.java @@ -0,0 +1,49 @@ +package io.tofpu.speedbridge2.command.help.collector; + +import java.util.*; + +public class TreeNode { + protected final Map> children; + protected T data; + protected TreeNode parent; + + public TreeNode(T data) { + this.data = data; + this.children = new LinkedHashMap<>(); + } + + public void data(T data) { + this.data = data; + } + + public TreeNode path(String name, T data) { + return path(name, new TreeNode<>(data)); + } + + TreeNode path(String name, TreeNode childNode) { + return children.computeIfAbsent(name, t -> { + childNode.parent = TreeNode.this; + return childNode; + }); + } + + public TreeNode parent() { + return parent; + } + + public T data() { + return data; + } + + public Collection> children() { + return children.values(); + } + + @Override + public String toString() { + return new StringJoiner(", ", TreeNode.class.getSimpleName() + "[", "]") + .add("data=" + data) + .add("children=" + children) + .toString(); + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/help/styler/HelpMessageStyler.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/styler/HelpMessageStyler.java new file mode 100644 index 00000000..7734bb64 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/help/styler/HelpMessageStyler.java @@ -0,0 +1,64 @@ +package io.tofpu.speedbridge2.command.help.styler; + +import io.tofpu.speedbridge2.command.help.ParentCommand; +import io.tofpu.speedbridge2.model.common.presenter.MessagePresenterHolder; +import io.tofpu.speedbridge2.model.common.presenter.MessagePresenterHolderImpl; +import io.tofpu.speedbridge2.model.common.presenter.type.MessagePairPresenter; +import io.tofpu.speedbridge2.model.common.presenter.type.MessageTreePresenter; +import org.apache.commons.lang.StringUtils; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; + +public class HelpMessageStyler { + + private static final String TITLE = "%s"; + private static final String KEY_STYLE = "%s"; + private static final String VALUE_STYLE = "%s"; + private static final String COMMAND_STYLE = "/%s %s - %s"; + private static final String DISCORD_LINK = "https://discord.gg/cDQjsHugPw"; + + public @NotNull MessagePresenterHolder create(Plugin plugin, ParentCommand parentCommand) { + final MessagePresenterHolder holder = new MessagePresenterHolderImpl("SpeedBridge v2"); + holder.append(() -> { + final MessagePairPresenter.Builder builder = new MessagePairPresenter.Builder(); + + builder.title(String.format(TITLE, "Information")); + builder.pair(String.format(KEY_STYLE, "Author"), String.format(VALUE_STYLE, "Tofpu")) + .pair(String.format(KEY_STYLE, "Version"), String.format(VALUE_STYLE, plugin.getDescription() + .getVersion())); + + return builder.build(); + }); + + holder.append(() -> { + final MessageTreePresenter.Builder builder = new MessageTreePresenter.Builder(); + builder.title(String.format(TITLE, "Commands")); + + parentCommand.commands().forEach(command -> { + String path = command.getPath().toRealString(); + String usage = command.getUsage(); + String description = command.getDescription(); + if (description == null) { + description = "No description provided"; + } + + String message = String.format(COMMAND_STYLE, path, usage, description); + message = StringUtils.normalizeSpace(message); + builder.message(message); + }); + + return builder.build(); + }); + + holder.append(() -> { + final MessagePairPresenter.Builder builder = new MessagePairPresenter.Builder(); + + builder.title(String.format(TITLE, "Support")) + .pair(String.format(KEY_STYLE, "Discord"), String.format(VALUE_STYLE, + "" + DISCORD_LINK)); + + return builder.build(); + }); + return holder; + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/BridgePlayerParser.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/BridgePlayerParser.java new file mode 100644 index 00000000..c75fdd60 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/BridgePlayerParser.java @@ -0,0 +1,33 @@ +package io.tofpu.speedbridge2.command.parser; + +import io.tofpu.dynamicclass.meta.AutoRegister; +import io.tofpu.speedbridge2.model.common.util.BridgeUtil; +import io.tofpu.speedbridge2.model.player.PlayerService; +import io.tofpu.speedbridge2.model.player.object.BridgePlayer; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import revxrsal.commands.exception.CommandErrorException; +import revxrsal.commands.process.ValueResolver; + +import static io.tofpu.speedbridge2.model.common.Message.INSTANCE; + +@AutoRegister +public class BridgePlayerParser extends AbstractLampParser { + private final PlayerService playerService; + + public BridgePlayerParser(PlayerService playerService, LampParseRegistry registry) { + super(BridgePlayer.class, registry); + this.playerService = playerService; + } + + @Override + BridgePlayer parse(ValueResolver.ValueResolverContext context) { + final String input = context.pop(); + Player player = Bukkit.getPlayer(input); + BridgePlayer bridgePlayer = player == null ? null : playerService.getIfPresent(player.getUniqueId()); + if (bridgePlayer == null) { + throw new CommandErrorException(BridgeUtil.miniMessageToLegacy(String.format(INSTANCE.mustBeOnline, input))); + } + return bridgePlayer; + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/LampParseRegistry.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/LampParseRegistry.java index 326bc9ea..e281c571 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/LampParseRegistry.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/LampParseRegistry.java @@ -5,4 +5,5 @@ @AutoRegister public final class LampParseRegistry extends AbstractLampRegistry, - AbstractLampParser> {} + AbstractLampParser> { +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/MaterialParser.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/MaterialParser.java new file mode 100644 index 00000000..9a96eca9 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/MaterialParser.java @@ -0,0 +1,26 @@ +package io.tofpu.speedbridge2.command.parser; + +import io.tofpu.dynamicclass.meta.AutoRegister; +import io.tofpu.speedbridge2.model.common.Message; +import io.tofpu.speedbridge2.model.common.util.BridgeUtil; +import io.tofpu.speedbridge2.util.material.MultiMaterial; +import org.bukkit.Material; +import revxrsal.commands.exception.CommandErrorException; +import revxrsal.commands.process.ValueResolver; + +@AutoRegister +public class MaterialParser extends AbstractLampParser { + public MaterialParser(LampParseRegistry registry) { + super(Material.class, registry); + } + + @Override + Material parse(ValueResolver.ValueResolverContext context) { + String materialName = context.pop(); + try { + return MultiMaterial.getOrThrow(materialName); + } catch (Exception e) { + throw new CommandErrorException(String.format(BridgeUtil.miniMessageToLegacy(Message.INSTANCE.invalidMaterial), materialName)); + } + } +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/annotation/PlayerUUID.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/annotation/PlayerUUID.java index c7f708d1..ff22cc6c 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/annotation/PlayerUUID.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/parser/annotation/PlayerUUID.java @@ -7,4 +7,5 @@ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) -public @interface PlayerUUID {} +public @interface PlayerUUID { +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/CommandCompletion.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/CommandCompletion.java index 4fd88f1e..835882e6 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/CommandCompletion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/CommandCompletion.java @@ -1,12 +1,21 @@ package io.tofpu.speedbridge2.command.subcommand; +import io.tofpu.speedbridge2.command.condition.annotation.MaterialType; import io.tofpu.speedbridge2.model.island.IslandService; +import io.tofpu.speedbridge2.util.material.MultiMaterial; +import org.bukkit.Bukkit; +import org.bukkit.entity.HumanEntity; import org.jetbrains.annotations.NotNull; +import revxrsal.commands.bukkit.BukkitCommandActor; import revxrsal.commands.command.CommandActor; import revxrsal.commands.command.ExecutableCommand; +import java.lang.reflect.Parameter; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; public final class CommandCompletion { private final IslandService islandService; @@ -16,14 +25,43 @@ public CommandCompletion(final IslandService islandService) { } public @NotNull List islands(final List args, final CommandActor actor, - final ExecutableCommand command) { + final ExecutableCommand command) { final List suggestions = new ArrayList<>(); for (final Integer integer : islandService.getIntegerIslands()) { - suggestions.add(integer + ""); + suggestions.add(String.valueOf(integer)); } System.out.println("CommandCompletion#islands: suggestions - " + suggestions); return suggestions; } + + public @NotNull Collection materials(final List args, final CommandActor actor, + final ExecutableCommand command) { + AtomicReference annotationRef = new AtomicReference<>(); + boolean anyMatch = command.getParameters().stream().anyMatch(commandParameter -> { + Parameter javaParameter = commandParameter.getJavaParameter(); + boolean present = javaParameter.isAnnotationPresent(MaterialType.class); + if (present) { + annotationRef.set(javaParameter.getAnnotation(MaterialType.class)); + } + return present; + }); + + MaterialType annotation = annotationRef.get(); + if (!anyMatch) { + return MultiMaterial.materials(); + } + return MultiMaterial.materials(annotation.category()); + } + + public Collection players(@NotNull List args, @NotNull CommandActor sender, @NotNull ExecutableCommand executableCommand) { + return Bukkit.getOnlinePlayers().stream() + .filter(player -> !((BukkitCommandActor) sender).isPlayer() + || ((BukkitCommandActor) sender).requirePlayer().canSee(player) + && !((BukkitCommandActor) sender).getSender().equals(player) + ).map(HumanEntity::getName) + .collect(Collectors.toList()); + + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/HelpCommandGenerator.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/HelpCommandGenerator.java deleted file mode 100644 index c55fbb5e..00000000 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/HelpCommandGenerator.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.tofpu.speedbridge2.command.subcommand; - -import io.tofpu.speedbridge2.model.common.presenter.MessagePresenterHolder; -import io.tofpu.speedbridge2.model.common.presenter.MessagePresenterHolderImpl; -import io.tofpu.speedbridge2.model.common.presenter.type.MessagePairPresenter; -import io.tofpu.speedbridge2.model.common.presenter.type.MessageTreePresenter; -import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.player.object.CommonBridgePlayer; -import net.kyori.adventure.text.Component; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import revxrsal.commands.annotation.Description; -import revxrsal.commands.annotation.Flag; -import revxrsal.commands.annotation.Optional; -import revxrsal.commands.annotation.Subcommand; -import revxrsal.commands.annotation.Usage; - -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -public final class HelpCommandGenerator { - private static final String TITLE = "%s"; - private static final String KEY_STYLE = "%s"; - private static final String VALUE_STYLE = "%s"; - private static final String COMMAND_STYLE = "/sb %s %s- %s"; - private static final String DISCORD_LINK = "https://discord.gg/cDQjsHugPw"; - - private static Component helpMessageComponent = null; - - public static void generateHelpCommand(final @NotNull Plugin plugin) { - final Method[] declaredMethods = SpeedBridgeCommand.class.getDeclaredMethods(); - - final MessagePresenterHolder holder = new MessagePresenterHolderImpl("SpeedBridge v2"); - - holder.append(() -> { - final MessagePairPresenter.Builder builder = new MessagePairPresenter.Builder(); - - builder.title(String.format(TITLE, "Information")); - builder.pair(String.format(KEY_STYLE, "Author"), String.format(VALUE_STYLE, "Tofpu")) - .pair(String.format(KEY_STYLE, "Version"), String.format(VALUE_STYLE, plugin.getDescription() - .getVersion())); - - return builder.build(); - }); - - holder.append(() -> { - final MessageTreePresenter.Builder builder = new MessageTreePresenter.Builder(); - - builder.title(String.format(TITLE, "Commands")); - for (final Method method : declaredMethods) { - final Subcommand commandMethod = method.getAnnotation(Subcommand.class); - final Description commandDescription = method.getAnnotation(Description.class); - if (commandMethod == null) { - continue; - } - final String usage = generateUsageOfMethod(commandMethod, method); - - builder.message(String.format(COMMAND_STYLE, commandMethod.value()[0], usage, commandDescription.value())); - } - return builder.build(); - }); - - holder.append(() -> { - final MessagePairPresenter.Builder builder = new MessagePairPresenter.Builder(); - - builder.title(String.format(TITLE, "Support")) - .pair(String.format(KEY_STYLE, "Discord"), String.format(VALUE_STYLE, - "" + DISCORD_LINK)); - - return builder.build(); - }); - - helpMessageComponent = BridgeUtil.translateMiniMessage(holder.getResult()); - } - - public static String generateUsageOfMethod(final Subcommand subcommand, - final Method method) { - final StringBuilder builder = new StringBuilder(); - - if (method.isAnnotationPresent(Usage.class)) { - return method.getAnnotation(Usage.class).value().replace(subcommand.value()[0] + " ", "") + " "; - } - - for (final Parameter parameter : method.getParameters()) { - if (CommonBridgePlayer.class.isAssignableFrom(parameter.getType())) { - continue; - } - - if (builder.length() != 0) { - builder.append(" "); - } - - final String name; - switch (parameter.getType().getSimpleName()) { - case "Island": - name = "slot"; - break; - default: - name = parameter.getName(); - } - - String startingTag = "<"; - String closingTag = ">"; - if (parameter.isAnnotationPresent(Optional.class)) { - startingTag = "["; - closingTag = "]"; - } - - String flag = ""; - if (parameter.isAnnotationPresent(Flag.class)) { - final Flag flagAnnotation = parameter.getAnnotation(Flag.class); - flag = "-" + flagAnnotation.value() + " "; - } - - builder.append(startingTag).append(flag).append(name).append(closingTag).append(" "); - } - - return builder.toString(); - } - - public static void showHelpMessage(final CommandSender sender) { - BridgeUtil.sendMessage(sender, helpMessageComponent); - } -} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/SpeedBridgeCommand.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/SpeedBridgeCommand.java index a5101ab5..83d9f5b0 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/SpeedBridgeCommand.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/SpeedBridgeCommand.java @@ -1,9 +1,8 @@ package io.tofpu.speedbridge2.command.subcommand; import io.tofpu.speedbridge2.command.NameAndUUID; -import io.tofpu.speedbridge2.command.condition.annotation.RestrictConsole; -import io.tofpu.speedbridge2.command.condition.annotation.RestrictDummyModel; -import io.tofpu.speedbridge2.command.condition.annotation.RestrictSetup; +import io.tofpu.speedbridge2.command.condition.annotation.*; +import io.tofpu.speedbridge2.command.help.HelpMessageProvider; import io.tofpu.speedbridge2.command.parser.annotation.PlayerUUID; import io.tofpu.speedbridge2.model.blockmenu.BlockMenuManager; import io.tofpu.speedbridge2.model.common.Message; @@ -23,18 +22,22 @@ import io.tofpu.speedbridge2.model.player.object.CommonBridgePlayer; import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.plugin.SpeedBridgePlugin; +import io.tofpu.speedbridge2.util.material.MaterialCategory; import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.command.CommandSender; +import org.bukkit.Material; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import revxrsal.commands.CommandHandler; +import revxrsal.commands.CommandHandlerVisitor; import revxrsal.commands.annotation.*; import revxrsal.commands.bukkit.annotation.CommandPermission; -import revxrsal.commands.bukkit.exception.MalformedEntitySelectorException; +import revxrsal.commands.command.CommandCategory; +import revxrsal.commands.command.ExecutableCommand; import java.util.ArrayList; import java.util.List; -import java.util.Optional; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; @@ -42,26 +45,33 @@ import java.util.stream.Collectors; import static io.tofpu.speedbridge2.model.common.Message.INSTANCE; -import static io.tofpu.speedbridge2.model.common.util.MessageUtil.Symbols.ARROW_RIGHT; -import static io.tofpu.speedbridge2.model.common.util.MessageUtil.Symbols.CHECK_MARK; -import static io.tofpu.speedbridge2.model.common.util.MessageUtil.Symbols.CROSS; +import static io.tofpu.speedbridge2.model.common.util.MessageUtil.Symbols.*; @Command({"sb", "speedbridge"}) -public final class SpeedBridgeCommand { +public final class SpeedBridgeCommand implements CommandHandlerVisitor { private static final String EMPTY_SCORE = "You haven't scored anything yet"; private static final String FORMATTED_SCORE = " " + CROSS.getSymbol() + " " + "Island " + - "%s" + " " + ARROW_RIGHT.getSymbol() + - " %s seconds"; + "%s" + " " + ARROW_RIGHT.getSymbol() + + " %s seconds"; + private final HelpMessageProvider helpMessageProvider; private final PlayerService playerService; private final IslandService islandService; - public SpeedBridgeCommand(final PlayerService playerService, final IslandService islandService) { + public SpeedBridgeCommand(final HelpMessageProvider helpMessageProvider, final PlayerService playerService, final IslandService islandService) { + this.helpMessageProvider = helpMessageProvider; this.playerService = playerService; this.islandService = islandService; } + @Override + public void visit(@NotNull CommandHandler handler) { + handler.register(this); + handler.register(new PlayerSubCommand()); + handler.register(new SetupCommand()); + } + @DefaultFor("~") @Description("The Main Command") public String defaultCommand() { @@ -81,14 +91,14 @@ public void onLobbySet(final BridgePlayer bridgePlayer) { } @Subcommand("create") - @Usage("create [-c category]") + @Usage(" [-c category]") @Description("Create an island") @CommandPermission("speedbridge.island.create") @RestrictSetup @RestrictDummyModel @RestrictConsole public String onIslandCreate(final BridgePlayer player, final int slot, final String schematic, - @revxrsal.commands.annotation.Optional @Flag("c") String category) { + @Optional @Flag("c") String category) { if (!isGeneralSetupComplete(player)) { return ""; } @@ -130,42 +140,13 @@ public String onIslandDelete(final Island target) { return String.format(INSTANCE.deletedAnIsland, target.getSlot()); } - @Subcommand("reset") - @Usage("reset ") - @Description("Resets player properties") - @CommandPermission("speedbridge.player.reset") - @AutoComplete("@players *") - public void onPlayerReset(final CommonBridgePlayer sender, final @PlayerUUID NameAndUUID target, - final ResetType type) { - String targetName = target.playerName(); - UUID targetId = target.playerUUID(); - - onCompletion(playerService.reset(targetId, type), unused -> { - String message = null; - switch (type) { - case ALL: - message = String.format(INSTANCE.playerWiped, targetName); - break; - case SCORES: - message = String.format(INSTANCE.playerScoreReset, targetName); - break; - case STATS: - message = String.format(INSTANCE.playerStatsReset, targetName); - break; - } - if (message == null) return; - BridgeUtil.sendMessage(sender, message); - }); - } - @Subcommand("modify") - @Usage("modify [-c category|-s schematic]") + @Usage(" [-c category|-s schematic]") @Description("Modify an island properties") @CommandPermission("speedbridge.island.modify") - public String onIslandSelect(final Island island, final @revxrsal.commands.annotation.Optional - @Flag(value = "c") @Default("") - String category, final @revxrsal.commands.annotation.Optional - @Flag(value = "s") @Default("") String schematic) { + public String onIslandSelect(final Island island, + final @Optional @Flag(value = "c") @Default("") String category, + final @Optional @Flag(value = "s") @Default("") String schematic) { final int slot = island.getSlot(); if (!category.isEmpty()) { @@ -210,42 +191,74 @@ private boolean isGeneralSetupComplete(final BridgePlayer bridgePlayer) { } @Command({"sb join", "speedbridge join" ,"join"}) - @Usage("join ") + @Usage("") @Description("Join an island") @RestrictDummyModel @RestrictConsole - public String onIslandJoin(final BridgePlayer bridgePlayer, final Island island) { - if (!isGeneralSetupComplete(bridgePlayer)) { + public String onIslandJoin(final BridgePlayer sender, final Island island, @OptionalPermission("sb.join.other") BridgePlayer target) { + if (!isGeneralSetupComplete(sender)) { return ""; } - if (bridgePlayer.isPlaying()) { + if (target == null && sender.isPlaying()) { return INSTANCE.alreadyInAIsland; + } else if (target != null && target.isPlaying()) { + return String.format(INSTANCE.otherIsAlreadyInAIsland, target.getName()); } if (!island.isReady()) { return String.format(INSTANCE.invalidIsland, island.getSlot()); } - island.join(bridgePlayer); - return String.format(INSTANCE.joinedAnIsland, island.getSlot() + ""); + if (target == null) { + island.join(sender); + return String.format(INSTANCE.joinedAnIsland, island.getSlot()); + } + + island.join(target); + return String.format(INSTANCE.otherJoinedAnIsland, target.getName(), island.getSlot()); } - @Command({"sb leave", "speedbridge leave" ,"leave"}) + @Command({"sb leave", "speedbridge leave", "leave"}) @Description("Leave an island") - public void onIslandLeave(final GameIsland gameIsland) { - gameIsland.stopGame(); + public String onIslandLeave(final BridgePlayer sender, + final @Optional GameIsland senderGame, + @OptionalPermission("sb.leave.other") BridgePlayer target) { + if (Objects.equals(sender, target)) { + target = null; + } + + System.out.println("onIslandLeave command called"); + if (senderGame == null && target == null) { + return String.format(INSTANCE.notInAIsland); + } else if (target == null) { + senderGame.stopGame(); + return ""; // handled by method + } + + GameIsland targetGame = target.getCurrentGame(); + int slot = targetGame == null ? -1 : targetGame.getIsland().getSlot(); + if (targetGame == null || !targetGame.stopGame()) { + return String.format(INSTANCE.otherNotInAIsland, target.getName(), slot); + } + return String.format(INSTANCE.otherLeftTheIsland, target.getName(), slot); } @Command({"sb score", "speedbridge score" ,"score"}) @Description("Shows a list of your scores") @RestrictConsole - public String onScore(final BridgePlayer bridgePlayer) { + public String onScore(final BridgePlayer sender, + @OptionalPermission("sb.score.other") BridgePlayer target) { + boolean isSender = target == null; + if (isSender) { + target = sender; + } + final List scoreList = new ArrayList<>(); - for (final Score score : bridgePlayer.getScores()) { + for (final Score score : target.getScores()) { if (scoreList.isEmpty()) { - scoreList.add(INSTANCE.scoreTitle); + scoreList.add(isSender ? INSTANCE.scoreTitle : String.format(INSTANCE.otherScoreTitle, target.getName())); } scoreList.add(String.format(FORMATTED_SCORE, score.getScoredOn(), BridgeUtil.formatNumber(score.getScore()))); @@ -268,6 +281,7 @@ public void chooseBlock(final BridgePlayer bridgePlayer) { } @Command({"sb islands", "speedbridge islands", "islands"}) + @CommandPermission("sb.islands") public String showIslands() { final MessagePresenterHolderImpl holder = new MessagePresenterHolderImpl( "List of Islands"); @@ -279,15 +293,15 @@ public String showIslands() { final String title = "Island Analysis\n"; final String schematicHover = title + "Schematic: " + - (island.getSchematicClipboard() == null ? - "" + CROSS.getSymbol() : - "" + CHECK_MARK.getSymbol()); + (island.getSchematicClipboard() == null ? + "" + CROSS.getSymbol() : + "" + CHECK_MARK.getSymbol()); final String spawnPointHover = "Spawnpoint: " + - (island.getAbsoluteLocation() == null ? - "" + CROSS.getSymbol() : - "" + - CHECK_MARK.getSymbol()); + (island.getAbsoluteLocation() == null ? + "" + CROSS.getSymbol() : + "" + + CHECK_MARK.getSymbol()); builder.pair("Island-" + island.getSlot(), hover( schematicHover + "\n" + spawnPointHover, island.isReady() ? @@ -321,9 +335,12 @@ public void pluginReload(final CommonBridgePlayer player) { @Subcommand("help") @CommandPermission("speedbridge.help") @Description("Shows a list of commands") - public void onHelpCommand(final CommonBridgePlayer bridgePlayer) { - final CommandSender player = bridgePlayer.getPlayer(); - HelpCommandGenerator.showHelpMessage(player); + public void onHelp(final CommonBridgePlayer bridgePlayer, final ExecutableCommand command) { + CommandCategory parent = command.getParent(); + if (parent == null) { + return; + } + helpMessageProvider.showHelpMessage(parent.getName(), bridgePlayer.getPlayer()); } @Command({"sb randomjoin", "speedbridge randomjoin" ,"randomjoin"}) @@ -331,108 +348,124 @@ public void onHelpCommand(final CommonBridgePlayer bridgePlayer) { @RestrictSetup @RestrictDummyModel @RestrictConsole - public String onRandomJoin(final BridgePlayer bridgePlayer) { - if (!isGeneralSetupComplete(bridgePlayer)) { + @AutoComplete("@players") + @CommandPermission("sb.randomjoin") + public String onRandomJoin( + final BridgePlayer sender, + @OptionalPermission("sb.randomjoin.other") final BridgePlayer target) { + if (!isGeneralSetupComplete(sender)) { return ""; } - if (bridgePlayer.isPlaying()) { + if (sender.isPlaying()) { return INSTANCE.alreadyInAIsland; } - final Optional optionalIsland = getRandomIsland(); + final java.util.Optional optionalIsland = getRandomIsland(); if (!optionalIsland.isPresent()) { return INSTANCE.noAvailableIsland; } final Island island = optionalIsland.get(); - island.join(bridgePlayer); + if (target == null || target.equals(sender)) { + island.join(sender); + return String.format(INSTANCE.joinedAnIsland, island.getSlot()); + } - return String.format(INSTANCE.joinedAnIsland, island.getSlot() + ""); + island.join(target); + return String.format(INSTANCE.otherJoinedAnIsland, target.getName(), island.getSlot()); } @NotNull - private Optional getRandomIsland() { + private java.util.Optional getRandomIsland() { final List filteredIslands = islandService.getAllIslands() .stream() .parallel() .filter(Island::isReady) .collect(Collectors.toList()); - return Optional.ofNullable(filteredIslands.get(ThreadLocalRandom.current().nextInt(filteredIslands.size()))); + if (filteredIslands.isEmpty()) { + return java.util.Optional.empty(); + } + + int randomIndex = ThreadLocalRandom.current().nextInt(filteredIslands.size()); + return java.util.Optional.ofNullable(filteredIslands.get(randomIndex)); } @Subcommand("setup") - @Description("Create an island setup") - @CommandPermission("speedbridge.setup.admin") - @RestrictDummyModel - @RestrictSetup - @RestrictConsole - public String onStartSetup(final BridgePlayer bridgePlayer, final Island island) { - if (!isGeneralSetupComplete(bridgePlayer)) { - return ""; - } - final int slot = island.getSlot(); + class SetupCommand { + @Subcommand("create") + @Description("Create an island setup") + @CommandPermission("speedbridge.setup.admin") + @RestrictDummyModel + @RestrictSetup + @RestrictConsole + public String onStartSetup(final BridgePlayer bridgePlayer, final Island island) { + if (!isGeneralSetupComplete(bridgePlayer)) { + return ""; + } + final int slot = island.getSlot(); + + if (bridgePlayer.isPlaying()) { + return INSTANCE.inAGame; + } else if (island == null) { + return String.format(INSTANCE.invalidIsland, slot); + } - if (bridgePlayer.isPlaying()) { - return INSTANCE.inAGame; - } else if (island == null) { - return String.format(INSTANCE.invalidIsland, slot); + IslandSetupHandler.INSTANCE.initiate(bridgePlayer, island); + return String.format(INSTANCE.startingSetupProcess, slot); } - IslandSetupHandler.INSTANCE.initiate(bridgePlayer, island); - return String.format(INSTANCE.startingSetupProcess, slot); - } + @Subcommand("setspawn") + @Description("Sets the island's spawnpoint") + @CommandPermission("speedbridge.setup.admin") + @RestrictSetup(opposite = true) + @RestrictConsole + public String setupSetSpawn(final BridgePlayer bridgePlayer) { + final IslandSetup islandSetup = IslandSetupHandler.INSTANCE.findSetupBy(bridgePlayer.getPlayerUid()); - @Subcommand("setup setspawn") - @Description("Sets the island's spawnpoint") - @CommandPermission("speedbridge.setup.admin") - @RestrictSetup(opposite = true) - @RestrictConsole - public String setupSetSpawn(final BridgePlayer bridgePlayer) { - final IslandSetup islandSetup = IslandSetupHandler.INSTANCE.findSetupBy(bridgePlayer.getPlayerUid()); + final Location playerLocation = bridgePlayer.getPlayer() + .getLocation(); + + // if the location given was not valid + if (!islandSetup.isLocationValid(playerLocation)) { + return INSTANCE.invalidSpawnPoint; + } - final Location playerLocation = bridgePlayer.getPlayer() - .getLocation(); + // otherwise, set the location point + islandSetup.setPlayerSpawnPoint(playerLocation); - // if the location given was not valid - if (!islandSetup.isLocationValid(playerLocation)) { - return INSTANCE.invalidSpawnPoint; + return INSTANCE.setSpawnPoint + "\n" + INSTANCE.completeNotification; } - // otherwise, set the location point - islandSetup.setPlayerSpawnPoint(playerLocation); - - return INSTANCE.setSpawnPoint + "\n" + INSTANCE.completeNotification; - } + @Subcommand("finish") + @Description("Completes the island's setup") + @CommandPermission("speedbridge.setup.admin") + @RestrictSetup(opposite = true) + @RestrictConsole + public String setupFinish(final BridgePlayer bridgePlayer) { + final IslandSetup islandSetup = IslandSetupHandler.INSTANCE.findSetupBy(bridgePlayer.getPlayerUid()); - @Subcommand("setup finish") - @Description("Completes the island's setup") - @CommandPermission("speedbridge.setup.admin") - @RestrictSetup(opposite = true) - @RestrictConsole - public String setupFinish(final BridgePlayer bridgePlayer) { - final IslandSetup islandSetup = IslandSetupHandler.INSTANCE.findSetupBy(bridgePlayer.getPlayerUid()); + if (!islandSetup.isReady()) { + return INSTANCE.setupIncomplete; + } - if (!islandSetup.isReady()) { - return INSTANCE.setupIncomplete; + islandSetup.finish(); + return INSTANCE.setupComplete; } - islandSetup.finish(); - return INSTANCE.setupComplete; - } - - @Subcommand("setup cancel") - @Description("Cancels the island's setup") - @CommandPermission("speedbridge.setup.admin") - @RestrictSetup(opposite = true) - @RestrictConsole - public String cancelSetup(final BridgePlayer bridgePlayer) { - final IslandSetup islandSetup = IslandSetupHandler.INSTANCE.findSetupBy(bridgePlayer.getPlayerUid()); + @Subcommand("cancel") + @Description("Cancels the island's setup") + @CommandPermission("speedbridge.setup.admin") + @RestrictSetup(opposite = true) + @RestrictConsole + public String cancelSetup(final BridgePlayer bridgePlayer) { + final IslandSetup islandSetup = IslandSetupHandler.INSTANCE.findSetupBy(bridgePlayer.getPlayerUid()); - islandSetup.cancel(); - return INSTANCE.setupCancelled; + islandSetup.cancel(); + return INSTANCE.setupCancelled; + } } private String hover(final String hoverContent, final String content) { @@ -448,4 +481,53 @@ private void onCompletion(final CompletableFuture future, final Consumer< consumer.accept(t); }); } + + @Subcommand("player") + class PlayerSubCommand { + @Subcommand("set block") + @Description("Changes the selected block type for a specified player") + @CommandPermission("speedbridge.player.set.block") + @AutoComplete("* @players") + @Usage(" ") + public String setSelectedBlockType(final @MaterialType(category = MaterialCategory.BLOCK) Material material, final BridgePlayer target) { + if (!material.isSolid()) { + return String.format(INSTANCE.blockTypeMustBeSolid, material); + } + + if (target.getChoseMaterial() == material) { + return String.format(INSTANCE.blockAlreadySelected, target.getName(), material); + } + + target.setChosenMaterial(material); + return String.format(INSTANCE.setChosenType, target.getName(), material); + } + + @Subcommand("reset") + @Usage(" ") + @Description("Resets player properties") + @CommandPermission("speedbridge.player.reset") + @AutoComplete("@players *") + public void onPlayerReset(final CommonBridgePlayer sender, final @PlayerUUID NameAndUUID target, + final ResetType type) { + String targetName = target.playerName(); + UUID targetId = target.playerUUID(); + + onCompletion(playerService.reset(targetId, type), unused -> { + String message = null; + switch (type) { + case ALL: + message = String.format(INSTANCE.playerWiped, targetName); + break; + case SCORES: + message = String.format(INSTANCE.playerScoreReset, targetName); + break; + case STATS: + message = String.format(INSTANCE.playerStatsReset, targetName); + break; + } + if (message == null) return; + BridgeUtil.sendMessage(sender, message); + }); + } + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/DestroyableLand.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/DestroyableLand.java index 79437af0..650290a6 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/DestroyableLand.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/DestroyableLand.java @@ -1,11 +1,9 @@ package io.tofpu.speedbridge2.command.subcommand.debug; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.extent.clipboard.Clipboard; -import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import io.tofpu.multiworldedit.EditSessionWrapper; @@ -26,7 +24,7 @@ public DestroyableLand(IslandLand islandLand) { public void generatePlot() throws WorldEditException { // TODO: Make this generation operation async BridgeUtil.debug("Generating plot at " + getPlotLocation().toString() + " for " + - "island " + getIsland().getSlot()); + "island " + getIsland().getSlot()); final BukkitWorld bukkitWorld = new BukkitWorld(getWorld()); @@ -50,7 +48,7 @@ public void generatePlot() throws WorldEditException { public void destroy() { // TODO: Make this generation operation async BridgeUtil.debug("Generating plot at " + getPlotLocation().toString() + " for " + - "island " + getIsland().getSlot()); + "island " + getIsland().getSlot()); final BukkitWorld bukkitWorld = new BukkitWorld(getWorld()); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/GameIsland2.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/GameIsland2.java index 9c88ca4f..76b821b7 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/GameIsland2.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/GameIsland2.java @@ -11,12 +11,12 @@ public GameIsland2(final ArenaManager arenaManager, GameIsland gameIsland) { super(arenaManager, gameIsland.getIsland(), gameIsland.getGamePlayer()); } - public void setIslandPlot(final IslandLand islandLand) { - this.islandLand = islandLand; - } - @Override public IslandLand getIslandPlot() { return this.islandLand; } + + public void setIslandPlot(final IslandLand islandLand) { + this.islandLand = islandLand; + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/SpeedBridgeDebugCommand.java b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/SpeedBridgeDebugCommand.java index 3c0e128e..9b2c96e6 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/SpeedBridgeDebugCommand.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/command/subcommand/debug/SpeedBridgeDebugCommand.java @@ -5,7 +5,6 @@ import io.tofpu.speedbridge2.model.island.arena.ArenaManager; import io.tofpu.speedbridge2.model.island.object.GameIsland; import io.tofpu.speedbridge2.model.island.object.Island; -import io.tofpu.speedbridge2.model.island.object.land.IslandLand; import io.tofpu.speedbridge2.model.player.object.GamePlayer; import org.bukkit.Location; import org.bukkit.entity.Player; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameInteractionListener.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameInteractionListener.java index 18de023c..a98dbde3 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameInteractionListener.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameInteractionListener.java @@ -1,17 +1,17 @@ package io.tofpu.speedbridge2.listener.game; import io.tofpu.dynamicclass.meta.AutoRegister; +import io.tofpu.speedbridge2.listener.GameListener; +import io.tofpu.speedbridge2.listener.wrapper.wrappers.BlockPlaceEventWrapper; +import io.tofpu.speedbridge2.listener.wrapper.wrappers.PlayerInteractEventWrapper; import io.tofpu.speedbridge2.model.common.Message; import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.island.object.Island; import io.tofpu.speedbridge2.model.island.object.GameIsland; -import io.tofpu.speedbridge2.model.player.object.score.Score; -import io.tofpu.speedbridge2.model.player.object.stat.PlayerStatType; +import io.tofpu.speedbridge2.model.island.object.Island; import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import io.tofpu.speedbridge2.model.player.object.GamePlayer; -import io.tofpu.speedbridge2.listener.GameListener; -import io.tofpu.speedbridge2.listener.wrapper.wrappers.BlockPlaceEventWrapper; -import io.tofpu.speedbridge2.listener.wrapper.wrappers.PlayerInteractEventWrapper; +import io.tofpu.speedbridge2.model.player.object.score.Score; +import io.tofpu.speedbridge2.model.player.object.stat.PlayerStatType; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameProtectionListener.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameProtectionListener.java index c68138a2..0a70b067 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameProtectionListener.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/game/GameProtectionListener.java @@ -1,9 +1,9 @@ package io.tofpu.speedbridge2.listener.game; import io.tofpu.dynamicclass.meta.AutoRegister; -import io.tofpu.speedbridge2.model.player.object.BridgePlayer; -import io.tofpu.speedbridge2.model.player.PlayerService; import io.tofpu.speedbridge2.listener.GameListener; +import io.tofpu.speedbridge2.model.player.PlayerService; +import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageEvent; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/general/PlayerConnectionListener.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/general/PlayerConnectionListener.java index e70dbba8..06a75ce7 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/general/PlayerConnectionListener.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/general/PlayerConnectionListener.java @@ -32,8 +32,9 @@ private void onPlayerJoin(final @NotNull PlayerJoinEvent event) { playerService.loadIfAbsent(player, (bridgePlayer) -> playerService.internalRefresh(player, bridgePlayer)); if (player.isOp()) { - UpdateChecker.get() - .updateNotification(player); + if (UpdateChecker.isInitialized() && ConfigurationManager.INSTANCE.getGeneralCategory().shouldCheckForUpdates()) { + UpdateChecker.get().updateNotification(player); + } } teleportToLobby(player); @@ -44,17 +45,21 @@ private void teleportToLobby(final Player player) { ConfigurationManager.INSTANCE.getLobbyCategory(); final Location location = lobbyCategory.getLobbyLocation(); - // if teleport_on_join is set to true, teleport the player to the lobby location - if (lobbyCategory.isTeleportOnJoin()) { - if (location != null) { - player.teleport(location); - return; + // a lobby is required to utilize speedbridge2 features + if (location == null) { + if (player.isOp()) { + BridgeUtil.sendMessage(player, Message.INSTANCE.lobbyMissing); } + return; + } - BridgeUtil.sendMessage(player, Message.INSTANCE.lobbyMissing); + if (!lobbyCategory.isTeleportOnJoin()) { + return; } - if (location != null && player.getWorld().equals(location.getWorld())) { + player.teleport(location); + + if (lobbyCategory.clearInventoryAfterTeleport() && player.getWorld().equals(location.getWorld())) { // clears the player's inventory. in-case the PlayerQuitEvent missed it. player.getInventory().clear(); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandProtectionListener.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandProtectionListener.java index 2eea23d3..6ff94672 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandProtectionListener.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandProtectionListener.java @@ -1,11 +1,11 @@ package io.tofpu.speedbridge2.listener.island; import io.tofpu.dynamicclass.meta.AutoRegister; -import io.tofpu.speedbridge2.model.island.object.GameIsland; -import io.tofpu.speedbridge2.model.player.object.GamePlayer; import io.tofpu.speedbridge2.listener.GameListener; import io.tofpu.speedbridge2.listener.wrapper.wrappers.BlockBreakEventWrapper; import io.tofpu.speedbridge2.listener.wrapper.wrappers.BlockPlaceEventWrapper; +import io.tofpu.speedbridge2.model.island.object.GameIsland; +import io.tofpu.speedbridge2.model.player.object.GamePlayer; import io.tofpu.speedbridge2.model.support.worldedit.CuboidRegion; import io.tofpu.speedbridge2.model.support.worldedit.Vector; import org.bukkit.Location; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandRegionListener.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandRegionListener.java index 63dc1df3..4a0ea73a 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandRegionListener.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/island/IslandRegionListener.java @@ -1,14 +1,17 @@ package io.tofpu.speedbridge2.listener.island; import io.tofpu.dynamicclass.meta.AutoRegister; +import io.tofpu.speedbridge2.listener.GameListener; import io.tofpu.speedbridge2.model.island.object.GameIsland; import io.tofpu.speedbridge2.model.player.PlayerService; import io.tofpu.speedbridge2.model.player.object.BridgePlayer; -import io.tofpu.speedbridge2.listener.GameListener; import io.tofpu.speedbridge2.model.support.worldedit.CuboidRegion; import io.tofpu.speedbridge2.model.support.worldedit.Vector; import org.bukkit.Location; import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.jetbrains.annotations.NotNull; @@ -20,11 +23,27 @@ public IslandRegionListener(final PlayerService playerService) { this.playerService = playerService; } + @EventHandler + private void onWorldChange(PlayerChangedWorldEvent event) { + final BridgePlayer bridgePlayer = playerService.getIfPresent(event.getPlayer() + .getUniqueId()); + if (bridgePlayer == null || !bridgePlayer.isPlaying()) { + return; + } + + final GameIsland currentGame = bridgePlayer.getCurrentGame(); + if (currentGame == null) { + return; + } + + currentGame.abortGame(); + } + @EventHandler(ignoreCancelled = true) // skipcq: JAVA-W0324 private void onPlayerMove(final @NotNull PlayerMoveEvent event) { final BridgePlayer bridgePlayer = playerService.getIfPresent(event.getPlayer() .getUniqueId()); - if (bridgePlayer == null ||!bridgePlayer.isPlaying()) { + if (bridgePlayer == null || !bridgePlayer.isPlaying()) { return; } @@ -47,4 +66,15 @@ private void onPlayerMove(final @NotNull PlayerMoveEvent event) { currentGame.resetGame(); } } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + private void onCraft(CraftItemEvent event) { + final BridgePlayer bridgePlayer = playerService.getIfPresent(event.getWhoClicked() + .getUniqueId()); + if (bridgePlayer == null || !bridgePlayer.isPlaying()) { + return; + } + + event.setCancelled(true); + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/EventWrapper.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/EventWrapper.java index 66b7bf11..0edaac16 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/EventWrapper.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/EventWrapper.java @@ -13,16 +13,16 @@ public class EventWrapper extends Event { private final @NotNull BridgePlayer bridgePlayer; private final @NotNull E event; - public static HandlerList getHandlerList() { - return handlers; - } - public EventWrapper(final @NotNull BridgePlayer bridgePlayer, - final @NotNull E event) { + final @NotNull E event) { this.bridgePlayer = bridgePlayer; this.event = event; } + public static HandlerList getHandlerList() { + return handlers; + } + public @NotNull E getEvent() { return event; } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/SpeedBridgeListener.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/SpeedBridgeListener.java index 2ee940f5..9ba2f2fb 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/SpeedBridgeListener.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/SpeedBridgeListener.java @@ -55,7 +55,7 @@ private void onPlayerInteract(final @NotNull PlayerInteractEvent event) { final EventWrapper eventWrapper = PlayerInteractEventWrapper.wrap(playerService, event); if (event.getAction() != Action.PHYSICAL || !eventWrapper.isPlaying() || - !eventWrapper.hasTimerStarted()) { + !eventWrapper.hasTimerStarted()) { return; } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockBreakEventWrapper.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockBreakEventWrapper.java index 7a3dd9c0..4ed1ae24 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockBreakEventWrapper.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockBreakEventWrapper.java @@ -1,19 +1,19 @@ package io.tofpu.speedbridge2.listener.wrapper.wrappers; -import io.tofpu.speedbridge2.model.player.PlayerService; import io.tofpu.speedbridge2.listener.wrapper.EventWrapper; +import io.tofpu.speedbridge2.model.player.PlayerService; import org.bukkit.event.block.BlockBreakEvent; import org.jetbrains.annotations.NotNull; public final class BlockBreakEventWrapper extends EventWrapper { - public static BlockBreakEventWrapper wrap(final PlayerService playerService, - final @NotNull BlockBreakEvent event) { - return new BlockBreakEventWrapper(playerService, event); - } - private BlockBreakEventWrapper(final PlayerService playerService, - final @NotNull BlockBreakEvent event) { + final @NotNull BlockBreakEvent event) { super(playerService.getOrDefault(event.getPlayer() .getUniqueId()), event); } + + public static BlockBreakEventWrapper wrap(final PlayerService playerService, + final @NotNull BlockBreakEvent event) { + return new BlockBreakEventWrapper(playerService, event); + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockPlaceEventWrapper.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockPlaceEventWrapper.java index 4c894643..1625a152 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockPlaceEventWrapper.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/BlockPlaceEventWrapper.java @@ -1,19 +1,19 @@ package io.tofpu.speedbridge2.listener.wrapper.wrappers; -import io.tofpu.speedbridge2.model.player.PlayerService; import io.tofpu.speedbridge2.listener.wrapper.EventWrapper; +import io.tofpu.speedbridge2.model.player.PlayerService; import org.bukkit.event.block.BlockPlaceEvent; import org.jetbrains.annotations.NotNull; public final class BlockPlaceEventWrapper extends EventWrapper { - public static BlockPlaceEventWrapper wrap(final PlayerService playerService, - final @NotNull BlockPlaceEvent event) { - return new BlockPlaceEventWrapper(playerService, event); - } - private BlockPlaceEventWrapper(final PlayerService playerService, - final @NotNull BlockPlaceEvent event) { + final @NotNull BlockPlaceEvent event) { super(playerService.getOrDefault(event.getPlayer() .getUniqueId()), event); } + + public static BlockPlaceEventWrapper wrap(final PlayerService playerService, + final @NotNull BlockPlaceEvent event) { + return new BlockPlaceEventWrapper(playerService, event); + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/PlayerInteractEventWrapper.java b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/PlayerInteractEventWrapper.java index 7207d264..612b3b70 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/PlayerInteractEventWrapper.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/listener/wrapper/wrappers/PlayerInteractEventWrapper.java @@ -1,19 +1,19 @@ package io.tofpu.speedbridge2.listener.wrapper.wrappers; -import io.tofpu.speedbridge2.model.player.PlayerService; import io.tofpu.speedbridge2.listener.wrapper.EventWrapper; +import io.tofpu.speedbridge2.model.player.PlayerService; import org.bukkit.event.player.PlayerInteractEvent; import org.jetbrains.annotations.NotNull; public class PlayerInteractEventWrapper extends EventWrapper { - public static PlayerInteractEventWrapper wrap(final PlayerService playerService, - final @NotNull PlayerInteractEvent event) { - return new PlayerInteractEventWrapper(playerService, event); - } - private PlayerInteractEventWrapper(final PlayerService playerService, - final @NotNull PlayerInteractEvent event) { + final @NotNull PlayerInteractEvent event) { super(playerService.getOrDefault(event.getPlayer() .getUniqueId()), event); } + + public static PlayerInteractEventWrapper wrap(final PlayerService playerService, + final @NotNull PlayerInteractEvent event) { + return new PlayerInteractEventWrapper(playerService, event); + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/BlockMenuManager.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/BlockMenuManager.java index f7afa701..fa542f81 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/BlockMenuManager.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/BlockMenuManager.java @@ -26,10 +26,8 @@ import java.util.function.Consumer; public final class BlockMenuManager { - private static final int BLOCK_CHANGE_COOLDOWN = 30; - public static final BlockMenuManager INSTANCE = new BlockMenuManager(); - + private static final int BLOCK_CHANGE_COOLDOWN = 30; private final Set materialSet = new HashSet<>(); private final Cache cooldownMap; @@ -104,8 +102,8 @@ public boolean canSelectItem(final BridgePlayer bridgePlayer, final ItemStack it return false; } return ConfigurationManager.INSTANCE.getBlockMenuCategory() - .getDefaultBlock() == type || bridgePlayer.getPlayer() - .hasPermission("speedbridge.block." + type.name()); + .getDefaultBlock() == type || bridgePlayer.getPlayer() + .hasPermission("speedbridge.block." + type.name()); } private void modifyItem(final ModifyItemType modifyItemType, final ItemStack itemStack) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/holder/BlockMenuHolder.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/holder/BlockMenuHolder.java index 53f532e1..067c152e 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/holder/BlockMenuHolder.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/holder/BlockMenuHolder.java @@ -12,7 +12,8 @@ public final class BlockMenuHolder implements InventoryHolder { private final Inventory inventory = Bukkit.createInventory(this, InventoryType.CHEST, INVENTORY_TITLE); - private BlockMenuHolder() {} + private BlockMenuHolder() { + } @Override public Inventory getInventory() { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/listener/BlockMenuListener.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/listener/BlockMenuListener.java index 4be134c8..d7f7dc98 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/listener/BlockMenuListener.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/blockmenu/listener/BlockMenuListener.java @@ -29,7 +29,7 @@ public BlockMenuListener(final PlayerService playerService) { public void onInventoryClick(final InventoryClickEvent event) { final Inventory clickedInventory = event.getClickedInventory(); if (clickedInventory == null || - (!(clickedInventory.getHolder() instanceof BlockMenuHolder))) { + (!(clickedInventory.getHolder() instanceof BlockMenuHolder))) { return; } event.setCancelled(true); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/Message.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/Message.java index 1ecc9e09..b6a15427 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/Message.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/Message.java @@ -6,39 +6,37 @@ import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; public final class Message { + public static final @NotNull Message INSTANCE; private static final @NotNull Map FIELD_MAP = new ConcurrentHashMap<>(); - private static final String SCORE_TITLE_BAR = MessageUtil.CHAT_BAR.substring(0, MessageUtil.CHAT_BAR.length() / 6); private static final String STYLE = "" + MessageUtil.Symbols.CLOCK.getSymbol() + " "; private static final String SECOND_STYLE = "" + MessageUtil.Symbols.STAR.getSymbol() + " "; - private static final String error = "" + MessageUtil.Symbols.WARNING.getSymbol() + - " "; + " "; private static final String SUCCESS = "" + MessageUtil.Symbols.ARROW_RIGHT.getSymbol() + - " "; + " "; - public static final @NotNull Message INSTANCE = new Message(); + static { + INSTANCE = new Message(); + } public final String noArgument = SUCCESS + "Type " + runCommand("/speedbridge help") + " for further " + - "information."; + "information."; public final String islandAlreadyExists = error + "Island %s already exists!"; public final String islandHasBeenCreatedSchematic = SUCCESS + "Island %s has been created with '%s' chosen as the " + - "schematic!"; + "schematic!"; public final String islandSetupNotification = SUCCESS + "You can complete your %slot% island setup by setting up the spawn point."; public final String validSelect = @@ -46,20 +44,25 @@ public final class Message { public final String unknownSchematic = error + "Schematic \"%s\" cannot be found"; public final String invalidIslandArgument = error + "Invalid argument. Please choose a slot, or an island category" + - ".\n" + error + "Alternatively, you could run the '" + - runCommand("/randomjoin") + "' command."; + ".\n" + error + "Alternatively, you could run the '" + + runCommand("/randomjoin") + "' command."; public final String invalidIsland = error + "Island %s cannot be found!"; public final String noAvailableIsland = error + "There is no island available " + - "at the moment... please try again " + - "later!"; + "at the moment... please try again " + + "later!"; public final String alreadyInAIsland = error + "You're already on an island!"; public final String inAGame = error + "You cannot execute this command while playing"; public final String scoreTitle = "" + SCORE_TITLE_BAR + " YOUR SCORES" + " " + - SCORE_TITLE_BAR; + "> YOUR SCORES" + " " + + SCORE_TITLE_BAR; + public final String otherScoreTitle = "" + SCORE_TITLE_BAR + " %s SCORES" + " " + + SCORE_TITLE_BAR; public final String joinedAnIsland = SUCCESS + "You're now on island %s!"; + public final String otherJoinedAnIsland = SUCCESS + "Player %s is now on island %s!"; public final String leftAnIsland = SUCCESS + "You left from island" + " %s!"; public final String notInAIsland = error + "You're not on an island!"; + public final String otherNotInAIsland = error + "Player % is not on an island!"; public final String deletedAnIsland = SUCCESS + "Island %s has been deleted!"; public final String emptySelect = error + "You haven't modified anything..."; public final String reloaded = SUCCESS + "The config has been reloaded!"; @@ -68,62 +71,54 @@ public final class Message { public final String timeStarted = STYLE + "The timer is now ticking!"; public final String scored = SECOND_STYLE + "You scored %s " + "seconds!"; - public final String lobbyMissing = error + "Incomplete setup. Please ensure to set up SpeedBridge's lobby to " + - "complete the " + "process." + "\nType " + - runCommand("/speedbridge setlobby") + " to set the " + "lobby."; - + "complete the " + "process." + "\nType " + + runCommand("/speedbridge setlobby") + " to set the " + "lobby."; public final String generalSetupIncomplete = error + "Incomplete setup. Please try again " + "later."; - public final String startingSetupProcess = SUCCESS + "You're now setting up %s " + "island."; - public final String notInASetup = error + "You're not setting up anything."; public final String setSpawnPoint = SUCCESS + "You have set the island's " + "spawnpoint."; - public final String completeNotification = SUCCESS + "You can complete the setup " + "by typing " + - runCommand("/sb setup finish"); - + runCommand("/sb setup finish"); public final String setupIncomplete = error + "The setup is incomplete. Please " + - "ensure that the spawn point is set."; + "ensure that the spawn point is set."; public final String setupComplete = SUCCESS + "The setup is now complete."; - public final String emptyScoreFormat = ""; - public final String invalidSpawnPoint = error + "The spawn point has to be set inside the regions."; - public final String setupCancelled = SUCCESS + "The setup has been cancelled."; - public final String playerDoesntExist = error + "%s does not exist."; - public final String playerWiped = SUCCESS + "%s's data has been reset."; public final String playerScoreReset = SUCCESS + "%s's scores has been reset."; public final String playerStatsReset = SUCCESS + "%s's stats has been reset."; - public final String somethingWentWrong = error + "Something went wrong... check " + "your console"; public final String inASetup = error + "You're already in a setup."; public final String notLoaded = error + "Your data has not been loaded yet. Please " + "try again later!"; - public final String islandReset = error.replace("red", "yellow") + "The island has " + "been " + "reset!"; - public final String blockChangeCooldown = error + "You can't do that yet! Please wait " + - "for %s seconds."; - + "for %s seconds."; public final String invalidUuid = error + "%s is not a valid uuid format. Please try again"; + public final String mustBeOnline = error + "%s must be available to modify their data"; + public final String setChosenType = SUCCESS + "Changed %s's selected block type to %s"; + public final String blockTypeMustBeSolid = error + "%s must be a solid block to be selectable!"; + public final String invalidMaterial = error + "Invalid material: %s"; + public final String blockAlreadySelected = error + "Player %s has already selected material %s!"; + public final String otherIsAlreadyInAIsland = error + "Player % is already in an island"; + public final String otherLeftTheIsland = error + "Player % left from island %s!"; private static String runCommand(final String command) { return "Click to run " + - "%command%'>%command%".replace( - "%command" + "%", command); + "%command%'>%command%".replace( + "%command" + "%", command); } public static @NotNull CompletableFuture load(final File directory) { @@ -131,7 +126,7 @@ private static String runCommand(final String command) { if (FIELD_MAP.isEmpty()) { for (final Field field : Message.class.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers()) || - field.isAnnotationPresent(IgnoreMessage.class)) { + field.isAnnotationPresent(IgnoreMessage.class)) { continue; } @@ -141,13 +136,13 @@ private static String runCommand(final String command) { FIELD_MAP.put(field.getName(), field); } - BridgeUtil.debug(String.valueOf(FIELD_MAP)); + BridgeUtil.debug("messages_field_map=" + FIELD_MAP); } final File messageFile = new File(directory, "messages.yml"); final boolean messageFileExists = messageFile.exists(); - BridgeUtil.debug(String.valueOf(FIELD_MAP)); + BridgeUtil.debug("messages_field_map=" + FIELD_MAP); if (!messageFileExists) { FileUtil.write(messageFile, false, ReflectionUtil.toString(FIELD_MAP)); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PlayerNameCache.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PlayerNameCache.java index 0ce2c209..5fe72184 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PlayerNameCache.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PlayerNameCache.java @@ -13,6 +13,23 @@ public final class PlayerNameCache { private final Map nameMap = new HashMap<>(); + private static String getPlayerName(final UUID uuid) { + final AtomicReference result = new AtomicReference<>(""); + try (final DatabaseQuery databaseQuery = DatabaseQuery.query("SELECT * FROM " + + "players " + "where uid = ?")) { + databaseQuery.setString(uuid.toString()); + + databaseQuery.executeQuery(databaseSet -> { + if (databaseSet.next()) { + result.set(databaseSet.getString("name")); + } + }); + } catch (Exception e) { + throw new IllegalStateException(e); + } + return result.get(); + } + /** * This method caches the player's name * @@ -27,7 +44,6 @@ public void insert(final UUID uuid, final String name) { * Retrieves the player's name synchronously * * @param uid player unique identification - * * @return the player name immediately if cached, otherwise it'll retrieve the name * from the "players" table database in sync */ @@ -39,7 +55,6 @@ public String getOrDefault(final UUID uid) { * Retrieves the player's name asynchronously * * @param uid player unique identification - * * @return the player name immediately if cached, otherwise it'll retrieve the name * from the "players" table database in async */ @@ -58,21 +73,4 @@ public CompletableFuture getOrDefaultAsync(final UUID uid) { return future; } - - private static String getPlayerName(final UUID uuid) { - final AtomicReference result = new AtomicReference<>(""); - try (final DatabaseQuery databaseQuery = DatabaseQuery.query("SELECT * FROM " + - "players " + "where uid = ?")) { - databaseQuery.setString(uuid.toString()); - - databaseQuery.executeQuery(databaseSet -> { - if (databaseSet.next()) { - result.set(databaseSet.getString("name")); - } - }); - } catch (Exception e) { - throw new IllegalStateException(e); - } - return result.get(); - } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PluginExecutor.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PluginExecutor.java index e4697c27..416e4276 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PluginExecutor.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/PluginExecutor.java @@ -2,11 +2,19 @@ import org.jetbrains.annotations.NotNull; -import java.util.concurrent.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.function.Supplier; public final class PluginExecutor implements Executor { public static final @NotNull PluginExecutor INSTANCE = new PluginExecutor(); + private final @NotNull ExecutorService executor; + + public PluginExecutor() { + this.executor = Executors.newFixedThreadPool(4); + } public static @NotNull CompletableFuture runAsync(final Runnable runnable) { return (CompletableFuture) INSTANCE.submit(runnable); @@ -16,12 +24,6 @@ public final class PluginExecutor implements Executor { return (CompletableFuture) INSTANCE.supplyAsync(supplier); } - private final @NotNull ExecutorService executor; - - public PluginExecutor() { - this.executor = Executors.newFixedThreadPool(4); - } - @Override public void execute(final @NotNull Runnable command) { executor.execute(command); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/PluginConfiguration.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/PluginConfiguration.java index 4d63d5e7..ad417522 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/PluginConfiguration.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/PluginConfiguration.java @@ -1,6 +1,9 @@ package io.tofpu.speedbridge2.model.common.config; -import io.tofpu.speedbridge2.model.common.config.category.*; +import io.tofpu.speedbridge2.model.common.config.category.BlockMenuCategory; +import io.tofpu.speedbridge2.model.common.config.category.GeneralCategory; +import io.tofpu.speedbridge2.model.common.config.category.LeaderboardCategory; +import io.tofpu.speedbridge2.model.common.config.category.LobbyCategory; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Setting; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/BlockMenuCategory.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/BlockMenuCategory.java index ac6d04d7..ba9cb586 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/BlockMenuCategory.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/BlockMenuCategory.java @@ -5,7 +5,10 @@ import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Setting; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; @ConfigSerializable public final class BlockMenuCategory { @@ -13,12 +16,16 @@ public final class BlockMenuCategory { @Setting("blocks") private List materials = new ArrayList<>(Arrays.asList(toMaterial(XMaterial.WHITE_WOOL), - Material.DIAMOND_BLOCK, Material.GOLD_BLOCK, Material.IRON_BLOCK, - Material.REDSTONE_BLOCK, Material.LAPIS_BLOCK, Material.QUARTZ_BLOCK)); + Material.DIAMOND_BLOCK, Material.GOLD_BLOCK, Material.IRON_BLOCK, + Material.REDSTONE_BLOCK, Material.LAPIS_BLOCK, Material.QUARTZ_BLOCK)); @Setting("default_block") private Material defaultBlock = materials.isEmpty() ? Material.AIR : materials.get(0); + public static Material toMaterial(final XMaterial xMaterial) { + return xMaterial.parseMaterial(); + } + public Collection getMaterialBlocks() { return materials.subList(0, Math.min(7, materials.size())); } @@ -26,8 +33,4 @@ public Collection getMaterialBlocks() { public Material getDefaultBlock() { return defaultBlock; } - - public static Material toMaterial(final XMaterial xMaterial) { - return xMaterial.parseMaterial(); - } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/GeneralCategory.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/GeneralCategory.java index 929f1b64..fee20f66 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/GeneralCategory.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/GeneralCategory.java @@ -9,25 +9,31 @@ public final class GeneralCategory { @Setting("show-debug-message") @Comment("Useful when debugging") private boolean showDebugMessage = false; + @Setting("default-island-category") + @Comment("This will set the default island category when they're not provided upon " + + "creation") + private String defaultIslandCategory = "standard"; + @Setting("island-space-gap") + @Comment("The space gap between islands") + private int islandSpaceGap = 10; + + @Setting("check-for-updates") + @Comment("Checks for an available update on startup. (default: true)") + private boolean checkForUpdates = true; public boolean isDebugEnabled() { return showDebugMessage; } - @Setting("default-island-category") - @Comment("This will set the default island category when they're not provided upon " + - "creation") - private String defaultIslandCategory = "standard"; - public String getDefaultIslandCategory() { return defaultIslandCategory; } - @Setting("island-space-gap") - @Comment("The space gap between islands") - private int islandSpaceGap = 10; - public int getIslandSpaceGap() { return islandSpaceGap; } + + public boolean shouldCheckForUpdates() { + return checkForUpdates; + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LeaderboardCategory.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LeaderboardCategory.java index b3f599ff..ce8b3c90 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LeaderboardCategory.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LeaderboardCategory.java @@ -13,7 +13,7 @@ public final class LeaderboardCategory { @Setting("session-update-interval") @Comment("A session leaderboard will update on every x interval. It's defined in " + - "seconds.") + "seconds.") private int sessionUpdateInterval = 10; @Setting("leaderboard-format") diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LobbyCategory.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LobbyCategory.java index 77520d99..ee740c78 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LobbyCategory.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/category/LobbyCategory.java @@ -8,31 +8,39 @@ import java.util.concurrent.CompletableFuture; +@SuppressWarnings("FieldCanBeLocal") @ConfigSerializable public final class LobbyCategory { @Setting("teleport-on-join") @Comment("If this is set to true, the players will teleport to the lobby upon them " + - "joining") + "joining") private boolean teleportOnJoin = true; - public boolean isTeleportOnJoin() { - return teleportOnJoin; - } - @Setting("lobby-location") @Comment("This is where the players will teleport when they join, or leave an " + - "island") + "island") private Location lobbyLocation = null; - public CompletableFuture setLobbyLocation(final Location lobbyLocation) { - this.lobbyLocation = lobbyLocation; - return ConfigurationManager.INSTANCE.update(); + @Comment("If this is set to true, the player's inventory will be cleared after teleporting to the lobby upon joining") + private boolean clearInventoryAfterTeleport = true; + + public boolean isTeleportOnJoin() { + return teleportOnJoin; } public void setTeleportOnJoin(final boolean teleportOnJoin) { this.teleportOnJoin = teleportOnJoin; } + public boolean clearInventoryAfterTeleport() { + return clearInventoryAfterTeleport; + } + + public CompletableFuture setLobbyLocation(final Location lobbyLocation) { + this.lobbyLocation = lobbyLocation; + return ConfigurationManager.INSTANCE.update(); + } + public Location getLobbyLocation() { return lobbyLocation; } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/AbstractItemActionSerializer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/AbstractItemActionSerializer.java index de61a0cd..95034f27 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/AbstractItemActionSerializer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/AbstractItemActionSerializer.java @@ -20,8 +20,7 @@ public AbstractItemAction deserialize(final Type type, final ConfigurationNode n } @Override - public void serialize(final Type type, @Nullable - final AbstractItemAction obj, final ConfigurationNode node) throws SerializationException { + public void serialize(final Type type, @Nullable final AbstractItemAction obj, final ConfigurationNode node) throws SerializationException { if (!(obj instanceof RunCommandItemAction)) { return; } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemMetaSerializer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemMetaSerializer.java index 9ae026a7..36c61187 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemMetaSerializer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemMetaSerializer.java @@ -39,8 +39,7 @@ public ItemMeta deserialize(final Type type, final ConfigurationNode node) throw } @Override - public void serialize(final Type type, @Nullable - final ItemMeta obj, final ConfigurationNode node) throws SerializationException { + public void serialize(final Type type, @Nullable final ItemMeta obj, final ConfigurationNode node) throws SerializationException { if (obj == null) { node.raw(); return; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemStackSerializer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemStackSerializer.java index 9fabf706..3b80ad76 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemStackSerializer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/ItemStackSerializer.java @@ -26,8 +26,7 @@ public ItemStack deserialize(final Type type, final ConfigurationNode node) thro } @Override - public void serialize(final Type type, @Nullable - final ItemStack obj, final ConfigurationNode node) throws SerializationException { + public void serialize(final Type type, @Nullable final ItemStack obj, final ConfigurationNode node) throws SerializationException { node.node("material").set(obj.getType()); node.node("durability").set(obj.getDurability()); node.node("meta").set(obj.getItemMeta()); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/LocationSerializer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/LocationSerializer.java index 85e00985..38e68ba5 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/LocationSerializer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/LocationSerializer.java @@ -16,7 +16,8 @@ public final class LocationSerializer implements TypeSerializer { public static final LocationSerializer INSTANCE = new LocationSerializer(); - private LocationSerializer() {} + private LocationSerializer() { + } @Override public Location deserialize(final Type type, final ConfigurationNode node) throws SerializationException { @@ -62,7 +63,7 @@ private World getWorld(final String worldName) { private ConfigurationNode nonVirtualNode(final ConfigurationNode source, final Object... path) throws SerializationException { if (!source.hasChild(path)) { throw new SerializationException("Required field " + Arrays.toString(path) + - " was not present in node"); + " was not present in node"); } return source.node(path); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/MaterialSerializer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/MaterialSerializer.java index 3125ad1f..f07b4acf 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/MaterialSerializer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/MaterialSerializer.java @@ -22,8 +22,7 @@ public Material deserialize(final Type type, final ConfigurationNode node) throw } @Override - public void serialize(final Type type, @Nullable - final Material obj, final ConfigurationNode node) throws SerializationException { + public void serialize(final Type type, @Nullable final Material obj, final ConfigurationNode node) throws SerializationException { if (obj == null) { node.set(Material.AIR.name()); return; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/UmbrellaItemSerializer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/UmbrellaItemSerializer.java index 52da5912..c379eac4 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/UmbrellaItemSerializer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/config/serializer/UmbrellaItemSerializer.java @@ -31,8 +31,7 @@ public SerializableUmbrellaItem deserialize(final Type type, final Configuration } @Override - public void serialize(final Type type, @Nullable - final SerializableUmbrellaItem obj, final ConfigurationNode node) throws SerializationException { + public void serialize(final Type type, @Nullable final SerializableUmbrellaItem obj, final ConfigurationNode node) throws SerializationException { final ItemStack itemStack = obj.getItemStack(); node.node("index").set(obj.getIndex()); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseQuery.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseQuery.java index 4428952c..d1ead1f5 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseQuery.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseQuery.java @@ -14,10 +14,6 @@ public class DatabaseQuery implements AutoCloseable { private final @Nullable PreparedStatement preparedStatement; private final @NotNull AtomicInteger setterCounter; - public static DatabaseQuery query(final @NotNull String query) { - return new DatabaseQuery(query); - } - private DatabaseQuery(final @NotNull String query) { try { this.preparedStatement = @@ -28,6 +24,10 @@ private DatabaseQuery(final @NotNull String query) { this.setterCounter = new AtomicInteger(0); } + public static DatabaseQuery query(final @NotNull String query) { + return new DatabaseQuery(query); + } + public @NotNull DatabaseQuery setInt(final Integer integer) { try { this.preparedStatement.setInt(setterCounter.incrementAndGet(), integer); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseTable.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseTable.java index f21a6c84..cab1bd96 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseTable.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/database/wrapper/DatabaseTable.java @@ -9,11 +9,6 @@ public class DatabaseTable { private final String[] columns; private final String sql; - public static DatabaseTable of(final @NotNull String table, - final @NotNull String... columns) { - return new DatabaseTable(table, columns); - } - private DatabaseTable(final @NotNull String table, final @NotNull String... columns) { this.table = table; this.columns = columns; @@ -22,6 +17,11 @@ private DatabaseTable(final @NotNull String table, final @NotNull String... colu BridgeUtil.debug(sql); } + public static DatabaseTable of(final @NotNull String table, + final @NotNull String... columns) { + return new DatabaseTable(table, columns); + } + public @NotNull String formatColumns(final String[] columns) { final StringBuilder formattedColumn = new StringBuilder(); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterBase.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterBase.java index 4c9d7834..9b0928c7 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterBase.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterBase.java @@ -7,6 +7,7 @@ public abstract class MessagePresenterBase { public abstract static class Builder { public abstract Builder append(final String message); + public abstract MessagePresenterBase build(); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolder.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolder.java index 6ad02618..db188a2a 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolder.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolder.java @@ -4,5 +4,6 @@ public interface MessagePresenterHolder { MessagePresenterHolderImpl append(final Supplier presenter); + String getResult(); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolderImpl.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolderImpl.java index 666dda94..8d2fd47c 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolderImpl.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/MessagePresenterHolderImpl.java @@ -4,7 +4,7 @@ public final class MessagePresenterHolderImpl implements MessagePresenterHolder { private static final String HEADER_FORMAT = "| <-> " + - "%s "; + "%s "; private final StringBuilder builder; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/type/MessageTreePresenter.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/type/MessageTreePresenter.java index e00982f8..796a228c 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/type/MessageTreePresenter.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/presenter/type/MessageTreePresenter.java @@ -52,8 +52,8 @@ public String getResult() { } public static class Builder { - private String title; private final List messages = new ArrayList<>(); + private String title; public Builder title(final String title) { this.title = title; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/BridgeUtil.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/BridgeUtil.java index 02dc9787..b6566ee3 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/BridgeUtil.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/BridgeUtil.java @@ -6,9 +6,11 @@ import io.tofpu.speedbridge2.model.common.database.wrapper.DatabaseQuery; import io.tofpu.speedbridge2.model.common.database.wrapper.DatabaseSet; import io.tofpu.speedbridge2.model.leaderboard.object.BoardPlayer; +import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import io.tofpu.speedbridge2.model.player.object.CommonBridgePlayer; import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.plugin.SpeedBridgePlugin; +import me.clip.placeholderapi.PlaceholderAPI; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.platform.bukkit.BukkitComponentSerializer; import net.kyori.adventure.text.Component; @@ -16,6 +18,7 @@ import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.UUID; @@ -82,12 +85,12 @@ public static Component translateMiniMessage(final String content) { * Send a message to a * command sender * - * @param sender The CommandSender who is sending the message. + * @param sender The CommandSender who is sending the message. * @param component The component to send. * @return The component that was sent. */ public static Component sendMessage(final CommandSender sender, - final Component component) { + final Component component) { final Audience audience = SpeedBridge.getAdventure() .sender(sender); audience.sendMessage(component); @@ -97,34 +100,37 @@ public static Component sendMessage(final CommandSender sender, /** * This function sends a message to a player * - * @param sender The player who sent the message. + * @param sender The player who sent the message. * @param content The message to send. * @return Nothing. */ public static Component sendMessage(final CommonBridgePlayer sender, - final String content) { + final String content) { if (content.isEmpty()) { return null; } - final Component component = translateMiniMessage(content); - sendMessage(sender.getPlayer(), component); - return component; + return sendMessage(sender.getPlayer(), content); } /** * Send a message to a * command sender * - * @param sender The CommandSender who will receive the message. + * @param sender The CommandSender who will receive the message. * @param content The content of the message. * @return Nothing. */ - public static Component sendMessage(final CommandSender sender, - final String content) { + public static Component sendMessage(final CommandSender sender, String content) { if (content.isEmpty()) { return null; } + + if (sender instanceof Player) { + content = replaceWithPAPI((Player) sender, content); + } + final Component component = translateMiniMessage(content); + sendMessage(sender, component); return component; } @@ -154,12 +160,21 @@ public static String translate(final String replace) { return ChatColor.translateAlternateColorCodes('&', replace); } + public static String replaceWithPAPI(Player player, String text) { + if (player == null) { + return text; + } + if (!Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { + return text; + } + return PlaceholderAPI.setBracketPlaceholders(player.getPlayer(), text); + } + /** * Given a row or column, and a database set, return a BoardPlayer * - * @param row boolean + * @param row boolean * @param databaseSet The database set that is being converted to a BoardPlayer. - * * @return A BoardPlayer object. */ public static BoardPlayer toBoardPlayer(final boolean row, final DatabaseSet databaseSet) { @@ -192,8 +207,8 @@ public static BoardPlayer toBoardPlayer(final boolean row, final DatabaseSet dat public static UUID findUUIDBy(final String playerName) { final AtomicReference uuid = new AtomicReference<>(); try (final DatabaseQuery databaseQuery = DatabaseQuery.query("SELECT uid FROM " + - "players WHERE name " + - "= ?")) { + "players WHERE name " + + "= ?")) { databaseQuery.setString(playerName); databaseQuery.executeQuery(databaseSet -> { @@ -224,22 +239,22 @@ public static void runBukkitAsync(final Runnable runnable) { * This function will run a task asynchronously * * @param runnable The Runnable to run. - * @param delay The delay is the amount of time to wait before the first execution. + * @param delay The delay is the amount of time to wait before the first execution. * @param interval How often the task should run. */ public static void runBukkitAsync(final Runnable runnable, final long delay, - final long interval) { + final long interval) { Bukkit.getScheduler().runTaskTimerAsynchronously(JavaPlugin.getPlugin(SpeedBridgePlugin.class), runnable, delay, interval); } /** * It runs the given Runnable when the CompletableFuture is completed. * - * @param completableFuture The completable future to be completed. + * @param completableFuture The completable future to be completed. * @param whenCompleteConsumer The consumer to be run when the completable future is completed. */ public static CompletableFuture whenComplete(final CompletableFuture completableFuture, - final Consumer whenCompleteConsumer) { + final Consumer whenCompleteConsumer) { return completableFuture.whenComplete((o, throwable) -> { if (throwable != null) { throw new IllegalStateException(throwable); @@ -252,11 +267,11 @@ public static CompletableFuture whenComplete(final CompletableFuture c * It runs the given Runnable when the CompletableFuture is completed. * * @param completableFuture The completable future to be completed. - * @param whenComplete The runnable to be run when the completable future is - * completed. + * @param whenComplete The runnable to be run when the completable future is + * completed. */ public static void whenComplete(final CompletableFuture completableFuture, - final Runnable whenComplete) { + final Runnable whenComplete) { completableFuture.whenComplete((o, throwable) -> { if (throwable != null) { throw new IllegalStateException(throwable); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/DatabaseUtil.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/DatabaseUtil.java index 482f0fe1..79155005 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/DatabaseUtil.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/DatabaseUtil.java @@ -14,7 +14,7 @@ public class DatabaseUtil { * executes the query and returns a CompletableFuture that will be completed when the * query is done * - * @param sql The SQL statement to execute. + * @param sql The SQL statement to execute. * @param databaseQueryConsumer A Consumer that takes a DatabaseQuery. * @return Nothing. */ @@ -42,12 +42,12 @@ public static CompletableFuture runAsync(final Runnable runnable) { /** * It takes a SQL query and a consumer that will be called for each row of the query * - * @param sql The SQL statement to execute. + * @param sql The SQL statement to execute. * @param databaseQueryConsumer A consumer that will be called for each row of the query. * @return Nothing. */ public static CompletableFuture databaseQueryExecute(final String sql, - final Consumer databaseQueryConsumer) { + final Consumer databaseQueryConsumer) { return runAsync(() -> { try (final DatabaseQuery query = DatabaseQuery.query(sql)) { query.executeQuery(databaseQueryConsumer); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/FileUtil.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/FileUtil.java index 69203f2b..65ff194b 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/FileUtil.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/FileUtil.java @@ -10,9 +10,9 @@ public final class FileUtil { /** * Write a collection of strings to a file * - * @param file The file to write to. - * @param append If true, the file will be appended to if it already exists. If false, - * the file will be overwritten if it already exists. + * @param file The file to write to. + * @param append If true, the file will be appended to if it already exists. If false, + * the file will be overwritten if it already exists. * @param stringCollection The collection of strings to write to the file. */ public static void write(final File file, final boolean append, final Collection stringCollection) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/IgnoreMessage.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/IgnoreMessage.java index c915d5f1..fcbf6e17 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/IgnoreMessage.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/IgnoreMessage.java @@ -7,4 +7,5 @@ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) -public @interface IgnoreMessage {} +public @interface IgnoreMessage { +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UmbrellaUtil.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UmbrellaUtil.java index 9e7c4eb1..c63a3291 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UmbrellaUtil.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UmbrellaUtil.java @@ -15,7 +15,7 @@ public class UmbrellaUtil { public static ItemStack create(final XMaterial material, final String displayName, - final String lore) { + final String lore) { final ItemStack itemStack = material.parseItem(); final ItemMeta meta = itemStack.getItemMeta(); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UpdateChecker.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UpdateChecker.java index 1b877c94..5c01a4b8 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UpdateChecker.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/util/UpdateChecker.java @@ -33,7 +33,12 @@ */ public final class UpdateChecker { - /** The default version scheme for this update checker */ + private static final String USER_AGENT = "CHOCO-update-checker"; + private static final String UPDATE_URL = "https://api.spigotmc.org/simple/0.1/index.php?action=getResource&id=%d"; + private static final Pattern DECIMAL_SCHEME_PATTERN = Pattern.compile("\\d+(?:\\.\\d+)*"); + /** + * The default version scheme for this update checker + */ public static final VersionScheme VERSION_SCHEME_DECIMAL = (first, second) -> { String[] firstSplit = splitVersionInfo(first), secondSplit = splitVersionInfo(second); if (firstSplit == null || secondSplit == null) { @@ -52,23 +57,16 @@ public final class UpdateChecker { return (secondSplit.length > firstSplit.length) ? second : first; }; - - private static final String USER_AGENT = "CHOCO-update-checker"; - private static final String UPDATE_URL = "https://api.spigotmc.org/simple/0.1/index.php?action=getResource&id=%d"; - private static final Pattern DECIMAL_SCHEME_PATTERN = Pattern.compile("\\d+(?:\\.\\d+)*"); - private static final String[] UPDATE_MESSAGE = { "You're using an outdated version of SpeedBridge!", "You can download the latest version at https://www.spigotmc.org/resources/.100619/" }; private static UpdateChecker instance; - - private UpdateResult lastResult = null; - private final JavaPlugin plugin; private final int pluginID; private final VersionScheme versionScheme; + private UpdateResult lastResult = null; private UpdateChecker(@NotNull JavaPlugin plugin, int pluginID, @NotNull VersionScheme versionScheme) { this.plugin = plugin; @@ -76,6 +74,70 @@ private UpdateChecker(@NotNull JavaPlugin plugin, int pluginID, @NotNull Version this.versionScheme = versionScheme; } + private static String[] splitVersionInfo(String version) { + Matcher matcher = DECIMAL_SCHEME_PATTERN.matcher(version); + return matcher.find() ? matcher.group().split("\\.") : null; + } + + /** + * Initialize this update checker with the specified values and return its instance. + * If an instance of UpdateChecker has already been initialized, this method will act + * similarly to {@link #get()} (which is recommended after initialization). + * + * @param plugin the plugin for which to check updates. Cannot be null + * @param pluginID the ID of the plugin as identified in the SpigotMC resource link. + * For example, "https://www.spigotmc.org/resources/veinminer.12038/" would + * expect "12038" as a value. The value must be greater than 0 + * @param versionScheme a custom version scheme parser. Cannot be null + * @return the UpdateChecker instance + */ + @NotNull + public static UpdateChecker init(@NotNull JavaPlugin plugin, int pluginID, @NotNull VersionScheme versionScheme) { + Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); + Preconditions.checkArgument(pluginID > 0, "Plugin ID must be greater than 0"); + Preconditions.checkArgument(versionScheme != null, "null version schemes are unsupported"); + + return (instance == null) ? instance = new UpdateChecker(plugin, pluginID, versionScheme) : instance; + } + + /** + * Initialize this update checker with the specified values and return its instance. + * If an instance of UpdateChecker has already been initialized, this method will act + * similarly to {@link #get()} (which is recommended after initialization). + * + * @param plugin the plugin for which to check updates. Cannot be null + * @param pluginID the ID of the plugin as identified in the SpigotMC resource link. + * For example, "https://www.spigotmc.org/resources/veinminer.12038/" would + * expect "12038" as a value. The value must be greater than 0 + * @return the UpdateChecker instance + */ + @NotNull + public static UpdateChecker init(@NotNull JavaPlugin plugin, int pluginID) { + return init(plugin, pluginID, VERSION_SCHEME_DECIMAL); + } + + /** + * Get the initialized instance of UpdateChecker. If {@link #init(JavaPlugin, int)} + * has not yet been invoked, this method will throw an exception. + * + * @return the UpdateChecker instance + */ + @NotNull + public static UpdateChecker get() { + Preconditions.checkState(instance != null, "Instance has not yet been initialized. Be sure #init() has been invoked"); + return instance; + } + + /** + * Check whether the UpdateChecker has been initialized or not (if + * {@link #init(JavaPlugin, int)} has been invoked) and {@link #get()} is safe to use. + * + * @return true if initialized, false otherwise + */ + public static boolean isInitialized() { + return instance != null; + } + public void updateNotification(final Player player) { final UpdateResult lastResult = getLastResult(); if (lastResult == null) { @@ -124,11 +186,9 @@ public void updateNotification(final Player player) { if (latest == null) { return new UpdateResult(UpdateReason.UNSUPPORTED_VERSION_SCHEME); - } - else if (latest.equals(pluginVersion)) { + } else if (latest.equals(pluginVersion)) { return new UpdateResult(pluginVersion.equals(currentVersion) ? UpdateReason.UP_TO_DATE : UpdateReason.UNRELEASED_VERSION); - } - else if (latest.equals(currentVersion)) { + } else if (latest.equals(currentVersion)) { return new UpdateResult(UpdateReason.NEW_UPDATE, latest); } } catch (IOException e) { @@ -151,93 +211,6 @@ public UpdateResult getLastResult() { return lastResult; } - private static String[] splitVersionInfo(String version) { - Matcher matcher = DECIMAL_SCHEME_PATTERN.matcher(version); - return matcher.find() ? matcher.group().split("\\.") : null; - } - - /** - * Initialize this update checker with the specified values and return its instance. - * If an instance of UpdateChecker has already been initialized, this method will act - * similarly to {@link #get()} (which is recommended after initialization). - * - * @param plugin the plugin for which to check updates. Cannot be null - * @param pluginID the ID of the plugin as identified in the SpigotMC resource link. - * For example, "https://www.spigotmc.org/resources/veinminer.12038/" would - * expect "12038" as a value. The value must be greater than 0 - * @param versionScheme a custom version scheme parser. Cannot be null - * - * @return the UpdateChecker instance - */ - @NotNull - public static UpdateChecker init(@NotNull JavaPlugin plugin, int pluginID, @NotNull VersionScheme versionScheme) { - Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); - Preconditions.checkArgument(pluginID > 0, "Plugin ID must be greater than 0"); - Preconditions.checkArgument(versionScheme != null, "null version schemes are unsupported"); - - return (instance == null) ? instance = new UpdateChecker(plugin, pluginID, versionScheme) : instance; - } - - /** - * Initialize this update checker with the specified values and return its instance. - * If an instance of UpdateChecker has already been initialized, this method will act - * similarly to {@link #get()} (which is recommended after initialization). - * - * @param plugin the plugin for which to check updates. Cannot be null - * @param pluginID the ID of the plugin as identified in the SpigotMC resource link. - * For example, "https://www.spigotmc.org/resources/veinminer.12038/" would - * expect "12038" as a value. The value must be greater than 0 - * - * @return the UpdateChecker instance - */ - @NotNull - public static UpdateChecker init(@NotNull JavaPlugin plugin, int pluginID) { - return init(plugin, pluginID, VERSION_SCHEME_DECIMAL); - } - - /** - * Get the initialized instance of UpdateChecker. If {@link #init(JavaPlugin, int)} - * has not yet been invoked, this method will throw an exception. - * - * @return the UpdateChecker instance - */ - @NotNull - public static UpdateChecker get() { - Preconditions.checkState(instance != null, "Instance has not yet been initialized. Be sure #init() has been invoked"); - return instance; - } - - /** - * Check whether the UpdateChecker has been initialized or not (if - * {@link #init(JavaPlugin, int)} has been invoked) and {@link #get()} is safe to use. - * - * @return true if initialized, false otherwise - */ - public static boolean isInitialized() { - return instance != null; - } - - - /** - * A functional interface to compare two version Strings with similar version schemes. - */ - @FunctionalInterface - public static interface VersionScheme { - - /** - * Compare two versions and return the higher of the two. If null is returned, it - * is assumed that at least one of the two versions are unsupported by this - * version scheme parser. - * - * @param first the first version to check - * @param second the second version to check - * - * @return the greater of the two versions. null if unsupported version schemes - */ - @Nullable - public String compareVersions(@NotNull String first, @NotNull String second); - - } /** * A constant reason for the result of {@link UpdateResult}. @@ -289,6 +262,26 @@ public static enum UpdateReason { } + /** + * A functional interface to compare two version Strings with similar version schemes. + */ + @FunctionalInterface + public static interface VersionScheme { + + /** + * Compare two versions and return the higher of the two. If null is returned, it + * is assumed that at least one of the two versions are unsupported by this + * version scheme parser. + * + * @param first the first version to check + * @param second the second version to check + * @return the greater of the two versions. null if unsupported version schemes + */ + @Nullable + public String compareVersions(@NotNull String first, @NotNull String second); + + } + /** * Represents a result for an update query performed by * {@link UpdateChecker#requestUpdateCheck()}. diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/wrapper/ConfigurateFile.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/wrapper/ConfigurateFile.java index 61bf887a..f4d1b482 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/common/wrapper/ConfigurateFile.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/common/wrapper/ConfigurateFile.java @@ -73,7 +73,7 @@ public void load(final Class bindTo, final FileConfigurationType type) { } catch (ConfigurateException e) { plugin.getLogger() .warning("An error occurred while loading this configuration:" + " " + - e.getMessage()); + e.getMessage()); if (e.getCause() != null) { e.printStackTrace(); } @@ -85,7 +85,7 @@ public void load(final Class bindTo, final FileConfigurationType type) { } catch (SerializationException e) { plugin.getLogger() .warning("An error occurred while converting MyConfiguration: " + - e.getMessage()); + e.getMessage()); if (e.getCause() != null) { e.printStackTrace(); } @@ -103,7 +103,7 @@ public CompletableFuture reload() { } catch (ConfigurateException e) { plugin.getLogger() .warning("An error occurred while converting MyConfiguration: " + - e.getMessage()); + e.getMessage()); if (e.getCause() != null) { e.printStackTrace(); } @@ -115,7 +115,7 @@ public void save() { if (this.node == null) { plugin.getLogger() .warning("Configuration cannot be saved due to the node " + - "being null"); + "being null"); return; } try { @@ -123,7 +123,7 @@ public void save() { } catch (ConfigurateException e) { plugin.getLogger() .warning("An error occurred while saving this configuration: " + - e.getMessage()); + e.getMessage()); if (e.getCause() != null) { e.printStackTrace(); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandDatabase.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandDatabase.java index 856f4c4f..19d9ffc9 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandDatabase.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandDatabase.java @@ -25,7 +25,7 @@ public IslandDatabase() { public @NotNull CompletableFuture insert(final Island island) { return DatabaseUtil.databaseExecute("INSERT OR IGNORE INTO islands VALUES " + - "(?, ?, ?, ?)", databaseQuery -> { + "(?, ?, ?, ?)", databaseQuery -> { databaseQuery.setInt(island.getSlot()); databaseQuery.setString(island.getCategory()); databaseQuery.setString(island.getSchematicName()); @@ -36,7 +36,7 @@ public IslandDatabase() { public @NotNull CompletableFuture update(final Island island) { return DatabaseUtil.databaseExecute( "UPDATE islands SET category = ?, schematic_name = " + - "?, spawn_point = ? WHERE slot = ?", databaseQuery -> { + "?, spawn_point = ? WHERE slot = ?", databaseQuery -> { BridgeUtil.debug("island category: " + island.getCategory()); databaseQuery.setString(island.getCategory()); @@ -78,7 +78,8 @@ public IslandDatabase() { } islands.add(builder.build()); - }}).get(); + } + }).get(); } catch (InterruptedException | ExecutionException e) { throw new IslandLoadFailureException(e); } @@ -93,7 +94,7 @@ private String serialize(final Location location) { } return location.getX() + ":" + location.getY() + ":" + - location.getZ() + ":" + location.getYaw() + ":" + location.getPitch(); + location.getZ() + ":" + location.getYaw() + ":" + location.getPitch(); } private Location deserialize(final String input) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandHandler.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandHandler.java index e04023c8..3d73eedc 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandHandler.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandHandler.java @@ -4,8 +4,8 @@ import io.tofpu.speedbridge2.model.common.util.BridgeUtil; import io.tofpu.speedbridge2.model.island.arena.ArenaManager; import io.tofpu.speedbridge2.model.island.object.Island; -import io.tofpu.speedbridge2.model.leaderboard.IslandBoard; import io.tofpu.speedbridge2.model.island.object.IslandBuild; +import io.tofpu.speedbridge2.model.leaderboard.IslandBoard; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -37,13 +37,13 @@ public void load(final @NotNull Map loadedIslands) { /** * Creates an island * - * @param slot The island's slot. - * @param category The category of the island. + * @param slot The island's slot. + * @param category The category of the island. * @param schematic The name of the schematic to load. It cannot be null nor empty. * @return The {@link IslandHandler.IslandCreationResult} enum. */ public @NotNull IslandHandler.IslandCreationResult createIsland(final int slot, - final @NotNull String category, final @NotNull String schematic) { + final @NotNull String category, final @NotNull String schematic) { // if the island does exist, return ALREADY_EXISTS! if (islandMap.containsKey(slot)) { return IslandCreationResultType.ISLAND_ALREADY_EXISTS.empty(); @@ -133,7 +133,6 @@ public void load(final @NotNull Map loadedIslands) { /** * @param island The island to register. - * * @return The registration result. */ public IslandRegistrationResultType registerIsland(Island island) { @@ -179,7 +178,7 @@ public IslandCreationResult empty() { } public IslandCreationResult create(final Island - island) { + island) { return new IslandCreationResult(this, island); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandService.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandService.java index a04bb954..ebf6299f 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandService.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/IslandService.java @@ -11,7 +11,7 @@ import java.util.concurrent.CompletableFuture; public final class IslandService { -// public static final @NotNull IslandService INSTANCE = new IslandService(); + // public static final @NotNull IslandService INSTANCE = new IslandService(); private final @NotNull IslandHandler islandHandler; private final @NotNull IslandRepository islandRepository; @@ -34,14 +34,14 @@ public CompletableFuture> loadAsync() { /** * Creates an island * - * @param slot The island's slot. - * @param category The category of the island. + * @param slot The island's slot. + * @param category The category of the island. * @param schematic The name of the schematic to load. It cannot be null nor empty. * @return The {@link IslandHandler.IslandCreationResult} enum. */ public @NotNull IslandHandler.IslandCreationResult createIsland(final int slot, - final @NotNull String category, - final @NotNull String schematic) { + final @NotNull String category, + final @NotNull String schematic) { return this.islandHandler.createIsland(slot, category, schematic); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/arena/ArenaManager.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/arena/ArenaManager.java index 7013355f..bc7abbba 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/arena/ArenaManager.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/arena/ArenaManager.java @@ -3,8 +3,8 @@ import com.sk89q.worldedit.WorldEditException; import io.tofpu.speedbridge2.model.common.config.manager.ConfigurationManager; import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.island.object.Island; import io.tofpu.speedbridge2.model.island.object.GameIsland; +import io.tofpu.speedbridge2.model.island.object.Island; import io.tofpu.speedbridge2.model.island.object.land.IslandLand; import io.tofpu.speedbridge2.model.support.worldedit.Vector; import org.apache.commons.io.FileUtils; @@ -30,10 +30,15 @@ public final class ArenaManager { private File worldDirectory; private World world; + @NotNull + private static String serializeVector(Vector vector) { + return String.format("%s, %s, %s", vector.getX(), vector.getY(), vector.getZ()); + } + public void load() { this.world = Bukkit.createWorld(WorldCreator.name("speedbridge2") .generator(new EmptyChunkGenerator())); - this.worldDirectory = new File( "speedbridge2"); + this.worldDirectory = new File("speedbridge2"); protectWorld(world); } @@ -105,8 +110,12 @@ private IslandLand getPlot(final Island island, final GameIsland gameIsland) { return islandLand; } +// private IslandLand getNewPlot(final Island target) { +// return getNewPlot(target, getPositions()); +// } + private IslandLand getAvailablePlot(final Collection islandLands, - final int slot) { + final int slot) { for (final IslandLand islandLand : islandLands) { // if it's not the same island plot, or the plot is not free; continue if (islandLand.getIsland().getSlot() != slot || !islandLand.isFree()) { @@ -119,10 +128,6 @@ private IslandLand getAvailablePlot(final Collection islandLands, return null; } -// private IslandLand getNewPlot(final Island target) { -// return getNewPlot(target, getPositions()); -// } - private IslandLand getNewPlot(final Island target, double[] positions) { return new IslandLand(target, world, positions); } @@ -199,11 +204,6 @@ public double[] getPositions() { return new double[]{COUNTER.get(), 100, 100}; } - @NotNull - private static String serializeVector(Vector vector) { - return String.format("%s, %s, %s", vector.getX(), vector.getY(), vector.getZ()); - } - public void resetWorld() { final File worldFile = getWorldDirectory(); if (worldFile != null && worldFile.exists()) { @@ -261,7 +261,6 @@ public World getWorld() { } - private static final class EmptyChunkGenerator extends ChunkGenerator { @Override public @NotNull ChunkData generateChunkData(final World world, final Random random, final int x, final int z, final BiomeGrid biome) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/exception/IslandDatabaseExceptionWrapper.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/exception/IslandDatabaseExceptionWrapper.java index 10469263..66babf8f 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/exception/IslandDatabaseExceptionWrapper.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/exception/IslandDatabaseExceptionWrapper.java @@ -2,7 +2,7 @@ public class IslandDatabaseExceptionWrapper extends RuntimeException { public IslandDatabaseExceptionWrapper(final String message, final int slot, - final Throwable e) { + final Throwable e) { super(message + (slot == -1 ? "" : ": " + slot), e); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/EmptyIsland.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/EmptyIsland.java deleted file mode 100644 index 9c10c750..00000000 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/EmptyIsland.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.tofpu.speedbridge2.model.island.object; - -import io.tofpu.speedbridge2.model.common.Message; -import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.player.object.BridgePlayer; -import io.tofpu.speedbridge2.model.player.object.GamePlayer; -import org.jetbrains.annotations.NotNull; - -import java.util.AbstractMap; -import java.util.Map; - -public class EmptyIsland extends Island { - public EmptyIsland() { - super(null, null, -1, "null"); - } - - @Override - public Map.Entry join(final BridgePlayer player) { - return new AbstractMap.SimpleImmutableEntry<>(null, null); - } - - @Override - public void leaveGame(final BridgePlayer bridgePlayer) { - BridgeUtil.sendMessage(bridgePlayer.getPlayer(), - Message.INSTANCE.notInAIsland); - } - - @Override - public GameIsland findGameByPlayer(final GamePlayer gamePlayer) { - return null; - } - - @Override - public void delete() { - // does nothing - } - - @Override - public void setCategory(final String anotherCategory) { - // does nothing - } - - @Override - public boolean selectSchematic(final @NotNull String schematicName) { - return false; - } -} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/GameIsland.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/GameIsland.java index 0aa88406..7bda235f 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/GameIsland.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/GameIsland.java @@ -4,11 +4,11 @@ import io.tofpu.speedbridge2.model.common.config.category.LobbyCategory; import io.tofpu.speedbridge2.model.common.config.manager.ConfigurationManager; import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.island.object.umbrella.GameIslandUmbrella; -import io.tofpu.speedbridge2.model.island.object.land.IslandLand; import io.tofpu.speedbridge2.model.island.arena.ArenaManager; -import io.tofpu.speedbridge2.model.player.object.stat.PlayerStatType; +import io.tofpu.speedbridge2.model.island.object.land.IslandLand; +import io.tofpu.speedbridge2.model.island.object.umbrella.GameIslandUmbrella; import io.tofpu.speedbridge2.model.player.object.GamePlayer; +import io.tofpu.speedbridge2.model.player.object.stat.PlayerStatType; import io.tofpu.speedbridge2.model.support.worldedit.CuboidRegion; import io.tofpu.umbrella.domain.Umbrella; import org.bukkit.GameMode; @@ -25,7 +25,7 @@ public class GameIsland { private IslandLand islandLand; public GameIsland(final ArenaManager arenaManager, final Island island, - final GamePlayer gamePlayer) { + final GamePlayer gamePlayer) { this.arenaManager = arenaManager; // todo: memory leak, as this does not get invalidated once done this.umbrella = new GameIslandUmbrella(this).getUmbrella(); @@ -147,7 +147,11 @@ public IslandLand getIslandPlot() { return islandLand; } - public void stopGame() { - getIsland().leaveGame(getGamePlayer().getBridgePlayer()); + public boolean stopGame() { + return getIsland().leaveGame(getGamePlayer().getBridgePlayer()); + } + + public void abortGame() { + getIsland().abortGame(getGamePlayer().getBridgePlayer()); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/Island.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/Island.java index 3f857deb..1c9ede46 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/Island.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/Island.java @@ -35,14 +35,13 @@ public class Island { private final int slot; private final Map islandMap; - private String category; - private final LeaderboardMap leaderboardMap; private final IslandSchematic islandSchematic; + private String category; private Location absoluteLocation; public Island(final IslandService islandService, final ArenaManager arenaManager, - final int slot, final String category) { + final int slot, final String category) { this.islandService = islandService; this.arenaManager = arenaManager; this.slot = slot; @@ -55,8 +54,8 @@ public Island(final IslandService islandService, final ArenaManager arenaManager } public Island(final IslandService islandService, final ArenaManager arenaManager, - final int slot, final String category, final String schematic, - final Location absoluteLocation) { + final int slot, final String category, final String schematic, + final Location absoluteLocation) { this.islandService = islandService; this.arenaManager = arenaManager; this.slot = slot; @@ -100,25 +99,29 @@ public Map.Entry join(final BridgePlayer player) { return new AbstractMap.SimpleImmutableEntry<>(gamePlayer, gameIsland); } + public boolean leaveGame(final BridgePlayer bridgePlayer) { + return leaveGame(bridgePlayer, true); + } + /** * When a player leaves the island, the island is removed from the island map and the * game player is removed from the game player map * * @param bridgePlayer The bridge player that is leaving the game island. */ - public void leaveGame(final BridgePlayer bridgePlayer) { + public boolean leaveGame(final BridgePlayer bridgePlayer, final boolean clearInventory) { final GamePlayer gamePlayer = bridgePlayer.getGamePlayer(); if (gamePlayer == null) { - return; + return false; } final GameIsland gameIsland = this.islandMap.remove(gamePlayer); if (gameIsland == null) { - return; + return false; } final Player player = bridgePlayer.getPlayer(); - if (player != null) { + if (player != null && clearInventory) { player.getInventory() .clear(); } @@ -128,6 +131,11 @@ public void leaveGame(final BridgePlayer bridgePlayer) { // reset the game island gameIsland.remove(); + return true; + } + + public void abortGame(BridgePlayer bridgePlayer) { + leaveGame(bridgePlayer, false); } /** @@ -140,16 +148,6 @@ public GameIsland findGameByPlayer(final GamePlayer gamePlayer) { return this.islandMap.get(gamePlayer); } - /** - * It sets the category of the question. - * - * @param anotherCategory The new category to set. - */ - public void setCategory(final String anotherCategory) { - this.category = anotherCategory; - update(); - } - /** * Selects a schematic from the list of available schematics * @@ -166,22 +164,22 @@ public boolean selectSchematic(final @NotNull String schematicName) { } /** - * This function sets the absolute location of the object + * Returns the absolute location of the object * - * @param newAbsoluteLocation The new location to set the object to. + * @return The absolute location of the object. */ - public void setAbsoluteLocation(final Location newAbsoluteLocation) { - this.absoluteLocation = newAbsoluteLocation; - update(); + public Location getAbsoluteLocation() { + return this.absoluteLocation; } /** - * Returns the absolute location of the object + * This function sets the absolute location of the object * - * @return The absolute location of the object. + * @param newAbsoluteLocation The new location to set the object to. */ - public Location getAbsoluteLocation() { - return this.absoluteLocation; + public void setAbsoluteLocation(final Location newAbsoluteLocation) { + this.absoluteLocation = newAbsoluteLocation; + update(); } /** @@ -191,7 +189,7 @@ public Location getAbsoluteLocation() { */ public boolean isReady() { return islandSchematic.getSchematicClipboard() != null && - absoluteLocation != null; + absoluteLocation != null; } /** @@ -215,6 +213,16 @@ public String getCategory() { return category; } + /** + * It sets the category of the question. + * + * @param anotherCategory The new category to set. + */ + public void setCategory(final String anotherCategory) { + this.category = anotherCategory; + update(); + } + /** * Load the leaderboard map with the given map * @@ -228,7 +236,7 @@ public void loadBoard(final Map boardMap) { * Add a score to the leaderboard for the given player * * @param bridgePlayer The bridge player to add the score to. - * @param score The score to add. + * @param score The score to add. */ public void addLeaderboardScore(final BridgePlayer bridgePlayer, final Score score) { leaderboardMap.append(bridgePlayer, score); @@ -360,9 +368,9 @@ public IslandSchematic(final Island island, final String schematic) { public boolean selectSchematic(final @NotNull String schematicName) { BridgeUtil.debug( "Loading schematic '" + schematicName + "' for " + island.getSlot() + - "..."); + "..."); BridgeUtil.debug("IslandSchematic#selectSchematic(): WorldEdit Directory: " + - schematicDirectory); + schematicDirectory); final File file = findSchematicFile(schematicDirectory, schematicName); if (file != null && file.exists()) { @@ -371,7 +379,7 @@ public boolean selectSchematic(final @NotNull String schematicName) { BridgeUtil.debug( "IslandSchematic#selectSchematic(): Successfully loaded schematic: " + - schematicName); + schematicName); this.schematicName = schematicName; return true; @@ -379,7 +387,7 @@ public boolean selectSchematic(final @NotNull String schematicName) { BridgeUtil.debug( "IslandSchematic#selectSchematic(): Failed to load schematic: " + - schematicName); + schematicName); return false; } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuild.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuild.java index c698999a..764ef168 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuild.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuild.java @@ -5,8 +5,8 @@ public class IslandBuild extends Island { public IslandBuild(final IslandService islandService, - final ArenaManager arenaManager, final int slot, - final String category) { + final ArenaManager arenaManager, final int slot, + final String category) { super(islandService, arenaManager, slot, category); } @@ -33,7 +33,7 @@ protected void update() { public Island toRegularIsland() { final Island island = new Island(islandService, super.arenaManager, this.getSlot(), - this.getCategory()); + this.getCategory()); island.selectSchematic(getSchematicName()); island.setAbsoluteLocation(getAbsoluteLocation()); return island; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuilder.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuilder.java index 2dace5fb..c5fc7506 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuilder.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/IslandBuilder.java @@ -10,14 +10,14 @@ public class IslandBuilder { private String schematic; private Location absoluteLocation; - public static IslandBuilder of() { - return new IslandBuilder(); - } - private IslandBuilder() { // prevent instantiation } + public static IslandBuilder of() { + return new IslandBuilder(); + } + public IslandBuilder setSlot(final int slot) { this.slot = slot; return this; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/land/IslandLand.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/land/IslandLand.java index 221de308..c62677ad 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/land/IslandLand.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/land/IslandLand.java @@ -6,14 +6,10 @@ import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; -import io.tofpu.multiworldedit.ClipboardWrapper; -import io.tofpu.multiworldedit.EditSessionWrapper; -import io.tofpu.multiworldedit.MultiWorldEditAPI; -import io.tofpu.multiworldedit.RegionWrapper; -import io.tofpu.multiworldedit.VectorWrapper; +import io.tofpu.multiworldedit.*; import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.island.object.Island; import io.tofpu.speedbridge2.model.island.object.GameIsland; +import io.tofpu.speedbridge2.model.island.object.Island; import io.tofpu.speedbridge2.model.support.worldedit.CuboidRegion; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; @@ -70,7 +66,7 @@ public IslandLand(final Island island, final World world, double[] positions) { public void generatePlot() throws WorldEditException { // TODO: Make this generation operation async BridgeUtil.debug("Generating plot at " + this.location.toString() + " for " + - "island " + this.island.getSlot()); + "island " + this.island.getSlot()); final BukkitWorld bukkitWorld = new BukkitWorld(world); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetup.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetup.java index 7e0d4b23..dac5910a 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetup.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetup.java @@ -152,7 +152,7 @@ private void resetPlot() { * Returns true if the player is not removed and has a player spawn point * * @return A boolean value. - */ + */ public boolean isReady() { return !isRemoved() && playerSpawnPoint != null; } @@ -195,7 +195,7 @@ private void resetState() { * Returns the UUID of the player that is currently editing the island * * @return The UUID of the player that is currently editing the island. - */ + */ public UUID getPlayerUid() { return player.getPlayerUid(); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupFactory.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupFactory.java index c47b6add..ce42ad14 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupFactory.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupFactory.java @@ -15,8 +15,8 @@ public static void init(final IslandService islandService) { } public static IslandSetup create(final IslandSetupFactoryType type, - final Umbrella umbrella, - final BridgePlayer player + final Umbrella umbrella, + final BridgePlayer player , final Island island, final IslandLand islandLand) { Preconditions.checkNotNull(islandService, "IslandService is not initialized"); Preconditions.checkNotNull(umbrella, "Umbrella cannot be null"); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupHandler.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupHandler.java index fff2c732..66b69dff 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupHandler.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/island/object/setup/IslandSetupHandler.java @@ -18,13 +18,12 @@ public final class IslandSetupHandler { private final Umbrella umbrella; private final Map islandSetupMap = new HashMap<>(); + private World world; private IslandSetupHandler() { this.umbrella = new IslandSetupUmbrella().getUmbrella(); } - private World world; - /** * This function is called when the plugin is loaded */ @@ -73,12 +72,12 @@ public IslandSetup findSetupBy(final UUID uuid) { return islandSetupMap.get(uuid); } - /** - * Remove the given island setup from the island setup map - * - * @param islandSetup The island setup that is being invalidated. - */ - public void invalidate(final IslandSetup islandSetup) { + /** + * Remove the given island setup from the island setup map + * + * @param islandSetup The island setup that is being invalidated. + */ + public void invalidate(final IslandSetup islandSetup) { islandSetupMap.remove(islandSetup.getPlayerUid()); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/IslandBoard.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/IslandBoard.java index 173eb01e..d7fe8481 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/IslandBoard.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/IslandBoard.java @@ -8,7 +8,10 @@ import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; -import java.util.*; +import java.util.HashMap; +import java.util.Map; +import java.util.Queue; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; @@ -32,17 +35,17 @@ public static CompletableFuture loadAsync(final JavaPlugin javaPlugin) { Bukkit.getScheduler() .runTaskAsynchronously(javaPlugin, () -> { BridgeUtil.debug("IslandBoard#load(): loading the island's " + - "leaderboard"); + "leaderboard"); for (final Island island : ISLAND_QUEUE) { BridgeUtil.debug("IslandBoard#load(): Loading " + island.getSlot() + " leaderboard " + - "now!"); + "now!"); final Map boardMap = new HashMap<>(); try (final DatabaseQuery databaseQuery = DatabaseQuery.query( "SELECT * FROM scores WHERE island_slot = ? ORDER BY" + - " " + - "score " + "LIMIT 10 OFFSET 0")) { + " " + + "score " + "LIMIT 10 OFFSET 0")) { databaseQuery.setInt(island.getSlot()); final Map boardPlayerMap = @@ -66,7 +69,7 @@ public static CompletableFuture loadAsync(final JavaPlugin javaPlugin) { }); BridgeUtil.debug("IslandBoard#load(): Successfully loaded " + island.getSlot() + - " island leaderboard!"); + " island leaderboard!"); BridgeUtil.debug(String.valueOf(boardMap)); island.loadBoard(boardMap); } catch (Exception e) { @@ -79,7 +82,7 @@ public static CompletableFuture loadAsync(final JavaPlugin javaPlugin) { Bukkit.getScheduler() .runTaskTimerAsynchronously(javaPlugin, () -> { BridgeUtil.debug("IslandBoard#load(): Starting the leaderboard " + - "update process!"); + "update process!"); for (final Island island : ISLAND_QUEUE) { BridgeUtil.debug("IslandBoard#load(): Updating " + island.getSlot() + " now!"); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/LeaderboardMap.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/LeaderboardMap.java index 0f97a969..28a5e4e9 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/LeaderboardMap.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/LeaderboardMap.java @@ -2,8 +2,8 @@ import io.tofpu.speedbridge2.model.common.PlayerNameCache; import io.tofpu.speedbridge2.model.leaderboard.object.BoardPlayer; -import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.model.player.object.BridgePlayer; +import io.tofpu.speedbridge2.model.player.object.score.Score; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; @@ -85,7 +85,7 @@ public void updateLeaderboard() { * Otherwise, insert the player's best score to the temp board * * @param bridgePlayer The player who's score is being appended to the board. - * @param score the score that the player has achieved. + * @param score the score that the player has achieved. */ public void append(final BridgePlayer bridgePlayer, final Score score) { final Score previousScore = globalReference.get(bridgePlayer.getPlayerUid()); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/BoardLoader.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/BoardLoader.java index a498660a..7b5041fd 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/BoardLoader.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/BoardLoader.java @@ -8,6 +8,7 @@ public interface BoardLoader { T retrieve(final @NotNull UUID uniqueId); + CompletableFuture retrieveAsync(final @NotNull UUID uniqueId, - final @NotNull Executor executor); + final @NotNull Executor executor); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/IslandLoader.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/IslandLoader.java index 55799def..661d5eb0 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/IslandLoader.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/IslandLoader.java @@ -36,7 +36,7 @@ public IslandBoardPlayer retrieve(final @NotNull UUID uniqueId) { @Override public @NotNull CompletableFuture retrieveAsync(final @NotNull UUID key, - final @NotNull Executor executor) { + final @NotNull Executor executor) { BridgeUtil.debug("IslandLoader#retrieveAsync: retrieving " + key); return CompletableFuture.supplyAsync(() -> retrieve(key), executor); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/PlayerPositionLoader.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/PlayerPositionLoader.java index bcee23fd..a66abe04 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/PlayerPositionLoader.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/loader/PlayerPositionLoader.java @@ -8,8 +8,8 @@ import io.tofpu.speedbridge2.model.common.util.BridgeUtil; import io.tofpu.speedbridge2.model.leaderboard.object.BoardPlayer; import io.tofpu.speedbridge2.model.player.PlayerService; -import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.model.player.object.BridgePlayer; +import io.tofpu.speedbridge2.model.player.object.score.Score; import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -22,7 +22,7 @@ public final class PlayerPositionLoader implements CacheLoader, BoardLoader { private static final String GLOBAL_POSITION = "SELECT DISTINCT 1 + COUNT(*) AS " + - "position FROM scores WHERE score < (SELECT score FROM scores WHERE uid = ?)"; + "position FROM scores WHERE score < (SELECT score FROM scores WHERE uid = ?)"; private final PlayerService playerService; @@ -61,7 +61,7 @@ public BoardPlayer retrieve(final @NotNull UUID uniqueId) { @Override public @NotNull CompletableFuture retrieveAsync(final @NotNull UUID key, - final @NotNull Executor executor) { + final @NotNull Executor executor) { return CompletableFuture.supplyAsync(() -> { BridgeUtil.debug("PersonalBoardLoader#retrieve(): key: " + key); try (final DatabaseQuery databaseQuery = DatabaseQuery.query(GLOBAL_POSITION)) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/object/IslandBoardPlayer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/object/IslandBoardPlayer.java index 7253f628..31349e78 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/object/IslandBoardPlayer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/leaderboard/object/IslandBoardPlayer.java @@ -16,8 +16,8 @@ public final class IslandBoardPlayer { private static final String ISLAND_POSITION = "SELECT 1 + COUNT(*) AS position FROM scores WHERE island_slot = ? AND " + - "score" + - " < " + "(SELECT score " + "FROM scores WHERE uid = ?)"; + "score" + + " < " + "(SELECT score " + "FROM scores WHERE uid = ?)"; private final PlayerService playerService; @@ -36,7 +36,7 @@ public IslandBoardPlayer(final PlayerService playerService, final UUID owner) { public @NotNull CompletableFuture retrieve(final int islandSlot) { BridgeUtil.debug("IslandBoardPlayer#retrieve(): Attempting to retrieve board " + - "for " + owner + ", " + islandSlot); + "for " + owner + ", " + islandSlot); final IslandBoard cachedValue = boardMap.get(islandSlot); // if the cached value is not null @@ -47,8 +47,8 @@ public IslandBoardPlayer(final PlayerService playerService, final UUID owner) { } BridgeUtil.debug("IslandBoardPlayer#retrieve(): Attempting to query to database" + - " for position for " + owner + - ", " + islandSlot); + " for position for " + owner + + ", " + islandSlot); try (final DatabaseQuery databaseQuery = DatabaseQuery.query(ISLAND_POSITION)) { databaseQuery.setInt(islandSlot); databaseQuery.setString(owner.toString()); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerDatabase.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerDatabase.java index e35fadd5..80a51bfe 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerDatabase.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerDatabase.java @@ -11,9 +11,9 @@ import io.tofpu.speedbridge2.model.player.exception.PlayerDeletionFailureException; import io.tofpu.speedbridge2.model.player.exception.PlayerLoadFailureException; import io.tofpu.speedbridge2.model.player.exception.PlayerUpdateNameFailureException; +import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.model.player.object.stat.PlayerStat; -import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; @@ -37,7 +37,7 @@ public PlayerDatabase() { completableFutures[0] = DatabaseUtil.databaseExecute( "INSERT OR IGNORE " + "INTO players VALUES (?, " + - "?)", databaseQuery -> { + "?)", databaseQuery -> { databaseQuery.setString(player.getPlayerUid() .toString()); databaseQuery.setString(player.getPlayer() diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerFactory.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerFactory.java index 430f5ba9..a4ceea80 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerFactory.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerFactory.java @@ -35,7 +35,7 @@ public static BridgePlayer createDummy(final UUID uuid) { } public static BridgePlayer create(final PlayerFactoryType type, final String name, - final UUID uuid) { + final UUID uuid) { Preconditions.checkNotNull(name, "name cannot be null"); Preconditions.checkNotNull(uuid, "uuid cannot be null"); @@ -50,7 +50,7 @@ public static BridgePlayer create(final PlayerFactoryType type, final String nam } public static BridgePlayer create(final PlayerFactoryType type, - final UUID uuid) { + final UUID uuid) { Preconditions.checkNotNull(uuid, "uuid cannot be null"); switch (type) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerHandler.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerHandler.java index e623240c..59e05bc1 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerHandler.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerHandler.java @@ -77,11 +77,11 @@ public void remove(final UUID uniqueId) { * If the player is in the * database, update the name and refresh the player instance * - * @param name The name of the player. + * @param name The name of the player. * @param uniqueId The unique ID of the player. */ public void internalRefresh(final String name, - final UUID uniqueId) { + final UUID uniqueId) { final BridgePlayer bridgePlayer = getIfPresent(uniqueId); if (bridgePlayer == null) { loadAsync(uniqueId); @@ -99,11 +99,11 @@ public void internalRefresh(final String name, * If the player is online, update the name if it has changed and refresh the * player instance * - * @param player The live instance of the player. + * @param player The live instance of the player. * @param bridgePlayer The bridge player instance that is being refreshed. */ public void internalRefresh(final @NotNull Player player, - final @NotNull BridgePlayer bridgePlayer) { + final @NotNull BridgePlayer bridgePlayer) { final String name = player.getName(); if (!bridgePlayer.getName() .equals(name)) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerService.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerService.java index 61ac0786..41f013be 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerService.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/PlayerService.java @@ -71,11 +71,11 @@ public void internalRefresh(final @NotNull Player player) { * If the player is online, update the name if it has changed and refresh the * player instance * - * @param player The live instance of the player. + * @param player The live instance of the player. * @param bridgePlayer The bridge player instance that is being refreshed. */ public void internalRefresh(final @NotNull Player player, - final @NotNull BridgePlayer bridgePlayer) { + final @NotNull BridgePlayer bridgePlayer) { playerHandler.internalRefresh(player, bridgePlayer); } @@ -118,7 +118,7 @@ public void shutdown() { } public void loadIfAbsent(final Player player, - final Consumer notAbsentConsumer) { + final Consumer notAbsentConsumer) { playerHandler.loadIfAbsent(player.getUniqueId(), notAbsentConsumer); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/exception/PlayerDatabaseExceptionWrapper.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/exception/PlayerDatabaseExceptionWrapper.java index 9d03f692..62611007 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/exception/PlayerDatabaseExceptionWrapper.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/exception/PlayerDatabaseExceptionWrapper.java @@ -4,7 +4,7 @@ public class PlayerDatabaseExceptionWrapper extends RuntimeException { public PlayerDatabaseExceptionWrapper(final String message, final UUID uniqueId, - final Throwable e) { + final Throwable e) { super(message + ": " + uniqueId.toString(), e); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/loader/PlayerLoader.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/loader/PlayerLoader.java index 395c4ec4..a012811d 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/loader/PlayerLoader.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/loader/PlayerLoader.java @@ -42,7 +42,7 @@ public BridgePlayer retrieve(final @NotNull UUID uniqueId) { try { BridgeUtil.debug("PlayerLoader#retrieve: Attempting to load " + uniqueId + - " player data!"); + " player data!"); bridgePlayer = retrieveAsync(uniqueId, PluginExecutor.INSTANCE).get(); } catch (InterruptedException | ExecutionException e) { @@ -56,17 +56,16 @@ public BridgePlayer retrieve(final @NotNull UUID uniqueId) { @Override public CompletableFuture retrieveAsync(final @NotNull UUID uniqueId, - final @NotNull Executor executor) { + final @NotNull Executor executor) { BridgeUtil.debug("attempting to load " + uniqueId + " player's data!"); return Databases.PLAYER_DATABASE.getStoredPlayer(uniqueId); } public static final class PlayerRemovalListener implements Expiry { + public static final PlayerRemovalListener INSTANCE = new PlayerRemovalListener(); private static final long EXPIRY_DURATION = TimeUnit.MINUTES.toNanos(5); private static final long INFINITE_DURATION = Long.MAX_VALUE; - public static final PlayerRemovalListener INSTANCE = new PlayerRemovalListener(); - private PlayerRemovalListener() { // prevent instantiation } @@ -78,11 +77,11 @@ public long expireAfterCreate(final UUID key, final BridgePlayer value, final lo @Override public long expireAfterUpdate(final UUID key, final BridgePlayer value, final long currentTime, - @NonNegative final long currentDuration) { + @NonNegative final long currentDuration) { final long elapse = Duration.ofNanos(currentDuration) .getSeconds(); BridgeUtil.debug("PlayerRemovalListener#expireAfterUpdate: Start: current " + - "duration is " + elapse + " seconds!"); + "duration is " + elapse + " seconds!"); if (value.getPlayer() == null) { BridgeUtil.debug("PlayerRemovalListener#expireAfterUpdate: Expiring " + key + " player data after " + elapse + " seconds!"); @@ -95,7 +94,7 @@ public long expireAfterUpdate(final UUID key, final BridgePlayer value, final lo @Override public long expireAfterRead(final UUID key, final BridgePlayer value, final long currentTime, - @NonNegative final long currentDuration) { + @NonNegative final long currentDuration) { final long elapse = Duration.ofNanos(currentDuration) .getSeconds(); BridgeUtil.debug("PlayerRemovalListener#expireAfterRead: Expiring " + key + " player data after " + elapse + " seconds!"); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/BridgePlayer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/BridgePlayer.java index 5b3d6d1e..916cac10 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/BridgePlayer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/BridgePlayer.java @@ -19,12 +19,7 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; +import java.util.*; import java.util.concurrent.CompletableFuture; public class BridgePlayer extends CommonBridgePlayer implements SessionScore, BlockChoice, SetupMeta { @@ -44,39 +39,6 @@ public class BridgePlayer extends CommonBridgePlayer implements SessionS private Material chosenBlock; private boolean inSetup; - /** - * Create a new BridgePlayer object that is a copy of the given BridgePlayer - * - * @param copy The BridgePlayer to copy. - * @return A new BridgePlayer object. - */ - public static BridgePlayer of(final BridgePlayer copy) { - return new BridgePlayer(copy); - } - - /** - * Create a new BridgePlayer object with the given UUID - * - * @param playerUid The UUID of the player. - * @return A new BridgePlayer object. - */ - public static BridgePlayer of(final IslandService islandService, - final Leaderboard leaderboard, final UUID playerUid) { - return new BridgePlayer(islandService, leaderboard, playerUid); - } - - /** - * Create a new BridgePlayer object with the given name and playerUid - * - * @param name The name of the player. - * @param playerUid The UUID of the player. - * @return A new BridgePlayer object. - */ - public static BridgePlayer of(final IslandService islandService, - final Leaderboard leaderboard, final String name, final UUID playerUid) { - return new BridgePlayer(islandService, leaderboard, name, playerUid); - } - protected BridgePlayer(final BridgePlayer copy) { this(copy.islandService, copy.leaderboard, copy.getName(), copy.playerUid); this.scoreMap.putAll(copy.scoreMap); @@ -87,7 +49,7 @@ protected BridgePlayer(final BridgePlayer copy) { } protected BridgePlayer(final IslandService islandService, - final Leaderboard leaderboard, final UUID playerUid) { + final Leaderboard leaderboard, final UUID playerUid) { this(islandService, leaderboard, "null", playerUid); if (player != null) { @@ -115,17 +77,54 @@ protected BridgePlayer(final IslandService islandService, final Leaderboard lead this.inSetup = false; } + /** + * Create a new BridgePlayer object that is a copy of the given BridgePlayer + * + * @param copy The BridgePlayer to copy. + * @return A new BridgePlayer object. + */ + public static BridgePlayer of(final BridgePlayer copy) { + return new BridgePlayer(copy); + } + + /** + * Create a new BridgePlayer object with the given UUID + * + * @param playerUid The UUID of the player. + * @return A new BridgePlayer object. + */ + public static BridgePlayer of(final IslandService islandService, + final Leaderboard leaderboard, final UUID playerUid) { + return new BridgePlayer(islandService, leaderboard, playerUid); + } + + /** + * Create a new BridgePlayer object with the given name and playerUid + * + * @param name The name of the player. + * @param playerUid The UUID of the player. + * @return A new BridgePlayer object. + */ + public static BridgePlayer of(final IslandService islandService, + final Leaderboard leaderboard, final String name, final UUID playerUid) { + return new BridgePlayer(islandService, leaderboard, name, playerUid); + } + @Override public String getName() { return this.name; } + public void setName(final String name) { + this.name = name; + } + /** * If the score is lower than the current score, * then update the scoreMap and sessionMap * * @param islandSlot The slot of the island that the player is currently on. - * @param score the score to be set + * @param score the score to be set * @return The new score. */ public Score setScoreIfLower(final int islandSlot, final double score) { @@ -191,7 +190,7 @@ public Score setNewScore(final Score score) { * It sets the score of the given island slot to the given new score. * * @param islandSlot The island slot that the score is being set for. - * @param newScore The new score to set. + * @param newScore The new score to set. * @return the score */ public Score setNewScore(final int islandSlot, final double newScore) { @@ -276,10 +275,6 @@ public CompletableFuture resetStats() { return Databases.STATS_DATABASE.delete(getPlayerUid()); } - public void setGamePlayer(final GamePlayer gamePlayer) { - this.gamePlayer = gamePlayer; - } - public boolean isPlaying() { return gamePlayer != null; } @@ -318,6 +313,10 @@ public GamePlayer getGamePlayer() { return gamePlayer; } + public void setGamePlayer(final GamePlayer gamePlayer) { + this.gamePlayer = gamePlayer; + } + public void invalidatePlayer() { this.player = null; @@ -332,10 +331,6 @@ public void invalidatePlayer() { resetSessionScores(); } - public void setName(final String name) { - this.name = name; - } - public void internalRefresh(final UUID uniqueId) { this.player = Bukkit.getPlayer(uniqueId); this.name = player.getName(); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/CommonBridgePlayer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/CommonBridgePlayer.java index 1689829e..3cd848be 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/CommonBridgePlayer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/CommonBridgePlayer.java @@ -5,7 +5,7 @@ public class CommonBridgePlayer { public String getName() { throw new UnsupportedOperationException("getName have not been " + - "implemented."); + "implemented."); } public T getPlayer() { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/DummyBridgePlayer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/DummyBridgePlayer.java index c6cf2618..4da11db5 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/DummyBridgePlayer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/DummyBridgePlayer.java @@ -6,13 +6,13 @@ import java.util.UUID; public class DummyBridgePlayer extends BridgePlayer { - public static DummyBridgePlayer of(final IslandService islandService, - final Leaderboard leaderboard, final UUID uniqueId) { - return new DummyBridgePlayer(islandService, leaderboard, uniqueId); - } - private DummyBridgePlayer(final IslandService islandService, - final Leaderboard leaderboard, final UUID uniqueId) { + final Leaderboard leaderboard, final UUID uniqueId) { super(islandService, leaderboard, uniqueId); } + + public static DummyBridgePlayer of(final IslandService islandService, + final Leaderboard leaderboard, final UUID uniqueId) { + return new DummyBridgePlayer(islandService, leaderboard, uniqueId); + } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/GamePlayer.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/GamePlayer.java index f4aedf5e..f90e256d 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/GamePlayer.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/GamePlayer.java @@ -7,7 +7,10 @@ import org.bukkit.Material; import org.bukkit.block.Block; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; public final class GamePlayer { private final BridgePlayer player; @@ -17,6 +20,11 @@ public final class GamePlayer { private GameIsland currentGame = null; private long timer = -1; + private GamePlayer(final BridgePlayer player) { + this.player = player; + this.blockLocations = new ArrayList<>(); + } + /** * It creates a new GamePlayer object for the given player. * @@ -27,15 +35,6 @@ public static GamePlayer of(final BridgePlayer player) { return new GamePlayer(player); } - private GamePlayer(final BridgePlayer player) { - this.player = player; - this.blockLocations = new ArrayList<>(); - } - - public void setCurrentGame(final GameIsland gameIsland) { - this.currentGame = gameIsland; - } - /** * Add a block to the list of blocks * @@ -62,12 +61,12 @@ public void resetBlocks() { for (final Location blockLocation : this.blockLocations) { final Block block = blockLocation.getBlock(); BridgeUtil.debug("GamePlayer(): Resetting " + block.getType() + " at " + block.getX() + - ", " + block.getY() + ", " + block.getZ() + " location!"); + ", " + block.getY() + ", " + block.getZ() + " location!"); block.setType(Material.AIR); } BridgeUtil.debug("GamePlayer(): Finished resetting the blocks! clearing the " + - "block locations " + - "immediately!"); + "block locations " + + "immediately!"); this.blockLocations.clear(); } @@ -98,12 +97,16 @@ public boolean isInQueue() { * Returns the current game * * @return The current game that is being played. - */ + */ public GameIsland getCurrentGame() { return currentGame; } - /** + public void setCurrentGame(final GameIsland gameIsland) { + this.currentGame = gameIsland; + } + + /** * Returns the player object associated with this bridge player * * @return The player object. diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockChoice.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockChoice.java index 93bdb84a..030f7492 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockChoice.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockChoice.java @@ -10,6 +10,7 @@ public interface BlockChoice { * @return The material that was chosen by the user. */ Material getChoseMaterial(); + /** * Set the material of the object to the given material * diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockDatabase.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockDatabase.java index c44c2c19..b6b3ebbe 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockDatabase.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/block/BlockDatabase.java @@ -28,7 +28,7 @@ public CompletableFuture insert(final @NotNull BridgePlayer player) { public CompletableFuture update(final @NotNull BridgePlayer player) { return DatabaseUtil.databaseExecute("UPDATE blocks SET chosen_block = ? " + - "WHERE uid = ?", databaseQuery -> { + "WHERE uid = ?", databaseQuery -> { databaseQuery.setString(player.getChoseMaterial() .name()); databaseQuery.setString(player.getPlayerUid() diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/Score.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/Score.java index 186935b7..17a80153 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/Score.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/Score.java @@ -6,22 +6,22 @@ public final class Score implements Comparable { private final int scoredOn; private final double score; + private Score(final int scoredOn, final double score) { + this.scoredOn = scoredOn; + this.score = score; + } + /** * Create a new Score object with the given island slot and score * * @param islandSlot The island slot that the score is for. - * @param score The score of the island. + * @param score The score of the island. * @return A new instance of Score. */ public static Score of(final int islandSlot, final double score) { return new Score(islandSlot, score); } - private Score(final int scoredOn, final double score) { - this.scoredOn = scoredOn; - this.score = score; - } - /** * Returns the score of the game * diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/ScoreDatabase.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/ScoreDatabase.java index c41b0374..125fac91 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/ScoreDatabase.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/score/ScoreDatabase.java @@ -21,10 +21,10 @@ public ScoreDatabase() { } public @NotNull CompletableFuture insert(final @NotNull UUID uuid, - final @NotNull Score score) { + final @NotNull Score score) { return DatabaseUtil.databaseExecute( "INSERT OR IGNORE INTO scores (uid, island_slot, score) VALUES " + - "(?, ?, ?)", databaseQuery -> { + "(?, ?, ?)", databaseQuery -> { BridgeUtil.debug("player uid: " + uuid); databaseQuery.setString(uuid.toString()); @@ -38,9 +38,9 @@ public ScoreDatabase() { } public @NotNull CompletableFuture update(final @NotNull UUID uuid, - final @NotNull Score score) { + final @NotNull Score score) { return DatabaseUtil.databaseExecute("UPDATE scores SET island_slot = ?, " + - "score = ? WHERE uid = ?", databaseQuery -> { + "score = ? WHERE uid = ?", databaseQuery -> { BridgeUtil.debug("player uid: " + uuid); BridgeUtil.debug("player score island: " + score.getScoredOn()); @@ -78,7 +78,7 @@ public ScoreDatabase() { public CompletableFuture delete(final UUID uuid) { return PluginExecutor.runAsync(() -> { try (final DatabaseQuery query = DatabaseQuery.query("DELETE FROM scores " + - "WHERE uid = ?")) { + "WHERE uid = ?")) { query.setString(uuid.toString()); query.execute(); } catch (Exception e) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/session/SessionScore.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/session/SessionScore.java index 78ca77d0..858220e5 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/session/SessionScore.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/session/SessionScore.java @@ -11,6 +11,7 @@ public interface SessionScore { * @return A collection of Score objects. */ Collection getSessionScores(); + /** * Reset the session scores for all users */ diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/setup/SetupMeta.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/setup/SetupMeta.java index 193136a9..9e760eb0 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/setup/SetupMeta.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/setup/SetupMeta.java @@ -7,10 +7,12 @@ public interface SetupMeta { * @return A boolean value. */ boolean isInSetup(); + /** * Toggle the setup mode of the program */ void toggleSetup(); + /** * Reset the setup to the default values */ diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStat.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStat.java index fa8ebfff..dfdebab0 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStat.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStat.java @@ -16,6 +16,7 @@ public interface PlayerStat { * @return The key of the current node. */ String getKey(); + /** * The function returns a string * diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStatType.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStatType.java index edcc8c51..0875c7f8 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStatType.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/PlayerStatType.java @@ -23,7 +23,7 @@ public static PlayerStat create(final UUID owner, final PlayerStatType playerSta } public static PlayerStatType match(final String statType) { - switch (statType.toUpperCase(Locale.ENGLISH)){ + switch (statType.toUpperCase(Locale.ENGLISH)) { case "TOTAL_WINS": return PlayerStatType.TOTAL_WINS; case "TOTAL_TRIES": diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/StatsDatabase.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/StatsDatabase.java index d14429a8..e1e3227f 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/StatsDatabase.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/player/object/stat/StatsDatabase.java @@ -25,7 +25,7 @@ public StatsDatabase() { public @NotNull CompletableFuture insert(final @NotNull PlayerStat playerStat) { return DatabaseUtil.databaseExecute( "INSERT OR IGNORE INTO stats (uid, key, value) VALUES " + - "(?, ?, ?)", databaseQuery -> { + "(?, ?, ?)", databaseQuery -> { databaseQuery.setString(playerStat.getOwner() .toString()); databaseQuery.setString(playerStat.getKey()); @@ -35,7 +35,7 @@ public StatsDatabase() { public @NotNull CompletableFuture update(final @NotNull PlayerStat playerStat) { return DatabaseUtil.databaseExecute("UPDATE stats SET value = ? WHERE " + - "uid = ? AND key = ?", databaseQuery -> { + "uid = ? AND key = ?", databaseQuery -> { databaseQuery.setString(playerStat.getValue()); databaseQuery.setString(playerStat.getOwner() @@ -50,21 +50,21 @@ public StatsDatabase() { try { DatabaseUtil.databaseExecute("SELECT * FROM stats WHERE uid = ?", databaseQuery -> { - databaseQuery.setString(owner.toString()); + databaseQuery.setString(owner.toString()); - databaseQuery.executeQuery(resultSet -> { - while (resultSet.next()) { - final PlayerStatType playerStatType = PlayerStatType.match(resultSet.getString("key")); + databaseQuery.executeQuery(resultSet -> { + while (resultSet.next()) { + final PlayerStatType playerStatType = PlayerStatType.match(resultSet.getString("key")); - if (playerStatType == null) { - continue; - } - final PlayerStat playerStat = PlayerStatType.create(owner, playerStatType, resultSet.getString("value")); - BridgeUtil.debug("found stat: " + playerStat); + if (playerStatType == null) { + continue; + } + final PlayerStat playerStat = PlayerStatType.create(owner, playerStatType, resultSet.getString("value")); + BridgeUtil.debug("found stat: " + playerStat); - playerStats.add(playerStat); - } - }); + playerStats.add(playerStat); + } + }); }) .get(); } catch (InterruptedException | ExecutionException e) { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/PluginExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/PluginExpansion.java index 32593d6c..1378b25d 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/PluginExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/PluginExpansion.java @@ -50,7 +50,7 @@ public boolean canRegister() { @Override public String onPlaceholderRequest(final Player player, - @NotNull final String params) { + @NotNull final String params) { if (player == null) { return ""; } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/AbstractExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/AbstractExpansion.java index d0e68c08..f06b0b68 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/AbstractExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/AbstractExpansion.java @@ -9,8 +9,11 @@ public AbstractExpansion() { } public abstract String getIdentifier(); + public abstract String getDefaultAction(final BridgePlayer bridgePlayer); + public abstract boolean passedRequirement(final BridgePlayer bridgePlayer, final String[] args); + public abstract String runAction(final BridgePlayer bridgePlayer, - final GamePlayer gamePlayer, final String[] args); + final GamePlayer gamePlayer, final String[] args); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/BestScoreExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/BestScoreExpansion.java index 97090e85..7e90c102 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/BestScoreExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/BestScoreExpansion.java @@ -3,9 +3,9 @@ import io.tofpu.dynamicclass.meta.AutoRegister; import io.tofpu.speedbridge2.model.common.Message; import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import io.tofpu.speedbridge2.model.player.object.GamePlayer; +import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.model.support.placeholderapi.expansion.AbstractExpansion; @AutoRegister diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/IslandSlotExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/IslandSlotExpansion.java index 5da75bab..e4059e88 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/IslandSlotExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/IslandSlotExpansion.java @@ -25,7 +25,7 @@ public boolean passedRequirement(final BridgePlayer bridgePlayer, final String[] @Override public String runAction(final BridgePlayer bridgePlayer, - final GamePlayer gamePlayer, final String[] args) { + final GamePlayer gamePlayer, final String[] args) { final GameIsland currentGame = bridgePlayer.getCurrentGame(); if (currentGame == null) { return ""; diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/LeaderboardExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/LeaderboardExpansion.java index 16962adf..c2c147f3 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/LeaderboardExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/LeaderboardExpansion.java @@ -4,13 +4,13 @@ import io.tofpu.speedbridge2.model.common.Message; import io.tofpu.speedbridge2.model.common.config.manager.ConfigurationManager; import io.tofpu.speedbridge2.model.common.util.BridgeUtil; -import io.tofpu.speedbridge2.model.leaderboard.Leaderboard; -import io.tofpu.speedbridge2.model.leaderboard.object.BoardPlayer; import io.tofpu.speedbridge2.model.island.IslandService; import io.tofpu.speedbridge2.model.island.object.Island; -import io.tofpu.speedbridge2.model.player.object.score.Score; +import io.tofpu.speedbridge2.model.leaderboard.Leaderboard; +import io.tofpu.speedbridge2.model.leaderboard.object.BoardPlayer; import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import io.tofpu.speedbridge2.model.player.object.GamePlayer; +import io.tofpu.speedbridge2.model.player.object.score.Score; import io.tofpu.speedbridge2.model.support.placeholderapi.expansion.AbstractExpansion; @AutoRegister @@ -35,14 +35,14 @@ public String getDefaultAction(final BridgePlayer bridgePlayer) { @Override public boolean passedRequirement(final BridgePlayer bridgePlayer, - final String[] args) { + final String[] args) { // this placeholder requires four arguments - return args.length == 3; + return args.length >= 3 && args.length <= 4; } @Override public String runAction(final BridgePlayer bridgePlayer, - final GamePlayer gamePlayer, final String[] args) { + final GamePlayer gamePlayer, final String[] args) { final int position = parse(args, 2); if (position == -1) { return "Invalid Placeholder"; @@ -82,6 +82,16 @@ public String runAction(final BridgePlayer bridgePlayer, return ""; } + TextDisplayType textDisplayType = TextDisplayType.FULL; + if (args.length > 3) { + textDisplayType = TextDisplayType.fromString(args[3], TextDisplayType.FULL); + } + + if (textDisplayType == TextDisplayType.NAME) { + return boardPlayer.getName(); + } else if (textDisplayType == TextDisplayType.SCORE) { + return BridgeUtil.formatNumber(bestScore.getScore()); + } return BridgeUtil.translate(ConfigurationManager.INSTANCE.getLeaderboardCategory() .getLeaderboardFormat() .replace("%position%", boardPlayer.getPosition() + "") @@ -89,6 +99,21 @@ public String runAction(final BridgePlayer bridgePlayer, .replace("%score%", BridgeUtil.formatNumber(bestScore.getScore()))); } + enum TextDisplayType { + NAME, SCORE, FULL; + + private static final TextDisplayType[] CACHED_VALUES = values(); + + public static TextDisplayType fromString(final String string, final TextDisplayType defaultValue) { + for (final TextDisplayType textDisplayType : CACHED_VALUES) { + if (textDisplayType.name().equalsIgnoreCase(string)) { + return textDisplayType; + } + } + return defaultValue; + } + } + public int parse(final String[] args, final int index) { try { return Integer.parseInt(args[index]); diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/PositionExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/PositionExpansion.java index 4a0677ee..aa2d6f3a 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/PositionExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/PositionExpansion.java @@ -38,7 +38,7 @@ public boolean passedRequirement(final BridgePlayer bridgePlayer, final String[] @Override public String runAction(final BridgePlayer bridgePlayer, - final GamePlayer gamePlayer, final String[] args) { + final GamePlayer gamePlayer, final String[] args) { if (args.length == 2) { // returns island-based position return getIslandPosition(bridgePlayer, args); } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TimerExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TimerExpansion.java index be018025..7ddf9f8a 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TimerExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TimerExpansion.java @@ -27,7 +27,7 @@ public boolean passedRequirement(final BridgePlayer bridgePlayer, final String[] @Override public String runAction(final BridgePlayer bridgePlayer, - final GamePlayer gamePlayer, final String[] args) { + final GamePlayer gamePlayer, final String[] args) { return BridgeUtil.formatNumber(BridgeUtil.nanoToSeconds(gamePlayer.getTimer())); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TotalStatsExpansion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TotalStatsExpansion.java index 2b2b8f7a..a0320fd0 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TotalStatsExpansion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/placeholderapi/expansion/expansions/TotalStatsExpansion.java @@ -1,8 +1,8 @@ package io.tofpu.speedbridge2.model.support.placeholderapi.expansion.expansions; -import io.tofpu.speedbridge2.model.player.object.stat.PlayerStatType; import io.tofpu.speedbridge2.model.player.object.BridgePlayer; import io.tofpu.speedbridge2.model.player.object.GamePlayer; +import io.tofpu.speedbridge2.model.player.object.stat.PlayerStatType; import io.tofpu.speedbridge2.model.support.placeholderapi.expansion.AbstractExpansion; public final class TotalStatsExpansion extends AbstractExpansion { diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/worldedit/CuboidRegion.java b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/worldedit/CuboidRegion.java index 0fee5742..3a469e25 100644 --- a/spigot/src/main/java/io/tofpu/speedbridge2/model/support/worldedit/CuboidRegion.java +++ b/spigot/src/main/java/io/tofpu/speedbridge2/model/support/worldedit/CuboidRegion.java @@ -40,6 +40,6 @@ public boolean contains(final Vector vector) { final double z = vector.getZ(); return x >= minVector.getX() && x <= maxVector.getX() && y >= minVector.getY() && - y <= maxVector.getY() && z >= minVector.getZ() && z <= maxVector.getZ(); + y <= maxVector.getY() && z >= minVector.getZ() && z <= maxVector.getZ(); } } diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/util/material/MaterialCategory.java b/spigot/src/main/java/io/tofpu/speedbridge2/util/material/MaterialCategory.java new file mode 100644 index 00000000..68e01317 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/util/material/MaterialCategory.java @@ -0,0 +1,6 @@ +package io.tofpu.speedbridge2.util.material; + +public enum MaterialCategory { + ANY, + BLOCK +} diff --git a/spigot/src/main/java/io/tofpu/speedbridge2/util/material/MultiMaterial.java b/spigot/src/main/java/io/tofpu/speedbridge2/util/material/MultiMaterial.java new file mode 100644 index 00000000..806328e1 --- /dev/null +++ b/spigot/src/main/java/io/tofpu/speedbridge2/util/material/MultiMaterial.java @@ -0,0 +1,57 @@ +package io.tofpu.speedbridge2.util.material; + +import com.cryptomorin.xseries.XMaterial; +import io.tofpu.dynamicclass.meta.AutoRegister; +import org.bukkit.Material; + +import java.util.*; + +@AutoRegister +public final class MultiMaterial { + private static final Map GENERAL_MATERIAL_LOOKUP_MAP = new HashMap<>(); + private static final Set BLOCK_MATERIALS = new HashSet<>(); + + static { + for (Material material : Material.values()) { + addToRegistry(material); + } + for (XMaterial material : XMaterial.values()) { + Material parseMaterial = material.parseMaterial(); + if (parseMaterial == null) continue; + addToRegistry(parseMaterial); + } + } + + private static void addToRegistry(Material material) { + String materialName = material.name(); + GENERAL_MATERIAL_LOOKUP_MAP.put(materialName, material); + + if (material.isBlock()) { + BLOCK_MATERIALS.add(materialName); + } + } + + public static Material getOrThrow(String name) { + Material material = GENERAL_MATERIAL_LOOKUP_MAP.get(name); + if (material == null) { + throw new IllegalArgumentException("Unknown material: %s"); + } + return material; + } + + public static Collection materials() { + return materials(MaterialCategory.ANY); + } + + public static Collection materials(MaterialCategory category) { + switch (category) { + case ANY: + return Collections.unmodifiableCollection(GENERAL_MATERIAL_LOOKUP_MAP.keySet()); + case BLOCK: + System.out.println(String.format("#Materials() returning %s", BLOCK_MATERIALS)); + return Collections.unmodifiableCollection(BLOCK_MATERIALS); + default: + throw new RuntimeException(String.format("Unknown material category: %s", category)); + } + } +}