diff --git a/.editorconfig b/.editorconfig
index bed2d93..b430227 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -432,4 +432,4 @@ ij_yaml_keep_line_breaks = true
ij_yaml_sequence_on_new_line = false
ij_yaml_space_before_colon = false
ij_yaml_spaces_within_braces = true
-ij_yaml_spaces_within_brackets = true
\ No newline at end of file
+ij_yaml_spaces_within_brackets = true
diff --git a/build.gradle.kts b/build.gradle.kts
index a7b2708..8bf4a64 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -4,41 +4,41 @@ import java.time.Instant
plugins {
`java-library`
- id("com.github.johnrengelman.shadow") version "8.1.1" // Shades and relocates dependencies, See https://imperceptiblethoughts.com/shadow/introduction/
- id("xyz.jpenilla.run-paper") version "2.2.4" // Adds runServer and runMojangMappedServer tasks for testing
+ id("io.github.goooler.shadow") version "8.1.8" // Shades and relocates dependencies, See https://imperceptiblethoughts.com/shadow/introduction/
+ id("xyz.jpenilla.run-paper") version "2.3.1" // Adds runServer and runMojangMappedServer tasks for testing
id("net.minecrell.plugin-yml.bukkit") version "0.6.0" // Automatic plugin.yml generation
- id("io.papermc.paperweight.userdev") version "1.6.2" // Used to develop internal plugins using Mojang mappings, See https://github.com/PaperMC/paperweight
- id("org.flywaydb.flyway") version "10.12.0" // Database migrations
- id("org.jooq.jooq-codegen-gradle") version "3.19.7"
+ id("io.papermc.paperweight.userdev") version "1.7.1" // Used to develop internal plugins using Mojang mappings, See https://github.com/PaperMC/paperweight
+ id("org.flywaydb.flyway") version "10.17.3" // Database migrations
+ id("org.jooq.jooq-codegen-gradle") version "3.19.11"
eclipse
idea
}
-group = "com.github.alathra"
-version = "3.0.0"
-description = ""
-val mainPackage = "${project.group}.${rootProject.name.lowercase()}"
+val mainPackage = "${project.group}.${project.name.lowercase()}"
+applyCustomVersion()
java {
- toolchain.languageVersion.set(JavaLanguageVersion.of(17)) // Configure the java toolchain. This allows gradle to auto-provision JDK 17 on systems that only have JDK 8 installed for example.
-// withJavadocJar() // Enable Javadoc generation
+ toolchain.languageVersion.set(JavaLanguageVersion.of(17)) // Configure the java toolchain. This allows gradle to auto-provision JDK 21 on systems that only have JDK 8 installed for example.
+ withJavadocJar() // Enable javadoc jar generation
+ withSourcesJar() // Enable sources jar generation
}
repositories {
mavenCentral()
- maven("https://papermc.io/repo/repository/maven-public/")
+ maven("https://repo.papermc.io/repository/maven-public/")
maven("https://mvn-repo.arim.space/lesser-gpl3/")
+ maven("https://maven.athyrium.eu/releases")
+
maven("https://repo.glaremasters.me/repository/towny/") {
content { includeGroup("com.palmergames.bukkit.towny") }
}
maven("https://jitpack.io/") {
content {
- includeGroup("com.github.milkdrinkers")
- includeGroup("com.github.MilkBowl")
+ includeGroup("com.github.MilkBowl") // VaultAPI
includeGroup("com.palmergames.bukkit.towny")
includeGroup("com.github.Gecolay.GSit")
}
@@ -55,6 +55,8 @@ repositories {
maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") {
content { includeGroup("me.clip") }
}
+
+ maven("https://repo.dmulloy2.net/repository/public/") // ProtocolLib
}
dependencies {
@@ -62,19 +64,23 @@ dependencies {
annotationProcessor("org.jetbrains:annotations:24.1.0")
paperweight.paperDevBundle("1.20.1-R0.1-SNAPSHOT")
- implementation("space.arim.morepaperlib:morepaperlib:latest.release")
+ implementation("space.arim.morepaperlib:morepaperlib:0.4.4")
- implementation("com.github.milkdrinkers:crate:1.1.0")
- implementation("com.github.milkdrinkers:colorparser:2.0.0") {
+ // API
+ implementation("com.github.milkdrinkers:crate-api:2.0.0")
+ implementation("com.github.milkdrinkers:crate-yaml:2.0.0")
+ implementation("com.github.milkdrinkers:colorparser:2.0.3") {
exclude("net.kyori")
}
-
implementation("dev.jorel:commandapi-bukkit-shade:9.3.0")
- compileOnly("me.clip:placeholderapi:2.11.5") {
+ // Plugin Dependencies
+ implementation("org.bstats:bstats-bukkit:3.0.3")
+ compileOnly("com.github.MilkBowl:VaultAPI:1.7.1")
+ compileOnly("com.comphenix.protocol:ProtocolLib:5.3.0-SNAPSHOT")
+ compileOnly("me.clip:placeholderapi:2.11.6") {
exclude("me.clip.placeholderapi.libs", "kyori")
}
- compileOnly("com.github.MilkBowl:VaultAPI:1.7.1")
compileOnly("com.palmergames.bukkit.towny:towny:0.100.2.6") {
exclude("com.palmergames.adventure")
}
@@ -84,19 +90,41 @@ dependencies {
compileOnly(files("lib/HeadsPlus-7.0.14.jar"))
compileOnly(files("lib/Skulls.jar"))
- // Database Dependencies
+ // Database Dependencies (Core)
implementation("com.zaxxer:HikariCP:5.1.0")
- library("org.flywaydb:flyway-core:10.12.0")
- library("org.flywaydb:flyway-mysql:10.12.0")
- library("org.flywaydb:flyway-database-hsqldb:10.12.0")
- library("org.jooq:jooq:3.19.7")
- jooqCodegen("com.h2database:h2:2.2.224")
+ library("org.flywaydb:flyway-core:10.17.3")
+ library("org.flywaydb:flyway-mysql:10.17.3")
+ library("org.jooq:jooq:3.19.11")
+ jooqCodegen("com.h2database:h2:2.3.232")
- // JDBC Drivers
- library("org.hsqldb:hsqldb:2.7.2")
- library("com.h2database:h2:2.2.224")
- library("com.mysql:mysql-connector-j:8.3.0")
- library("org.mariadb.jdbc:mariadb-java-client:3.3.3")
+ // Database Dependencies (JDBC Drivers)
+ library("com.h2database:h2:2.3.232")
+ library("org.xerial:sqlite-jdbc:3.46.1.0")
+ library("com.mysql:mysql-connector-j:9.0.0")
+ library("org.mariadb.jdbc:mariadb-java-client:3.4.1")
+
+ // Testing (Core)
+ testImplementation("org.jetbrains:annotations:24.1.0")
+ testImplementation(platform("org.junit:junit-bom:5.11.0"))
+ testImplementation("org.junit.jupiter:junit-jupiter")
+ testRuntimeOnly("org.junit.platform:junit-platform-launcher")
+ testRuntimeOnly("org.slf4j:slf4j-simple:2.1.0-alpha1")
+ testImplementation(platform("org.testcontainers:testcontainers-bom:1.20.1"))
+ testImplementation("org.testcontainers:junit-jupiter")
+ testImplementation("org.testcontainers:mysql")
+ testImplementation("org.testcontainers:mariadb")
+
+ // Testing (Database Dependencies)
+ testImplementation("com.zaxxer:HikariCP:5.1.0")
+ testImplementation("org.flywaydb:flyway-core:10.17.3")
+ testImplementation("org.flywaydb:flyway-mysql:10.17.3")
+ testImplementation("org.jooq:jooq:3.19.11")
+
+ // Testing (JDBC Drivers)
+ testImplementation("com.h2database:h2:2.3.232")
+ testImplementation("org.xerial:sqlite-jdbc:3.46.1.0")
+ testImplementation("com.mysql:mysql-connector-j:9.0.0")
+ testImplementation("org.mariadb.jdbc:mariadb-java-client:3.4.1")
}
tasks {
@@ -125,11 +153,13 @@ tasks {
javadoc {
isFailOnError = false
- exclude("${mainPackage.replace(".", "/")}/db/schema/**") // Exclude generated jOOQ sources from javadocs
+ exclude("**/database/schema/**") // Exclude generated jOOQ sources from javadocs
val options = options as StandardJavadocDocletOptions
- options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything
+ options.encoding = Charsets.UTF_8.name()
options.overview = "src/main/javadoc/overview.html"
+ options.windowTitle = "${rootProject.name} Javadoc"
options.tags("apiNote:a:API Note:", "implNote:a:Implementation Note:", "implSpec:a:Implementation Requirements:")
+ options.addStringOption("Xdoclint:none", "-quiet")
options.use()
}
@@ -145,10 +175,11 @@ tasks {
fun reloc(originPkg: String, targetPkg: String) = relocate(originPkg, "${mainPackage}.lib.${targetPkg}")
reloc("space.arim.morepaperlib", "morepaperlib")
- reloc("com.github.milkdrinkers.Crate", "crate")
+ reloc("com.github.milkdrinkers.crate", "crate")
reloc("com.github.milkdrinkers.colorparser", "colorparser")
reloc("dev.jorel.commandapi", "commandapi")
reloc("com.zaxxer.hikari", "hikaricp")
+ reloc("org.bstats", "bstats")
mergeServiceFiles {
setPath("META-INF/services/org.flywaydb.core.extensibility.Plugin") // Fix Flyway overriding its own files
@@ -157,30 +188,40 @@ tasks {
minimize()
}
+ test {
+ useJUnitPlatform()
+ failFast = false
+ }
+
runServer {
// Configure the Minecraft version for our task.
minecraftVersion("1.20.1")
// IntelliJ IDEA debugger setup: https://docs.papermc.io/paper/dev/debugging#using-a-remote-debugger
- jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-DPaper.IgnoreJavaVersion=true", "-Dcom.mojang.eula.agree=true", "-DIReallyKnowWhatIAmDoingISwear")
+ jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-DPaper.IgnoreJavaVersion=true", "-Dcom.mojang.eula.agree=true", "-DIReallyKnowWhatIAmDoingISwear", "-Dpaper.playerconnection.keepalive=6000")
systemProperty("terminal.jline", false)
systemProperty("terminal.ansi", true)
// Automatically install dependencies
downloadPlugins {
- url("https://ci.dmulloy2.net/job/ProtocolLib/lastStableBuild/artifact/build/libs/ProtocolLib.jar")
github("MilkBowl", "Vault", "1.7.3", "Vault.jar")
url("https://download.luckperms.net/1521/bukkit/loader/LuckPerms-Bukkit-5.4.108.jar")
modrinth("tab-was-taken", "4.1.2")
github("PlaceholderAPI", "PlaceholderAPI", "2.11.4", "PlaceholderAPI-2.11.4.jar")
+ url("https://ci.dmulloy2.net/job/ProtocolLib/lastSuccessfulBuild/artifact/build/libs/ProtocolLib.jar")
// url("https://www.spigotmc.org/resources/skulls-the-ultimate-head-database.90098/download?version=520217/Skulls.jar")
}
}
}
+tasks.named("sourcesJar") { // Required for sources jar generation with jOOQ
+ dependsOn(tasks.jooqCodegen)
+ duplicatesStrategy = DuplicatesStrategy.INCLUDE
+}
+
bukkit { // Options: https://github.com/Minecrell/plugin-yml#bukkit
// Plugin main class (required)
- main = "${mainPackage}.${rootProject.name}"
+ main = "${mainPackage}.${project.name}"
// Plugin Information
name = project.name
@@ -193,23 +234,17 @@ bukkit { // Options: https://github.com/Minecrell/plugin-yml#bukkit
// Misc properties
load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.POSTWORLD // STARTUP or POSTWORLD
- depend = listOf("Vault", "Towny")
+ depend = listOf("Vault", "ProtocolLib", "Towny")
softDepend = listOf("PlaceholderAPI", "TAB", "Skulls", "HeadsPlus")
}
flyway {
- url = "jdbc:h2:${project.layout.buildDirectory.get()}/generated/flyway/db;AUTO_SERVER=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE;IGNORECASE=TRUE"
+ url = "jdbc:h2:${project.layout.buildDirectory.get()}/generated/flyway/db;AUTO_SERVER=TRUE;MODE=MYSQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE;IGNORECASE=TRUE"
user = "sa"
password = ""
schemas = listOf("PUBLIC").toTypedArray()
placeholders = mapOf( // Substitute placeholders for flyway
"tablePrefix" to "",
- "columnSuffix" to " VIRTUAL",
- "tableDefaults" to "",
- "uuidType" to "BINARY(16)",
- "inetType" to "VARBINARY(16)",
- "binaryType" to "BLOB",
- "alterViewStatement" to "ALTER VIEW",
)
validateMigrationNaming = true
baselineOnMigrate = true
@@ -233,27 +268,22 @@ jooq {
database {
name = "org.jooq.meta.h2.H2Database"
includes = ".*"
- excludes = "(flyway_schema_history)|(?i:information_schema\\..*)|(?i:system_lobs\\..*)" // Exclude db specific files
+ excludes = "(flyway_schema_history)|(?i:information_schema\\..*)|(?i:system_lobs\\..*)" // Exclude database specific files
inputSchema = "PUBLIC"
schemaVersionProvider = "SELECT :schema_name || '_' || MAX(\"version\") FROM \"flyway_schema_history\"" // Grab version from Flyway
}
target {
- packageName = "${mainPackage}.db.schema"
- directory = layout.buildDirectory.dir("generated-src/jooq").get().toString()
+ packageName = "${mainPackage}.database.schema"
withClean(true)
}
}
}
}
-// Apply custom version arg
-val versionArg = if (hasProperty("customVersion"))
- (properties["customVersion"] as String).uppercase() // Uppercase version string
-else
- "${project.version}-SNAPSHOT-${Instant.now().epochSecond}" // Append snapshot to version
+fun applyCustomVersion() {
+ // Apply custom version arg or append snapshot version
+ val ver = properties["altVer"]?.toString() ?: "${rootProject.version}-SNAPSHOT-${Instant.now().epochSecond}"
-// Strip prefixed "v" from version tag
-project.version = if (versionArg.first().equals('v', true))
- versionArg.substring(1)
-else
- versionArg.uppercase()
\ No newline at end of file
+ // Strip prefixed "v" from version tag
+ rootProject.version = (if (ver.first().equals('v', true)) ver.substring(1) else ver.uppercase()).uppercase()
+}
\ No newline at end of file
diff --git a/crowdin.yml b/crowdin.yml
new file mode 100644
index 0000000..f60df84
--- /dev/null
+++ b/crowdin.yml
@@ -0,0 +1,3 @@
+files:
+ - source: /src/main/resources/translations/en-US.yml
+ translation: /src/main/resources/translations/%locale%.yml
diff --git a/gradle.properties b/gradle.properties
index fc40dfd..85ba786 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,4 +1,7 @@
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.daemon=true
-org.gradle.jvmargs=-Xmx2048M
\ No newline at end of file
+org.gradle.jvmargs=-Xmx2048M
+group=com.github.alathra
+version=3.0.0
+description=
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 7f93135..a4b76b9 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 3fa8f86..0aaefbc 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
diff --git a/gradlew b/gradlew
index 1aa94a4..f5feea6 100755
--- a/gradlew
+++ b/gradlew
@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+# SPDX-License-Identifier: Apache-2.0
+#
##############################################################################
#
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
-# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -84,7 +86,8 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
-APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
diff --git a/gradlew.bat b/gradlew.bat
index 93e3f59..9d21a21 100755
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@@ -43,11 +45,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
goto fail
@@ -57,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
goto fail
diff --git a/settings.gradle.kts b/settings.gradle.kts
index 8c6c031..b1b17fe 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -6,7 +6,7 @@ pluginManagement {
}
plugins {
- id("org.gradle.toolchains.foojay-resolver-convention") version("0.7.0")
+ id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" // allow automatic download of JDKs
}
rootProject.name = "AlathranWars"
\ No newline at end of file
diff --git a/src/main/java/com/github/alathra/alathranwars/AlathranWars.java b/src/main/java/com/github/alathra/alathranwars/AlathranWars.java
index 30ea039..f9deba1 100644
--- a/src/main/java/com/github/alathra/alathranwars/AlathranWars.java
+++ b/src/main/java/com/github/alathra/alathranwars/AlathranWars.java
@@ -1,102 +1,197 @@
package com.github.alathra.alathranwars;
-import com.github.alathra.alathranwars.commands.CommandManager;
+import com.github.alathra.alathranwars.commands.CommandHandler;
import com.github.alathra.alathranwars.config.ConfigHandler;
import com.github.alathra.alathranwars.conflict.war.WarController;
-import com.github.alathra.alathranwars.db.DatabaseHandler;
-import com.github.alathra.alathranwars.db.DatabaseQueries;
-import com.github.alathra.alathranwars.hooks.HookManager;
-import com.github.alathra.alathranwars.items.WarItemRegistry;
+import com.github.alathra.alathranwars.database.DatabaseQueries;
+import com.github.alathra.alathranwars.database.handler.DatabaseHandler;
+import com.github.alathra.alathranwars.hook.*;
import com.github.alathra.alathranwars.listeners.ListenerHandler;
-import net.milkbowl.vault.economy.Economy;
-import org.bukkit.plugin.RegisteredServiceProvider;
+import com.github.alathra.alathranwars.translation.TranslationManager;
+import com.github.alathra.alathranwars.updatechecker.UpdateChecker;
+import com.github.alathra.alathranwars.utility.Logger;
+import com.github.milkdrinkers.colorparser.ColorParser;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
import space.arim.morepaperlib.MorePaperLib;
public class AlathranWars extends JavaPlugin {
- public static @Nullable Economy econ = null;
private static MorePaperLib paperLib;
private static AlathranWars instance;
private ConfigHandler configHandler;
+ private TranslationManager translationManager;
private DatabaseHandler databaseHandler;
+ private CommandHandler commandHandler;
private ListenerHandler listenerHandler;
+ private UpdateChecker updateChecker;
- private CommandManager commandManager;
- private HookManager hookManager;
-
- @SuppressWarnings("rawtypes")
- private boolean setupEconomy() {
- if (this.getServer().getPluginManager().getPlugin("Vault") == null) {
- return false;
- }
- @SuppressWarnings("unchecked") final @Nullable RegisteredServiceProvider rsp = (RegisteredServiceProvider) this.getServer()
- .getServicesManager().getRegistration((Class) Economy.class);
- if (rsp == null) {
- return false;
- }
- econ = rsp.getProvider();
- return econ != null;
- }
+ // Hooks
+ private static BStatsHook bStatsHook;
+ private static VaultHook vaultHook;
+ private static ProtocolLibHook protocolLibHook;
+ private static PAPIHook papiHook;
public void onLoad() {
instance = this;
paperLib = new MorePaperLib(instance);
WarController.getInstance();
configHandler = new ConfigHandler(instance);
- databaseHandler = new DatabaseHandler(instance);
- commandManager = new CommandManager(instance);
+ translationManager = new TranslationManager(instance);
+ databaseHandler = new DatabaseHandler(configHandler, getComponentLogger());
+ commandHandler = new CommandHandler(instance);
listenerHandler = new ListenerHandler(instance);
- hookManager = new HookManager();
+ updateChecker = new UpdateChecker();
+ bStatsHook = new BStatsHook(instance);
+ vaultHook = new VaultHook(instance);
+ protocolLibHook = new ProtocolLibHook(instance);
+ papiHook = new PAPIHook(instance);
configHandler.onLoad();
+ translationManager.onLoad();
databaseHandler.onLoad();
- commandManager.onLoad();
+ commandHandler.onLoad();
listenerHandler.onLoad();
- hookManager.onLoad();
+ updateChecker.onLoad();
+ bStatsHook.onLoad();
+ vaultHook.onLoad();
+ protocolLibHook.onLoad();
+ papiHook.onLoad();
}
public void onEnable() {
- this.saveDefaultConfig();
- new WarItemRegistry();
- setupEconomy();
-
configHandler.onEnable();
+ translationManager.onEnable();
databaseHandler.onEnable();
- commandManager.onEnable();
+ commandHandler.onEnable();
listenerHandler.onEnable();
- hookManager.onEnable();
+ updateChecker.onEnable();
+ bStatsHook.onEnable();
+ vaultHook.onEnable();
+ protocolLibHook.onEnable();
+ papiHook.onEnable();
+
+ if (!databaseHandler.isRunning()) {
+ Logger.get().warn(ColorParser.of("Database handler failed to start. Database support has been disabled.").build());
+ }
+
+ if (vaultHook.isVaultLoaded()) {
+ Logger.get().info(ColorParser.of("Vault has been found on this server. Vault support enabled.").build());
+ } else {
+ Logger.get().warn(ColorParser.of("Vault is not installed on this server. Vault support has been disabled.").build());
+ }
+
+ if (protocolLibHook.isHookLoaded()) {
+ Logger.get().info(ColorParser.of("ProtocolLib has been found on this server. ProtocolLib support enabled.").build());
+ } else {
+ Logger.get().warn(ColorParser.of("ProtocolLib is not installed on this server. ProtocolLib support has been disabled.").build());
+ }
+
WarController.getInstance().loadAll();
}
public void onDisable() {
getPaperLib().scheduling().cancelGlobalTasks();
DatabaseQueries.saveAll();
- commandManager.onDisable();
- listenerHandler.onDisable();
- hookManager.onDisable();
- databaseHandler.onDisable();
+
configHandler.onDisable();
+ translationManager.onDisable();
+ databaseHandler.onDisable();
+ commandHandler.onDisable();
+ listenerHandler.onDisable();
+ updateChecker.onDisable();
+ bStatsHook.onDisable();
+ vaultHook.onDisable();
+ protocolLibHook.onDisable();
+ papiHook.onDisable();
}
+ /**
+ * Gets plugin instance.
+ *
+ * @return the plugin instance
+ */
@NotNull
public static AlathranWars getInstance() {
return instance;
}
+ /**
+ * Gets more paper lib instance.
+ *
+ * @return the more paper lib instance
+ */
public static MorePaperLib getPaperLib() {
return paperLib;
}
+ /**
+ * Gets data handler.
+ *
+ * @return the data handler
+ */
@NotNull
public DatabaseHandler getDataHandler() {
return databaseHandler;
}
+ /**
+ * Gets config handler.
+ *
+ * @return the config handler
+ */
@NotNull
public ConfigHandler getConfigHandler() {
return configHandler;
}
+
+ /**
+ * Gets config handler.
+ *
+ * @return the translation handler
+ */
+ @NotNull
+ public TranslationManager getTranslationManager() {
+ return translationManager;
+ }
+
+ /**
+ * Gets update checker.
+ *
+ * @return the update checker
+ */
+ @NotNull
+ public UpdateChecker getUpdateChecker() {
+ return updateChecker;
+ }
+
+ /**
+ * Gets bStats hook.
+ *
+ * @return the bStats hook
+ */
+ @NotNull
+ public static BStatsHook getBStatsHook() {
+ return bStatsHook;
+ }
+
+ /**
+ * Gets vault hook.
+ *
+ * @return the vault hook
+ */
+ @NotNull
+ public static VaultHook getVaultHook() {
+ return vaultHook;
+ }
+
+ /**
+ * Gets ProtocolLib hook.
+ *
+ * @return the ProtocolLib hook
+ */
+ @NotNull
+ public static ProtocolLibHook getProtocolLibHook() {
+ return protocolLibHook;
+ }
}
diff --git a/src/main/java/com/github/alathra/alathranwars/commands/AdminCommands.java b/src/main/java/com/github/alathra/alathranwars/commands/AdminCommands.java
index 99b08e9..1ac3342 100644
--- a/src/main/java/com/github/alathra/alathranwars/commands/AdminCommands.java
+++ b/src/main/java/com/github/alathra/alathranwars/commands/AdminCommands.java
@@ -1,7 +1,7 @@
package com.github.alathra.alathranwars.commands;
import com.github.alathra.alathranwars.AlathranWars;
-import com.github.alathra.alathranwars.hooks.NameColorHandler;
+import com.github.alathra.alathranwars.hook.NameColorHandler;
import com.github.alathra.alathranwars.items.WarItemRegistry;
import com.github.alathra.alathranwars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
diff --git a/src/main/java/com/github/alathra/alathranwars/commands/CommandManager.java b/src/main/java/com/github/alathra/alathranwars/commands/CommandHandler.java
similarity index 58%
rename from src/main/java/com/github/alathra/alathranwars/commands/CommandManager.java
rename to src/main/java/com/github/alathra/alathranwars/commands/CommandHandler.java
index e17ebfd..23106e5 100644
--- a/src/main/java/com/github/alathra/alathranwars/commands/CommandManager.java
+++ b/src/main/java/com/github/alathra/alathranwars/commands/CommandHandler.java
@@ -4,15 +4,20 @@ import com.github.alathra.alathranwars.AlathranWars;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPIBukkitConfig;
-public class CommandManager {
- private final AlathranWars instance;
+public class CommandHandler {
+ private final AlathranWars plugin;
- public CommandManager(AlathranWars instance) {
- this.instance = instance;
+ /**
+ * Instantiates the Command handler.
+ *
+ * @param plugin the plugin
+ */
+ public CommandHandler(AlathranWars plugin) {
+ this.plugin = plugin;
}
public void onLoad() {
- CommandAPI.onLoad(new CommandAPIBukkitConfig(instance).shouldHookPaperReload(true).silentLogs(true));
+ CommandAPI.onLoad(new CommandAPIBukkitConfig(plugin).shouldHookPaperReload(true).silentLogs(true));
}
public void onEnable() {
diff --git a/src/main/java/com/github/alathra/alathranwars/commands/CommandUtil.java b/src/main/java/com/github/alathra/alathranwars/commands/CommandUtil.java
index 0de605e..45c72ab 100644
--- a/src/main/java/com/github/alathra/alathranwars/commands/CommandUtil.java
+++ b/src/main/java/com/github/alathra/alathranwars/commands/CommandUtil.java
@@ -7,7 +7,6 @@ import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.enums.CommandArgsSiege;
import com.github.alathra.alathranwars.enums.CommandArgsWar;
-import com.github.alathra.alathranwars.hooks.TownyHook;
import com.github.alathra.alathranwars.items.WarItemRegistry;
import com.github.alathra.alathranwars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
@@ -31,10 +30,7 @@ import org.jetbrains.annotations.Nullable;
import java.time.Duration;
import java.time.Instant;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.UUID;
+import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -66,7 +62,7 @@ public class CommandUtil {
return TownyAPI.getInstance().getNation(argNationName);
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
- final @NotNull List nationNames = TownyHook.getNations()
+ final @NotNull List nationNames = TownyAPI.getInstance().getNations()
.stream()
.map(Nation::getName)
.sorted()
@@ -85,7 +81,7 @@ public class CommandUtil {
return TownyAPI.getInstance().getTown(argTownName);
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
- final @NotNull List townNames = TownyHook.getTowns()
+ final @NotNull List townNames = TownyAPI.getInstance().getTowns()
.stream()
.map(Town::getName)
.sorted()
@@ -107,17 +103,17 @@ public class CommandUtil {
@Nullable Nation nation = TownyAPI.getInstance().getNation(argNationName);
- if (war.getNations().contains(nation) || war.getSurrenderedNations().contains(nation))
+ if (war.getNations().contains(nation) || war.getNationsSurrendered().contains(nation))
return nation;
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The nation is already at war!").parseLegacy().build());
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
- final @NotNull List nationNames = TownyHook.getNations()
+ final @NotNull List nationNames = TownyAPI.getInstance().getNations()
.stream()
.map(Nation::getName)
.sorted()
.collect(Collectors.toList());
- final @NotNull List townNames = TownyHook.getTowns()
+ final @NotNull List townNames = TownyAPI.getInstance().getTowns()
.stream()
.map(Town::getName)
.sorted()
@@ -131,7 +127,7 @@ public class CommandUtil {
final @NotNull List removeNames = Stream.concat( // Create a list of all nations in war
war.getNations().stream().map(Nation::getName),
- war.getSurrenderedNations().stream().map(Nation::getName)
+ war.getNationsSurrendered().stream().map(Nation::getName)
).toList();
nationNames.removeAll(removeNames);
@@ -152,12 +148,12 @@ public class CommandUtil {
@Nullable Town town = TownyAPI.getInstance().getTown(argTownName);
- if (war.getTowns().contains(town) || war.getSurrenderedTowns().contains(town))
+ if (war.getTowns().contains(town) || war.getTownsSurrendered().contains(town))
return town;
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The town is already at war!").parseLegacy().build());
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
- final @NotNull List townNames = TownyHook.getTowns()
+ final @NotNull List townNames = TownyAPI.getInstance().getTowns()
.stream()
.map(Town::getName)
.sorted()
@@ -169,7 +165,7 @@ public class CommandUtil {
final @NotNull List removeNames = Stream.concat( // Create a list of all nations & towns in war
war.getTowns().stream().map(Town::getName),
- war.getSurrenderedTowns().stream().map(Town::getName)
+ war.getTownsSurrendered().stream().map(Town::getName)
).toList();
townNames.removeAll(removeNames);
@@ -188,7 +184,7 @@ public class CommandUtil {
if (nation == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The nation does not exist!").parseLegacy().build());
- if (!war.isNationInWar(nation))
+ if (!war.isInWar(nation))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The nation is not in that war!").parseLegacy().build());
return nation;
@@ -198,7 +194,7 @@ public class CommandUtil {
return Stream.concat( // Create a list of all nations & towns in war
war.getNations().stream().map(Nation::getName),
- war.getSurrenderedNations().stream().map(Nation::getName)
+ war.getNationsSurrendered().stream().map(Nation::getName)
).sorted().toList();
}));
}
@@ -213,7 +209,7 @@ public class CommandUtil {
if (town == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The town does not exist!").parseLegacy().build());
- if (!war.isTownInWar(town))
+ if (!war.isInWar(town))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The town is not in that war!").parseLegacy().build());
return town;
@@ -223,7 +219,7 @@ public class CommandUtil {
return Stream.concat( // Create a list of all nations & towns in war
war.getTowns().stream().map(Town::getName),
- war.getSurrenderedTowns().stream().map(Town::getName)
+ war.getTownsSurrendered().stream().map(Town::getName)
).sorted().toList();
}));
}
@@ -256,12 +252,12 @@ public class CommandUtil {
.build()
);
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
- final @NotNull List nationNames = TownyHook.getNations()
+ final @NotNull List nationNames = TownyAPI.getInstance().getNations()
.stream()
.map(Nation::getName)
.sorted()
.collect(Collectors.toList());
- final @NotNull List townNames = TownyHook.getTowns()
+ final @NotNull List townNames = TownyAPI.getInstance().getTowns()
.stream()
.map(Town::getName)
.sorted()
@@ -276,10 +272,10 @@ public class CommandUtil {
final @NotNull List removeNames = Stream.concat( // Create a list of all nations & towns in war
war.getNations().stream().map(Nation::getName),
Stream.concat(
- war.getSurrenderedNations().stream().map(Nation::getName),
+ war.getNationsSurrendered().stream().map(Nation::getName),
Stream.concat(
war.getTowns().stream().map(Town::getName),
- war.getSurrenderedTowns().stream().map(Town::getName)
+ war.getTownsSurrendered().stream().map(Town::getName)
)
)
).toList();
@@ -301,9 +297,9 @@ public class CommandUtil {
);
}
- final List townNames = war.getTowns().stream().map(Town::getName).sorted().toList();
- final List nationNames = war.getNations().stream().map(Nation::getName).sorted().toList();
- final List playerNames = war.getPlayersIncludingOffline().stream()
+ final List townNames = war.getTownsAll().stream().map(Town::getName).sorted().toList();
+ final List nationNames = war.getNationsAll().stream().map(Nation::getName).sorted().toList();
+ final List playerNames = war.getPlayersAll().stream()
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
.filter(p -> p.getName() != null)
.map(OfflinePlayer::getName)
@@ -330,12 +326,12 @@ public class CommandUtil {
return Collections.emptyList();
}
- final List nationNames = war.getNations().stream().map(Nation::getName).sorted().toList();
- final List townNames = war.getTowns().stream().map(Town::getName).sorted().toList();
- final List playerNames = war.getPlayersIncludingOffline().stream()
+ final List nationNames = war.getNationsAll().stream().map(Nation::getName).sorted().toList();
+ final List townNames = war.getTownsAll().stream().map(Town::getName).sorted().toList();
+ final List playerNames = war.getPlayersAll().stream()
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
- .filter(p -> p.getName() != null)
.map(OfflinePlayer::getName)
+ .filter(Objects::nonNull)
.sorted()
.toList();
@@ -358,7 +354,7 @@ public class CommandUtil {
if (town == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The town does not exist!").parseLegacy().build());
- if (!war.isTownInWar(town))
+ if (!war.isInWar(town))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The town is not in that war!").parseLegacy().build());
if (checkIfSieged) {
@@ -376,14 +372,14 @@ public class CommandUtil {
final @NotNull List townNames = new ArrayList<>();
if (info.sender() instanceof Player p) {
- if (war.getSide1().isPlayerOnSide(p)) {
+ if (war.getSide1().isOnSide(p)) {
townNames.addAll(war.getSide2().getTowns()
.stream()
.map(TownyObject::getName)
.sorted()
.toList()
);
- } else if (war.getSide2().isPlayerOnSide(p)) {
+ } else if (war.getSide2().isOnSide(p)) {
townNames.addAll(war.getSide1().getTowns()
.stream()
.map(TownyObject::getName)
@@ -418,13 +414,13 @@ public class CommandUtil {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player does not exist!").build());
- if (!siege.isPlayerInSiege(player))
+ if (!siege.isPlayerParticipating(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player is already in that war.").build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Only players can execute this command!").build());
- if (!siege.isPlayerInSiege(player))
+ if (!siege.isPlayerParticipating(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You are already in this war.").build());
}
}
@@ -433,13 +429,13 @@ public class CommandUtil {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player does not exist!").build());
- if (siege.isPlayerInSiege(player))
+ if (siege.isPlayerParticipating(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player is not in that war.").build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Only players can execute this command!").build());
- if (siege.isPlayerInSiege(player))
+ if (siege.isPlayerParticipating(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You are not in that war.").build());
}
}
@@ -462,11 +458,11 @@ public class CommandUtil {
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
- siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
+ siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerParticipating(player)).map(Siege::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
- siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
+ siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerParticipating(player)).map(Siege::getName).toList();
}
}
@@ -478,11 +474,11 @@ public class CommandUtil {
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
- siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
+ siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerParticipating(player)).map(Siege::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
- siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
+ siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerParticipating(player)).map(Siege::getName).toList();
}
}
@@ -503,13 +499,13 @@ public class CommandUtil {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player does not exist!").parseLegacy().build());
- if (!war.isPlayerInWar(player))
+ if (!war.isInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player is already in that war.").parseLegacy().build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Only players can execute this command!").parseLegacy().build());
- if (!war.isPlayerInWar(player))
+ if (!war.isInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You are already in this war.").parseLegacy().build());
}
}
@@ -518,13 +514,13 @@ public class CommandUtil {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player does not exist!").parseLegacy().build());
- if (war.isPlayerInWar(player))
+ if (war.isInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player is not in that war.").parseLegacy().build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Only players can execute this command!").parseLegacy().build());
- if (war.isPlayerInWar(player))
+ if (war.isInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You are not in that war.").parseLegacy().build());
}
}
@@ -547,11 +543,11 @@ public class CommandUtil {
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
- warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
+ warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isInWar(player)).map(War::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
- warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
+ warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isInWar(player)).map(War::getName).toList();
}
}
@@ -563,11 +559,11 @@ public class CommandUtil {
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
- warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
+ warNames = WarController.getInstance().getWars().stream().filter(war -> war.isInWar(player)).map(War::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
- warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
+ warNames = WarController.getInstance().getWars().stream().filter(war -> war.isInWar(player)).map(War::getName).toList();
}
}
@@ -594,13 +590,13 @@ public class CommandUtil {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player does not exist!").parseLegacy().build());
- if (side.getPlayers().contains(player))
+ if (side.getPlayersOnline().contains(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The player is already on that side.").parseLegacy().build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Only players can execute this command!").parseLegacy().build());
- if (side.getPlayers().contains(player))
+ if (side.getPlayersOnline().contains(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You are already on that side.").parseLegacy().build());
}
}
@@ -616,14 +612,14 @@ public class CommandUtil {
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
for (@NotNull Side side : war.getSides()) {
- if (!side.getPlayers().contains(player))
+ if (!side.getPlayersOnline().contains(player))
sideNames.add(side.getName());
}
}
} else {
if (info.sender() instanceof Player player) {
for (@NotNull Side side : war.getSides()) {
- if (!side.getPlayers().contains(player))
+ if (!side.getPlayersOnline().contains(player))
sideNames.add(side.getName());
}
}
@@ -655,7 +651,7 @@ public class CommandUtil {
if (isTown && !war.getTowns().stream().map(Town::getName).toList().contains(argTargetName))
return argTargetName;
- if (isPlayer && !war.getPlayers().stream().map(Player::getName).toList().contains(argTargetName))
+ if (isPlayer && !war.getPlayersOnline().stream().map(Player::getName).toList().contains(argTargetName))
return argTargetName;
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid target.").build());
@@ -665,7 +661,7 @@ public class CommandUtil {
// Get all participants in war into list
final List inWar = Stream.concat(
- war.getPlayers().stream().map(Player::getName),
+ war.getPlayersOnline().stream().map(Player::getName),
Stream.concat(
war.getNations().stream().map(Nation::getName),
war.getTowns().stream().map(Town::getName)
diff --git a/src/main/java/com/github/alathra/alathranwars/commands/SiegeCommands.java b/src/main/java/com/github/alathra/alathranwars/commands/SiegeCommands.java
index 84986cb..57b752b 100644
--- a/src/main/java/com/github/alathra/alathranwars/commands/SiegeCommands.java
+++ b/src/main/java/com/github/alathra/alathranwars/commands/SiegeCommands.java
@@ -119,7 +119,7 @@ public class SiegeCommands {
if (side == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You are not in this war.").build());
- if (side.isPlayerSurrendered(siegeLeader))
+ if (side.isSurrendered(siegeLeader))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You have surrendered and cannot participate in this war.").build());
if (side.isSiegeGraceActive() && !asAdmin)
@@ -130,7 +130,7 @@ public class SiegeCommands {
);
// Attacking own side
- if (side.isTownOnSide(town) && !side.isTownSurrendered(town)) {
+ if (side.isOnSide(town) && !side.isSurrendered(town)) {
if (asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You cannot attack your own side.").build());
else
@@ -152,7 +152,7 @@ public class SiegeCommands {
if (location.distance(townLocation) <= Siege.BATTLEFIELD_START_MIN_RANGE && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You need to be further than blocks away from the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MIN_RANGE)).build());
- if ((AlathranWars.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
+ if ((AlathranWars.getVaultHook().isEconomyLoaded() && AlathranWars.getVaultHook().getEconomy().getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You need to have $ to start a siege!").parseMinimessagePlaceholder("amount", String.valueOf(Siege.SIEGE_VICTORY_MONEY)).build());
side.setSiegeGrace();
diff --git a/src/main/java/com/github/alathra/alathranwars/commands/WarCommands.java b/src/main/java/com/github/alathra/alathranwars/commands/WarCommands.java
index 32c59eb..1bb3137 100644
--- a/src/main/java/com/github/alathra/alathranwars/commands/WarCommands.java
+++ b/src/main/java/com/github/alathra/alathranwars/commands/WarCommands.java
@@ -5,7 +5,7 @@ import com.github.alathra.alathranwars.conflict.war.WarBuilder;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
-import com.github.alathra.alathranwars.hooks.NameColorHandler;
+import com.github.alathra.alathranwars.hook.NameColorHandler;
import com.github.alathra.alathranwars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.TownyAPI;
@@ -249,8 +249,8 @@ public class WarCommands {
if (!war.isEventWar()) {
// Join nation into war
- if (isArgNation && nation != null && !war.isNationInWar(nation) && (asAdmin || canKingJoin)) {
- side.addNation(nation);
+ if (isArgNation && nation != null && !war.isInWar(nation) && (asAdmin || canKingJoin)) {
+ side.add(nation);
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().calculatePlayerColors(player));
Bukkit.broadcast(
ColorParser.of(
@@ -282,8 +282,8 @@ public class WarCommands {
}
// Join town into war
- if (isArgTown && town != null && !war.isTownInWar(town) && (asAdmin || canMayorJoin)) {
- side.addTown(town);
+ if (isArgTown && town != null && !war.isInWar(town) && (asAdmin || canMayorJoin)) {
+ side.add(town);
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().getPlayerNameColor(player));
Bukkit.broadcast(
ColorParser.of(
@@ -316,9 +316,9 @@ public class WarCommands {
}
// Join player into war
- if (isArgPlayer && targetPlayer != null && !war.isPlayerInWar(targetPlayer) && asAdmin) {
+ if (isArgPlayer && targetPlayer != null && !war.isInWar(targetPlayer) && asAdmin) {
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
- side.addPlayer(targetPlayer);
+ side.add(targetPlayer);
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
final Title warTitle = Title.title(
ColorParser.of("War")
@@ -367,10 +367,10 @@ public class WarCommands {
final Location targetLocation = targetPlayer.getLocation();
if (!location.getWorld().equals(targetLocation.getWorld())) continue;
if (location.distance(targetLocation) > 25D) continue;
- if (war.isPlayerInWar(targetPlayer)) continue;
+ if (war.isInWar(targetPlayer)) continue;
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
- side.addPlayer(targetPlayer);
+ side.add(targetPlayer);
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
final Title warTitle = Title.title(
ColorParser.of("War")
@@ -404,7 +404,7 @@ public class WarCommands {
if (town == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You are not in a town.").build());
- @Nullable Side side = war.getTownSide(town);
+ @Nullable Side side = war.getSide(town);
if (side == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You are not in that war.").build());
@@ -415,7 +415,7 @@ public class WarCommands {
// Has nation surrender permission
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resNation.getName() + ".").build());
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The nation of " + resNation.getName() + " has surrendered!").build());
- war.surrenderNation(resNation);
+ war.surrender(resNation);
} else if (resTown == null) {
// Cannot surrender nation involvement
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You cannot surrender for your nation.").build());
@@ -426,7 +426,7 @@ public class WarCommands {
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resTown.getName() + ".").build());
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The town of " + resTown.getName() + " has surrendered!").build());
war.cancelSieges(resTown);
- war.surrenderTown(resTown);
+ war.surrender(resTown);
} else {
// No perms
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You cannot surrender war for your town.").build());
@@ -447,26 +447,26 @@ public class WarCommands {
Town town = TownyAPI.getInstance().getTown(uuid);
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
- Side sideNation = war.getNationSide(nation);
- Side sideTown = war.getTownSide(town);
+ Side sideNation = war.getSide(nation);
+ Side sideTown = war.getSide(town);
Side sidePlayer = war.getPlayerSide(uuid);
if (isNation && sideNation != null) {
- sideNation.kickNation(nation);
+ sideNation.kick(nation);
p.sendMessage(ColorParser.of("Target yeeted.").build());
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
return;
}
if (isTown && sideTown != null) {
- sideTown.kickTown(town);
+ sideTown.kick(town);
p.sendMessage(ColorParser.of("Target yeeted.").build());
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
return;
}
if (isPlayer && sidePlayer != null) {
- sidePlayer.kickPlayer(player.getUniqueId());
+ sidePlayer.kick(player.getUniqueId());
p.sendMessage(ColorParser.of("Target yeeted.").build());
if (player.getPlayer() != null)
NameColorHandler.getInstance().calculatePlayerColors(player.getPlayer());
@@ -509,9 +509,9 @@ public class WarCommands {
for (Side side : war.getSides()) {
msg.append("\n%s".formatted(side.getName()));
msg.append("\n Score: %s".formatted(side.getScore()));
- msg.append("\n Nations: %s/%s".formatted(side.getNations().size(), side.getNations().size() + side.getSurrenderedNations().size()));
- msg.append("\n Towns: %s/%s".formatted(side.getTowns().size(), side.getTowns().size() + side.getSurrenderedTowns().size()));
- msg.append("\n Players: %s/%s".formatted(side.getPlayersIncludingOffline().size(), side.getPlayersIncludingOffline().size() + side.getSurrenderedPlayersIncludingOffline().size()));
+ msg.append("\n Nations: %s/%s".formatted(side.getNations().size(), side.getNations().size() + side.getNationsSurrendered().size()));
+ msg.append("\n Towns: %s/%s".formatted(side.getTowns().size(), side.getTowns().size() + side.getTownsSurrendered().size()));
+ msg.append("\n Players: %s/%s".formatted(side.getPlayersAll().size(), side.getPlayersAll().size() + side.getPlayersSurrendered().size()));
msg.append("\n");
}
diff --git a/src/main/java/com/github/alathra/alathranwars/config/ConfigHandler.java b/src/main/java/com/github/alathra/alathranwars/config/ConfigHandler.java
index 6d247ee..7c55218 100644
--- a/src/main/java/com/github/alathra/alathranwars/config/ConfigHandler.java
+++ b/src/main/java/com/github/alathra/alathranwars/config/ConfigHandler.java
@@ -2,30 +2,32 @@ package com.github.alathra.alathranwars.config;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.Reloadable;
-import com.github.milkdrinkers.Crate.Config;
+import com.github.milkdrinkers.crate.Config;
import javax.inject.Singleton;
/**
- * A class that generates/loads & provides access to a configuration file.
+ * A class that generates/loads {@literal &} provides access to a configuration file.
*/
@Singleton
public class ConfigHandler implements Reloadable {
- private final AlathranWars alathranWars;
+ private final AlathranWars plugin;
private Config cfg;
+ private Config databaseCfg;
/**
* Instantiates a new Config handler.
*
- * @param alathranWars the plugin instance
+ * @param plugin the plugin instance
*/
- public ConfigHandler(AlathranWars alathranWars) {
- this.alathranWars = alathranWars;
+ public ConfigHandler(AlathranWars plugin) {
+ this.plugin = plugin;
}
@Override
public void onLoad() {
- cfg = new Config("config", alathranWars.getDataFolder().getPath(), alathranWars.getResource("config.yml")); // Create a config file from the template in our resources folder
+ cfg = new Config("config", plugin.getDataFolder().getPath(), plugin.getResource("config.yml")); // Create a config file from the template in our resources folder
+ databaseCfg = new Config("database", plugin.getDataFolder().getPath(), plugin.getResource("database.yml"));
}
@Override
@@ -37,11 +39,20 @@ public class ConfigHandler implements Reloadable {
}
/**
- * Gets alathranWars config object.
+ * Gets main config object.
*
- * @return the alathranWars config object
+ * @return the config object
*/
public Config getConfig() {
return cfg;
}
+
+ /**
+ * Gets database config object.
+ *
+ * @return the config object
+ */
+ public Config getDatabaseConfig() {
+ return databaseCfg;
+ }
}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/Conflict.java b/src/main/java/com/github/alathra/alathranwars/conflict/Conflict.java
index afe1843..96496f4 100644
--- a/src/main/java/com/github/alathra/alathranwars/conflict/Conflict.java
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/Conflict.java
@@ -2,6 +2,42 @@ package com.github.alathra.alathranwars.conflict;
import com.github.alathra.alathranwars.enums.ConflictType;
-public class Conflict {
+import java.util.UUID;
+
+public abstract class Conflict implements IUnique {
private ConflictType conflictType;
+ private final UUID uuid;
+
+ public Conflict(UUID uuid) {
+ this.uuid = uuid;
+ }
+
+ /**
+ * @return conflict uuid
+ */
+ @Override
+ public UUID getUUID() {
+ return uuid;
+ }
+
+ /**
+ * Equals boolean.
+ *
+ * @param uuid the uuid
+ * @return the boolean
+ */
+ @Override
+ public boolean equals(UUID uuid) {
+ return getUUID().equals(uuid);
+ }
+
+ /**
+ * Equals boolean.
+ *
+ * @param conflict the conflict
+ * @return the boolean
+ */
+ public boolean equals(Conflict conflict) {
+ return conflict.getUUID().equals(uuid);
+ }
}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/IAssociatedWar.java b/src/main/java/com/github/alathra/alathranwars/conflict/IAssociatedWar.java
new file mode 100644
index 0000000..23f0f8a
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/IAssociatedWar.java
@@ -0,0 +1,18 @@
+package com.github.alathra.alathranwars.conflict;
+
+import com.github.alathra.alathranwars.conflict.war.War;
+
+public interface IAssociatedWar {
+ /**
+ * Gets the associated war with this object from the war uuid
+ * @return the associated war
+ */
+ War getWar();
+
+ /**
+ * Check whether a war is associated with this class
+ * @param war the war to compare with
+ * @return if the war is the one associated with this object
+ */
+ boolean equals(War war);
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/IUnique.java b/src/main/java/com/github/alathra/alathranwars/conflict/IUnique.java
new file mode 100644
index 0000000..fc0fbaa
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/IUnique.java
@@ -0,0 +1,27 @@
+package com.github.alathra.alathranwars.conflict;
+
+import java.util.UUID;
+
+public interface IUnique> {
+ UUID getUUID();
+
+ /**
+ * Equals boolean.
+ *
+ * @param uuid the uuid
+ * @return the boolean
+ */
+ default boolean equals(UUID uuid) {
+ return getUUID().equals(uuid);
+ }
+
+ /**
+ * Equals boolean.
+ *
+ * @param obj the object implementing IUnique
+ * @return the boolean
+ */
+ default boolean equals(T obj) {
+ return getUUID().equals(obj.getUUID());
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/AbstractBattleTeamManagement.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/AbstractBattleTeamManagement.java
new file mode 100644
index 0000000..5a8db82
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/AbstractBattleTeamManagement.java
@@ -0,0 +1,213 @@
+package com.github.alathra.alathranwars.conflict.battle;
+
+import com.github.alathra.alathranwars.conflict.war.War;
+import com.github.alathra.alathranwars.enums.battle.BattleSide;
+import com.github.alathra.alathranwars.events.battle.PlayerEnteredBattlefieldEvent;
+import com.github.alathra.alathranwars.events.battle.PlayerLeftBattlefieldEvent;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.entity.Player;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * Provides methods for handling all members of a Battle
+ */
+public abstract class AbstractBattleTeamManagement {
+ // SECTION Player management
+
+ private final List attackers = new ArrayList<>(); // A list of all players who are in the attackers team
+ private final List defenders = new ArrayList<>(); // A list of all players who are in the attackers team
+
+ /**
+ * Get all online players eligible to fight in the battle
+ * @param side battle side
+ * @return list of players
+ */
+ public List getPlayersOnline(BattleSide side) {
+ return switch (side) {
+ case ATTACKER -> attackers.stream()
+ .filter(OfflinePlayer::isOnline)
+ .map(OfflinePlayer::getPlayer)
+ .toList();
+ case DEFENDER -> defenders.stream()
+ .filter(OfflinePlayer::isOnline)
+ .map(OfflinePlayer::getPlayer)
+ .toList();
+ case SPECTATOR -> Bukkit.getOnlinePlayers().stream()
+ .map(OfflinePlayer::getPlayer)
+ .filter(p -> !attackers.contains(p) && !defenders.contains(p))
+ .toList();
+ };
+ }
+
+ /**
+ * Get all players eligible to fight in the battle
+ * @param side battle side
+ * @return list of players
+ */
+ public List getPlayers(BattleSide side) {
+ return switch (side) {
+ case ATTACKER -> attackers;
+ case DEFENDER -> defenders;
+ default -> List.of();
+ };
+ }
+
+ public void addPlayer(OfflinePlayer p, BattleSide side) {
+ switch (side) {
+ case ATTACKER -> attackers.add(p);
+ case DEFENDER -> defenders.add(p);
+ }
+ }
+
+ public void addPlayer(Player p, BattleSide side) { addPlayer(Bukkit.getOfflinePlayer(p.getUniqueId()), side); }
+
+ public void addPlayer(UUID uuid, BattleSide side) { addPlayer(Bukkit.getOfflinePlayer(uuid), side); }
+
+ public void removePlayer(OfflinePlayer p, BattleSide side) {
+ switch (side) {
+ case ATTACKER -> attackers.remove(p);
+ case DEFENDER -> defenders.remove(p);
+ }
+ }
+
+ public void removePlayer(Player p, BattleSide side) { removePlayer(p.getUniqueId(), side); }
+
+ public void removePlayer(UUID uuid, BattleSide side) { removePlayer(Bukkit.getOfflinePlayer(uuid), side); }
+
+ // Player info methods
+
+ public BattleSide getPlayerBattleSide(OfflinePlayer p) {
+ if (getPlayers(BattleSide.ATTACKER).contains(p))
+ return BattleSide.ATTACKER;
+
+ if (getPlayers(BattleSide.DEFENDER).contains(p))
+ return BattleSide.DEFENDER;
+
+ return BattleSide.SPECTATOR;
+ }
+
+ public BattleSide getPlayerBattleSide(Player p) {
+ return getPlayerBattleSide(p.getUniqueId());
+ }
+
+ public BattleSide getPlayerBattleSide(UUID uuid) {
+ return getPlayerBattleSide(Bukkit.getOfflinePlayer(uuid));
+ }
+
+ // Misc
+
+ /**
+ * Checks if the player is considered part of this battle
+ * @param p the player
+ * @return yes if they have joined the battle
+ */
+ public boolean isPlayerParticipating(OfflinePlayer p) {
+ return getPlayers(BattleSide.ATTACKER).contains(p) || getPlayers(BattleSide.DEFENDER).contains(p);
+ }
+
+ /**
+ * Checks if the player is considered part of this battle
+ * @param p the player
+ * @return yes if they have joined the battle
+ */
+ public boolean isPlayerParticipating(Player p) {
+ return isPlayerParticipating(p.getUniqueId());
+ }
+
+ /**
+ * Checks if the player is considered part of this battle
+ * @param uuid the player uuid
+ * @return yes if they have joined the battle
+ */
+ public boolean isPlayerParticipating(UUID uuid) {
+ return isPlayerParticipating(Bukkit.getOfflinePlayer(uuid));
+ }
+
+ // SECTION Active player management
+
+ private final List activeAttackers = new ArrayList<>(); // Players in the battle zone
+ private final List activeDefenders = new ArrayList<>(); // Players in the battle zone
+ private final List activeSpectators = new ArrayList<>(); // Players in the battle zone
+
+ /**
+ * Get all online players within the battlefield.
+ * @param side battle side
+ * @return list of players
+ */
+ public List getActivePlayers(BattleSide side) {
+ return switch (side) {
+ case ATTACKER -> activeAttackers;
+ case DEFENDER -> activeDefenders;
+ case SPECTATOR -> activeSpectators;
+ };
+ }
+
+ private void addActivePlayer(Player p, BattleSide side) {
+ switch (side) {
+ case ATTACKER -> activeAttackers.add(p);
+ case DEFENDER -> activeDefenders.add(p);
+ case SPECTATOR -> activeSpectators.add(p);
+ };
+ }
+
+ private void removeActivePlayer(Player p, BattleSide side) {
+ switch (side) {
+ case ATTACKER -> activeAttackers.remove(p);
+ case DEFENDER -> activeDefenders.remove(p);
+ case SPECTATOR -> activeSpectators.remove(p);
+ };
+ }
+
+ public void calculateBattlefieldPlayers(Location location, int range, War war, Battle battle) {
+ final List previousAttackersOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.ATTACKER));
+ final List previousDefendersOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.DEFENDER));
+ final List previousSpectatorsOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.SPECTATOR));
+
+ activeAttackers.clear();
+ activeSpectators.addAll(getPlayersWithinRange(BattleSide.ATTACKER, location, range));
+
+ activeDefenders.clear();
+ activeSpectators.addAll(getPlayersWithinRange(BattleSide.DEFENDER, location, range));
+
+ activeSpectators.clear();
+ activeSpectators.addAll(getPlayersWithinRange(BattleSide.SPECTATOR, location, range));
+
+ // Attackers
+ emitLeaving(BattleSide.ATTACKER, previousAttackersOnBattlefield, war, battle); // Emit Leaving attackers events
+ emitEntering(BattleSide.ATTACKER, previousAttackersOnBattlefield, war, battle); // Emit Entering attackers events
+
+ // Defenders
+ emitLeaving(BattleSide.DEFENDER, previousDefendersOnBattlefield, war, battle); // Emit Leaving defenders events
+ emitEntering(BattleSide.DEFENDER, previousDefendersOnBattlefield, war, battle); // Emit Entering defenders events
+
+ // Spectators
+ emitLeaving(BattleSide.SPECTATOR, previousSpectatorsOnBattlefield, war, battle); // Emit Leaving spectators events
+ emitEntering(BattleSide.SPECTATOR, previousSpectatorsOnBattlefield, war, battle); // Emit Entering spectators events
+ }
+
+ private List getPlayersWithinRange(BattleSide battleSide, Location location, int range) {
+ return getPlayersOnline(battleSide).stream()
+ .filter(OfflinePlayer::isOnline)
+ .filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
+ .filter(p -> location.distance(p.getLocation()) < range)
+ .toList();
+ }
+
+ private void emitEntering(BattleSide battleSide, List previousPlayers, War war, Battle battle) {
+ getActivePlayers(battleSide).stream()
+ .filter(p -> p.isConnected() && !previousPlayers.contains(p))
+ .collect(Collectors.toSet())
+ .forEach(p -> new PlayerEnteredBattlefieldEvent(p, war, battle, battleSide).callEvent());
+ }
+
+ private void emitLeaving(BattleSide battleSide, List previousPlayers, War war, Battle battle) {
+ previousPlayers.stream()
+ .filter(p -> p.isConnected() && !getActivePlayers(battleSide).contains(p))
+ .collect(Collectors.toSet())
+ .forEach(p -> new PlayerLeftBattlefieldEvent(p, war, battle, battleSide).callEvent());
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/Battle.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/Battle.java
index 763569f..e7524e2 100644
--- a/src/main/java/com/github/alathra/alathranwars/conflict/battle/Battle.java
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/Battle.java
@@ -1,40 +1,58 @@
package com.github.alathra.alathranwars.conflict.battle;
+import com.github.alathra.alathranwars.conflict.IUnique;
+import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.enums.battle.BattleType;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
-import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.ApiStatus;
-import java.util.UUID;
+public interface Battle extends IUnique {
+ War war = null;
-public interface Battle {
- void start(); // Initiates battle
-
- void stop(); // Ends battle
-
- void resume(); // Resume battle after server restart or plugin reload
-
- void attackersWin(BattleVictoryReason reason); // A Attacker victory
-
- void defendersWin(BattleVictoryReason reason); // A Defender victory
-
- void equalWin(BattleVictoryReason reason); // A Draw
-
-
- UUID uuid = null; // Battle UUID
-
- default @NotNull UUID getUUID() {
- return uuid;
+ default War getWar() {
+ return war;
}
/**
- * Equals boolean.
- *
- * @param uuid the uuid
- * @return the boolean
+ * Starts the battle
*/
- default boolean equals(UUID uuid) {
- return getUUID().equals(uuid);
- }
+ @ApiStatus.Internal
+ void start();
+
+ /**
+ * Resumes the battle (after a server restart e.t.c.)
+ */
+ @ApiStatus.Internal
+ void resume();
+
+ /**
+ * Stops the battle
+ *
+ * Internal stop method for battles which triggers cleanup methods
+ */
+ @ApiStatus.Internal
+ void stop(); // Ends battle
+
+ /**
+ * Stop a battle in favor of the attackers
+ *
+ * @param reason what triggered the end
+ */
+ void attackersWin(BattleVictoryReason reason); // A Attacker victory
+
+ /**
+ * Stop a battle in favor of the defenders
+ *
+ * @param reason what triggered the end
+ */
+ void defendersWin(BattleVictoryReason reason); // A Defender victory
+
+ /**
+ * End a battle in favor of no one
+ *
+ * @param reason what triggered the end
+ */
+ void equalWin(BattleVictoryReason reason); // A Draw
/**
* Equals boolean.
@@ -42,7 +60,7 @@ public interface Battle {
* @param battle the battle
* @return the boolean
*/
- default boolean equals(@NotNull Battle battle) {
+ default boolean equals(Battle battle) {
return getUUID().equals(battle.getUUID());
}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/betterbeam/BetterBeam.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/betterbeam/BetterBeam.java
new file mode 100644
index 0000000..b59aaf5
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/betterbeam/BetterBeam.java
@@ -0,0 +1,98 @@
+package com.github.alathra.alathranwars.conflict.battle.beam.betterbeam;
+
+public class BetterBeam {
+ /*BetterBeam() {
+ PacketContainer spawnPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
+ PacketContainer metadataPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
+ PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
+
+ // Required fields
+ // EndCrystal entity
+ // Squid entity (Made invisible)
+ AlathranWars.getProtocolLibHook().getProtocolManager()
+
+ PacketContainer spawnCrystalPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
+ PacketContainer spawnCrystalPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
+
+ ProtocolManager manager = AlathranWars.getProtocolLibHook().getProtocolManager();
+
+ Entity endcrystal;
+
+ endcrystal.getI
+ spawnPacket.getStructures()
+
+
+
+ }
+
+ private void spawnEntity(Location location, Vector vector, EntityType type) {
+ int entityId = 10000;
+
+ PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
+
+ // Crucial data, do not remove
+ packet.getIntegers().write(0, entityId);
+ packet.getUUIDs().write(0, UUID.randomUUID());
+ packet.getEntityTypeModifier().write(0, type);
+
+ packet.getDoubles()
+ .write(0, location.getX())
+ .write(1, location.getY())
+ .write(2, location.getZ());
+ // -- section end --
+
+ // Pitch and yaw, remove this code section if you want to default to 0
+
+ packet.
+ packet.getIntegers()
+ .write(4, (int) (location.getPitch() * 256.0F / 360.0F))
+ .write(5, (int) (location.getYaw() * 256.0F / 360.0F));
+
+ // -- section end --
+
+ // Send the packet to all players
+ try {
+ for(Player player : Bukkit.getOnlinePlayers()) {
+ ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ private void spawnLivingEntity(Location location, Vector vector, EntityType type) {
+ int entityId = 10000;
+
+ PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
+
+ // Crucial data, do not remove
+ packet.getIntegers().write(0, entityId);
+ packet.getUUIDs().write(0, UUID.randomUUID());
+ packet.getIntegers().write(1, (int) type.getTypeId()); // getTypeId is deprecated, you can find the actual IDs on wiki.vg/Protocol
+
+ packet.getDoubles()
+ .write(0, location.getX())
+ .write(1, location.getY())
+ .write(2, location.getZ());
+ // -- section end --
+
+ // Pitch and yaw, remove this code section if you want to default to 0
+ packet.getBytes()
+ .write(4, (byte) (location.getYaw() * 256.0F / 360.0F)) // yaw
+ .write(5, (byte) (location.getPitch() * 256.0F / 360.0F)) // pitch
+ .write(5, (byte) (location.getYaw() * 256.0F / 360.0F)); // head yaw
+
+ // -- section end --
+
+ // Send the packet to all players
+ try {
+ for(Player player : Bukkit.getOnlinePlayers()) {
+ ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }*/
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseManager.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseManager.java
new file mode 100644
index 0000000..acba8de
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseManager.java
@@ -0,0 +1,9 @@
+package com.github.alathra.alathranwars.conflict.battle.phase;
+
+import java.time.Instant;
+
+public class BattlePhaseManager & IBattlePhase> extends BattlePhaseManagerImpl {
+ public BattlePhaseManager(T phase, int progress, Instant startTime) {
+ super(phase, progress, startTime);
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseManagerImpl.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseManagerImpl.java
new file mode 100644
index 0000000..3463df7
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseManagerImpl.java
@@ -0,0 +1,57 @@
+package com.github.alathra.alathranwars.conflict.battle.phase;
+
+import java.time.Duration;
+import java.time.Instant;
+
+public abstract class BattlePhaseManagerImpl & IBattlePhase> implements IBattlePhaseManager {
+ private T phase;
+ private int progress;
+ private Instant startTime;
+
+ public BattlePhaseManagerImpl(T phase, int progress, Instant startTime) {
+ this.phase = phase;
+ this.progress = progress;
+ this.startTime = startTime;
+ }
+
+ @Override
+ public T get() {
+ return phase;
+ }
+
+ @Override
+ public void set(T phase) throws BattlePhaseSwitchException {
+ this.phase = phase;
+ }
+
+ @Override
+ public int getProgress() {
+ return progress;
+ }
+
+ @Override
+ public void setProgress(int val) {
+ if (val > 100) { // TODO Use phase progress max here
+ val = 100;
+ } else if (val < 0) {
+ val = 0;
+ }
+
+ progress = val;
+ }
+
+ @Override
+ public Instant getStartTime() {
+ return startTime;
+ }
+
+ @Override
+ public void setStartTime(Instant instant) {
+ startTime = instant;
+ }
+
+ @Override
+ public Duration getElapsedTime() {
+ return Duration.between(Instant.now(), getStartTime());
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseSwitchException.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseSwitchException.java
new file mode 100644
index 0000000..f4e379e
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/BattlePhaseSwitchException.java
@@ -0,0 +1,7 @@
+package com.github.alathra.alathranwars.conflict.battle.phase;
+
+public class BattlePhaseSwitchException extends RuntimeException {
+ public BattlePhaseSwitchException(String message) {
+ super(message);
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/IBattlePhase.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/IBattlePhase.java
new file mode 100644
index 0000000..5be667f
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/IBattlePhase.java
@@ -0,0 +1,100 @@
+package com.github.alathra.alathranwars.conflict.battle.phase;
+
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Arrays;
+
+/**
+ * Used to implement common methods in battle phase enums
+ * @param the Enum
+ */
+public interface IBattlePhase & IBattlePhase> {
+ int getPhaseIdentifier();
+
+ /**
+ * Uses {@link #next(Enum)} to get the next phase
+ * @return a phase enum value
+ * @throws BattlePhaseSwitchException Thrown if no next phase can be found
+ */
+ T next() throws BattlePhaseSwitchException;
+
+ /**
+ * Uses {@link #previous(Enum)} to get the previous phase
+ * @return a phase enum value
+ * @throws BattlePhaseSwitchException Thrown if no previous phase can be found
+ */
+ T previous() throws BattlePhaseSwitchException;
+
+ /**
+ * Get the next phase after the provided one
+ * @param phase a phase enum value
+ * @return a phase enum value
+ * @throws BattlePhaseSwitchException Thrown if no next phase can be found
+ */
+ default T next(T phase) throws BattlePhaseSwitchException {
+ final int currentPhase = phase.getPhaseIdentifier();
+
+ // Find the next enum constant by incrementing until a valid enum constant is found
+ int increment = 0;
+ for (int i = 1; i < 6; i++) {
+ if (fromIdentifier(currentPhase + i) != null) {
+ increment = i;
+ break;
+ }
+ }
+
+ // Failed to find new phase
+ if (increment == 0)
+ throw new BattlePhaseSwitchException("No later phase could be found.");
+
+ return fromIdentifier(currentPhase + increment);
+ }
+
+ /**
+ * Get the previous phase to the provided one
+ * @param phase a phase enum value
+ * @return a phase enum value
+ * @throws BattlePhaseSwitchException Thrown if no previous phase can be found
+ */
+ default T previous(T phase) throws BattlePhaseSwitchException {
+ final int currentPhase = phase.getPhaseIdentifier();
+ if (currentPhase - 1 < 1)
+ throw new BattlePhaseSwitchException("No previous phase could be found.");
+
+ // Find the previous enum constant by decrementing until a valid enum constant is found
+ int decrement = 0;
+ for (int i = 1; i < 6; i++) {
+ if (fromIdentifier(currentPhase - i) != null) {
+ decrement = i;
+ break;
+ }
+ }
+
+ // Failed to find new phase
+ if (decrement == 0)
+ throw new BattlePhaseSwitchException("No previous phase could be found.");
+
+ return fromIdentifier(currentPhase - decrement);
+ }
+
+ /**
+ * Get a phase from the phase identifier
+ * @param identifier the phase identifier
+ * @return a phase enum value or null if none was found
+ */
+ @Nullable
+ default T fromIdentifier(final int identifier) {
+ if (identifier < 1)
+ return null;
+
+ return Arrays.stream(getDeclaringClass().getEnumConstants())
+ .filter(phase -> phase.getPhaseIdentifier() == identifier)
+ .findFirst()
+ .orElse(null);
+ }
+
+ /**
+ * Don't override this method, it is implemented in all enums by default.
+ */
+ Class getDeclaringClass();
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/IBattlePhaseManager.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/IBattlePhaseManager.java
new file mode 100644
index 0000000..2623d02
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/IBattlePhaseManager.java
@@ -0,0 +1,70 @@
+package com.github.alathra.alathranwars.conflict.battle.phase;
+
+import org.jetbrains.annotations.ApiStatus;
+
+import java.time.Duration;
+import java.time.Instant;
+
+public interface IBattlePhaseManager & IBattlePhase> {
+ /**
+ * Get the current battle phase
+ * @return the phase
+ */
+ T get();
+
+ /**
+ * Set the current battle phase
+ * @param phase the phase
+ * @throws BattlePhaseSwitchException Thrown if unable to switch phase
+ */
+ @ApiStatus.Internal
+ void set(T phase) throws BattlePhaseSwitchException;
+
+ /**
+ * Goes to the next battle phase if possible
+ * @throws BattlePhaseSwitchException Thrown if unable to switch phase
+ */
+ default T next() throws BattlePhaseSwitchException {
+ return get().next();
+ };
+
+ /**
+ * Goes to the previous battle phase if possible
+ * @throws BattlePhaseSwitchException Thrown if unable to switch phase
+ */
+ default T previous() throws BattlePhaseSwitchException {
+ return get().previous();
+ };
+
+ /**
+ * Get the current phase progress
+ * @return integer from 0 to 100
+ */
+ int getProgress();
+
+ /**
+ * Set the current phase progress
+ * @param val integer from 0 to 100
+ */
+ @ApiStatus.Internal
+ void setProgress(int val);
+
+ /**
+ * Get the time at which this phase started
+ * @return the instant at which this phase started
+ */
+ Instant getStartTime();
+
+ /**
+ * Set the time of when this phase started
+ * @param instant the instant at which this phase started
+ */
+ @ApiStatus.Internal
+ void setStartTime(Instant instant);
+
+ /**
+ * Get the duration between now and when phase started
+ * @return duration between now and start time
+ */
+ Duration getElapsedTime();
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/TestBattlePhase.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/TestBattlePhase.java
new file mode 100644
index 0000000..db58d10
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/phase/TestBattlePhase.java
@@ -0,0 +1,36 @@
+package com.github.alathra.alathranwars.conflict.battle.phase;
+
+public enum TestBattlePhase implements IBattlePhase {
+ INITIAL(1),
+ FIGHTING(2),
+ END(3);
+
+ // Identifiers start at 1, used to traverse between stages
+ private final int phaseIdentifier;
+
+ TestBattlePhase(int phaseIdentifier) {
+ this.phaseIdentifier = phaseIdentifier;
+ }
+
+ public int getPhaseIdentifier() {
+ return phaseIdentifier;
+ }
+
+ public TestBattlePhase next() throws BattlePhaseSwitchException {
+ return next(fromIdentifier(getPhaseIdentifier()));
+ }
+
+ public TestBattlePhase previous() throws BattlePhaseSwitchException {
+ return previous(fromIdentifier(getPhaseIdentifier()));
+ }
+
+ @Override
+ public TestBattlePhase next(TestBattlePhase phase) throws BattlePhaseSwitchException {
+ return IBattlePhase.super.next(phase);
+ }
+
+ @Override
+ public TestBattlePhase previous(TestBattlePhase phase) throws BattlePhaseSwitchException {
+ return IBattlePhase.super.previous(phase);
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/BattleProgressManager.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/BattleProgressManager.java
new file mode 100644
index 0000000..fa76ea2
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/BattleProgressManager.java
@@ -0,0 +1,7 @@
+package com.github.alathra.alathranwars.conflict.battle.progress;
+
+public class BattleProgressManager extends BattleProgressManagerImpl {
+ public BattleProgressManager(int progress, int maxProgress) {
+ super(progress, maxProgress);
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/BattleProgressManagerImpl.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/BattleProgressManagerImpl.java
new file mode 100644
index 0000000..2bad755
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/BattleProgressManagerImpl.java
@@ -0,0 +1,32 @@
+package com.github.alathra.alathranwars.conflict.battle.progress;
+
+public abstract class BattleProgressManagerImpl implements IBattleProgressManager {
+ private int progress;
+ private final int maxProgress;
+
+ public BattleProgressManagerImpl(int progress, int maxProgress) {
+ this.progress = progress;
+ this.maxProgress = maxProgress;
+ }
+
+ @Override
+ public int get() {
+ return progress;
+ }
+
+ @Override
+ public void set(int val) {
+ if (val > getMax()) {
+ val = getMax();
+ } else if (val < 0) {
+ val = 0;
+ }
+
+ progress = val;
+ }
+
+ @Override
+ public int getMax() {
+ return maxProgress;
+ }
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/IBattleProgressManager.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/IBattleProgressManager.java
new file mode 100644
index 0000000..40c66d1
--- /dev/null
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/progress/IBattleProgressManager.java
@@ -0,0 +1,24 @@
+package com.github.alathra.alathranwars.conflict.battle.progress;
+
+import org.jetbrains.annotations.ApiStatus;
+
+public interface IBattleProgressManager {
+ /**
+ * Get the current battle progress
+ * @return the current progress
+ */
+ int get();
+
+ /**
+ * Set the current battle progress
+ * @param val the new progress (Cannot be higher than max or lower than 0)
+ */
+ @ApiStatus.Internal
+ void set(int val);
+
+ /**
+ * Get the current battles maximum progress
+ * @return the maximum progress this battle can reach
+ */
+ int getMax();
+}
diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/raid/Raid.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/raid/Raid.java
index b484de5..48d0649 100644
--- a/src/main/java/com/github/alathra/alathranwars/conflict/battle/raid/Raid.java
+++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/raid/Raid.java
@@ -29,608 +29,617 @@ import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-public class Raid implements Battle {
- public static final Duration RAID_DURATION = Duration.ofMinutes(60);
- public static final int MAX_RAID_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
- public static final int MAX_RAID_PROGRESS = 60 * 10 * MAX_RAID_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second
- public static final Duration ATTACKERS_MUST_TOUCH_END = Duration.ofMinutes(40); // If point is not touched in this much time, defenders win
- public static final Duration ATTACKERS_MUST_TOUCH_REVERT = Duration.ofSeconds(60); // If point is not touched in this much time, raid progress begins reverting
- public static final int BATTLEFIELD_RANGE = 500;
- public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
- public static final int BATTLEFIELD_START_MIN_RANGE = 75;
- public static final double SIEGE_VICTORY_MONEY = 2500.0;
-
- private final @NotNull UUID uuid;
- private final Set attackers = new HashSet<>(); // Players inside battlefield
- private final Set defenders = new HashSet<>(); // Players inside battlefield
- private final Set attackerPlayers = new HashSet<>();
- private final Set defenderPlayers = new HashSet<>();
- private final Set attackerPlayersIncludingOffline = new HashSet<>();
- private final Set defenderPlayersIncludingOffline = new HashSet<>();
- private @NotNull War war; // War which raid belongs to
- private Instant endTime;
- private int raidProgress = 0;
- private Instant lastTouched;
- private RaidRunnable raidRunnable;
- private Town town; // Town of the raid
- private boolean side1AreAttackers; // bool of if side1 being attacker
- private OfflinePlayer raidLeader;
- private @Nullable TownBlock homeBlock = null;
- private @Nullable Location townSpawn = null;
- private @Nullable BossBar activeBossBar = null;
- private boolean stopped = false; // Used to track if the raid has been already deleted
-
- public Raid(final @NotNull War war, final Town town, Player raidLeader) {
- uuid = UUID.randomUUID();
-
- endTime = Instant.now().plus(RAID_DURATION);
- lastTouched = Instant.now();
-
- this.war = war;
- this.town = town;
- this.raidLeader = raidLeader;
-
- side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
-
- if (getSide1AreAttackers()) {
- attackerPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
- defenderPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
- } else {
- attackerPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
- defenderPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
- }
- calculateOnlinePlayers();
- }
-
- // Construct when loading from DB
- public Raid(War war, @NotNull UUID uuid, Town town, OfflinePlayer raidLeader, Instant endTime, Instant lastTouched, int raidProgress, Set attackerPlayersIncludingOffline, Set defenderPlayersIncludingOffline) {
- this.war = war;
- this.uuid = uuid;
- this.town = town;
- this.raidLeader = raidLeader;
- this.endTime = endTime;
- this.lastTouched = lastTouched;
- this.raidProgress = raidProgress;
- this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline);
- this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline);
-
- side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
-
- calculateOnlinePlayers();
- }
-
- /**
- * Starts a raid
- */
- public void start() {
- raidRunnable = new RaidRunnable(this);
- if (!war.isEventWar())
- AlathranWars.econ.withdrawPlayer(raidLeader, SIEGE_VICTORY_MONEY);
-
- final Title.Times times = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
- final Title defTitle = Title.title(
- ColorParser.of("")
- .parseMinimessagePlaceholder("town", town.getName())
- .build(),
- ColorParser.of("Is under raid, defend!")
- .build(),
- times
- );
- final Title attTitle = Title.title(
- ColorParser.of("")
- .parseMinimessagePlaceholder("town", town.getName())
- .build(),
- ColorParser.of("Has been put to raid, attack!")
- .build(),
- times
- );
-
- final List soundList = List.of(
- Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
- Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
- Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
- Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
- );
-
- getDefenderPlayers().forEach(player -> {
- player.showTitle(defTitle);
- player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
- });
-
- getAttackerPlayers().forEach(player -> {
- player.showTitle(attTitle);
- player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
- });
- }
-
- /**
- * Resumes a raid (after a server restart e.t.c.)
- */
- public void resume() {
- raidRunnable = new RaidRunnable(this, getRaidProgress());
- }
-
- /**
- * Stops a raid
- */
- public void stop() {
- if (stopped) return;
- stopped = true;
- raidRunnable.cancel();
-// DatabaseQueries.deleteRaid(this); // TODO Delete raid
- war.removeRaid(this);
- }
-
- public void attackersWin(BattleVictoryReason reason) {
- if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
-
- if (!war.isEventWar()) {
- AlathranWars.econ.depositPlayer(raidLeader, SIEGE_VICTORY_MONEY);
- double amt;
-
- if (town.getAccount().getHoldingBalance() > 10000.0) {
- amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
- town.getAccount().withdraw(amt, "Raid Defeat");
- } else {
- town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Raid Defeat");
- amt = SIEGE_VICTORY_MONEY;
- }
-
- AlathranWars.econ.depositPlayer(raidLeader, amt);
- }
-
- if (side1AreAttackers) {
- war.getSide1().addScore(50);
- war.getSide2().addScore(5);
- } else {
- war.getSide1().addScore(5);
- war.getSide2().addScore(50);
- }
-
- new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
-
- stop();
-
- if (!war.isEventWar()) {
- Side townSide = getWar().getTownSide(town);
- Side attackerSide = getAttackerSide();
-
- if (attackerSide.equals(townSide)) {
- if (townSide.isTownSurrendered(town))
- war.unsurrenderTown(town);
- } else {
- if (!townSide.isTownSurrendered(town))
- war.surrenderTown(town);
- }
- }
- }
-
- public void defendersWin(BattleVictoryReason reason) {
- if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
-
- if (!war.isEventWar())
- town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Raid Victory");
-
- if (side1AreAttackers) {
- war.getSide2().addScore(10);
- } else {
- war.getSide1().addScore(10);
- }
-
- new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
-
- stop();
- }
-
- /**
- * No winner declared
- */
- public void equalWin(BattleVictoryReason reason) {
- if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
-
- new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
-
- stop();
- }
-
- @NotNull
- public Instant getLastTouched() {
- return lastTouched;
- }
-
- public void setLastTouched(Instant lastTouched) {
- this.lastTouched = lastTouched;
- }
-
- public int getRaidProgress() {
- return raidProgress;
- }
-
- public void setRaidProgress(int raidProgress) {
- if (raidProgress < 0) {
- raidProgress = 0;
- } else if (raidProgress > MAX_RAID_PROGRESS) {
- raidProgress = MAX_RAID_PROGRESS;
- }
- this.raidProgress = raidProgress;
- }
-
- public float getRaidProgressPercentage() {
- return (getRaidProgress() * 1.0f) / MAX_RAID_PROGRESS;
- }
-
- @NotNull
- public War getWar() {
- return war;
- }
-
- public void setWar(final War war) {
- this.war = war;
- }
-
- @NotNull
- public Town getTown() {
- return town;
- }
-
- public void setTown(final Town town) {
- this.town = town;
- }
-
- /**
- * Gets attacker name string
- */
- @NotNull
- public Side getAttackerSide() {
- return side1AreAttackers ? war.getSide1() : war.getSide2();
- }
-
- /**
- * Gets defender name string
- */
- @NotNull
- public Side getDefenderSide() {
- return side1AreAttackers ? war.getSide2() : war.getSide1();
- }
-
- // SECTION Display Bar
-
- public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) {
- if (activeBossBar == null)
- createNewDisplayBar();
-
- for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
- p.hideBossBar(activeBossBar);
- }
-
- for (@Nullable Player p : this.getPlayersOnBattlefield()) {
- if (p != null)
- p.showBossBar(activeBossBar);
- }
-
- final String color = switch (progressDirection) {
- case UP -> {
- if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
- activeBossBar.color(BossBar.Color.RED);
- yield "";
- } else {
- activeBossBar.color(BossBar.Color.BLUE);
- yield "";
- }
- }
- case CONTESTED -> {
- activeBossBar.color(BossBar.Color.YELLOW);
- yield "";
- }
- case UNCONTESTED -> {
- activeBossBar.color(BossBar.Color.WHITE);
- yield "";
- }
- case DOWN -> {
- if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
- activeBossBar.color(BossBar.Color.BLUE);
- yield "";
- } else {
- activeBossBar.color(BossBar.Color.RED);
- yield "";
- }
- }
- };
-
- if (Instant.now().isBefore(getEndTime())) {
- activeBossBar.name(
- ColorParser.of("Capture Progress: %s