From 862abd302b40a21691529d9bfa1dbb44dd061dd5 Mon Sep 17 00:00:00 2001 From: Loving11ish Date: Tue, 26 Nov 2024 03:10:40 +0000 Subject: [PATCH 1/2] Updated GitHub repository. Added new `messages.yml`. Massive recode. Added 1.21+ support. Added world-name to location settings. Changed plugin version to `2.6.0`. --- .mvn/wrapper/maven-wrapper.properties | 19 + jitpack.yml | 4 + mvnw | 259 +++++++++++ mvnw.cmd | 149 ++++++ pom.xml | 109 ++++- .../RedLightGreenLight.java | 428 +++++++++++++----- .../commands/CommandManager.java | 164 ++++++- .../commands/ConsoleCommand.java | 2 +- .../commands/consolecommands/ConsoleHelp.java | 40 +- .../consolecommands/ConsoleJoinAll.java | 12 +- .../consolecommands/ConsoleLeaveAll.java | 8 +- .../consolecommands/ConsoleReload.java | 29 +- .../commands/subcommands/Help.java | 41 +- .../commands/subcommands/JoinAll.java | 28 +- .../commands/subcommands/JoinGame.java | 17 +- .../commands/subcommands/LeaveAll.java | 16 +- .../commands/subcommands/LeaveGame.java | 22 +- .../commands/subcommands/Reload.java | 45 +- .../events/PlayerCommand.java | 8 +- .../events/PlayerHungerChange.java | 4 +- .../redlightgreenlight/events/PlayerJoin.java | 19 +- .../redlightgreenlight/events/PlayerMove.java | 80 ++-- .../redlightgreenlight/events/PlayerQuit.java | 11 +- .../externalhooks/PlugManXAPI.java | 23 - .../files/MessagesFileManager.java | 64 +++ .../managers/filemanagers/ConfigManager.java | 259 +++++++++++ .../filemanagers/MessagesManager.java | 263 +++++++++++ .../tasks/OnlinePlayerTasks.java | 13 + .../updatesystem/JoinEvent.java | 14 +- .../updatesystem/UpdateChecker.java | 14 +- .../redlightgreenlight/utils/ColorUtils.java | 33 +- .../utils/CountDownTasksUtils.java | 68 ++- .../redlightgreenlight/utils/GameManager.java | 164 +++---- .../utils/MessageUtils.java | 107 +++++ .../utils/PlayerInventoryHandler.java | 10 +- .../utils/ReloadingUtils.java | 23 + .../utils/VersionCheckerUtils.java | 37 +- .../versionsystems/ServerVersion.java | 65 +++ src/main/resources/config.yml | 177 ++------ src/main/resources/messages.yml | 91 ++++ src/main/resources/plugin.yml | 8 + 41 files changed, 2269 insertions(+), 678 deletions(-) create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 jitpack.yml create mode 100755 mvnw create mode 100644 mvnw.cmd delete mode 100644 src/main/java/me/loving11ish/redlightgreenlight/externalhooks/PlugManXAPI.java create mode 100644 src/main/java/me/loving11ish/redlightgreenlight/files/MessagesFileManager.java create mode 100644 src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/ConfigManager.java create mode 100644 src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java create mode 100644 src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java create mode 100644 src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java create mode 100644 src/main/java/me/loving11ish/redlightgreenlight/utils/ReloadingUtils.java create mode 100644 src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java create mode 100644 src/main/resources/messages.yml diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000..663d2f8 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,4 @@ +jdk: + - openjdk11 +install: + - ./mvnw install -DskipTests \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..19529dd --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml index 05545d1..3f87c59 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.loving11ish RedLightGreenLight - 2.5.4 + 2.6.0-ALPHA-01 jar RedLightGreenLight @@ -20,29 +20,56 @@ package + + + io.takari + maven + 0.7.7 + + + + wrapper + + + + + org.apache.maven.plugins maven-compiler-plugin - 3.11.0 + 3.13.0 ${java.version} ${java.version} + org.apache.maven.plugins maven-shade-plugin - 3.5.0 + 3.6.0 ${project.build.directory}/dependency-reduced-pom.xml io.papermc.lib - me.loving11ish.redlightgreenlight.paperlib + me.loving11ish.redlightgreenlight.libs.paperlib com.tcoded.folialib - me.loving11ish.redlightgreenlight.folialib + me.loving11ish.redlightgreenlight.libs.folialib + + + net.kyori + me.loving11ish.redlightgreenlight.libs.adventure + + + org.apache.commons + me.loving11ish.redlightgreenlight.libs.apache + + + com.google.gson + me.loving11ish.redlightgreenlight.libs.gson @@ -55,6 +82,7 @@ + @@ -81,10 +109,14 @@ papermc https://papermc.io/repo/repository/maven-public/ - - PlugMan - https://raw.githubusercontent.com/TheBlackEntity/PlugMan/repository/ + jitpack.io + https://jitpack.io + + + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ @@ -92,26 +124,69 @@ org.spigotmc spigot-api - 1.20.2-R0.1-SNAPSHOT + 1.16.5-R0.1-SNAPSHOT provided + + + + commons-codec + commons-codec + 1.17.0 + compile + - com.tcoded + org.apache.commons + commons-lang3 + 3.15.0 + compile + + + + + org.jetbrains + annotations + 24.1.0 + provided + + + + com.google.code.gson + gson + 2.10 + compile + + + + net.kyori + adventure-api + 4.17.0 + compile + + + net.kyori + adventure-platform-bukkit + 4.3.4 + + + net.kyori + adventure-text-minimessage + 4.17.0 + compile + + + + com.github.technicallycoded FoliaLib - 0.3.0 + 0.4.3 compile + io.papermc paperlib 1.0.8 compile - - com.rylinaux - PlugMan - 2.3.3 - provided - diff --git a/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java b/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java index 585a820..3d52675 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java @@ -1,16 +1,20 @@ package me.loving11ish.redlightgreenlight; -import com.rylinaux.plugman.api.PlugManAPI; import com.tcoded.folialib.FoliaLib; +import com.tcoded.folialib.wrapper.task.WrappedTask; import io.papermc.lib.PaperLib; import me.loving11ish.redlightgreenlight.commands.CommandManager; import me.loving11ish.redlightgreenlight.events.*; -import me.loving11ish.redlightgreenlight.externalhooks.PlugManXAPI; +import me.loving11ish.redlightgreenlight.files.MessagesFileManager; +import me.loving11ish.redlightgreenlight.managers.filemanagers.ConfigManager; +import me.loving11ish.redlightgreenlight.managers.filemanagers.MessagesManager; +import me.loving11ish.redlightgreenlight.tasks.OnlinePlayerTasks; import me.loving11ish.redlightgreenlight.updatesystem.JoinEvent; import me.loving11ish.redlightgreenlight.updatesystem.UpdateChecker; import me.loving11ish.redlightgreenlight.utils.*; +import me.loving11ish.redlightgreenlight.versionsystems.ServerVersion; +import net.kyori.adventure.platform.bukkit.BukkitAudiences; import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.plugin.PluginDescriptionFile; @@ -19,166 +23,251 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.concurrent.TimeUnit; +@SuppressWarnings("unused") public final class RedLightGreenLight extends JavaPlugin { - ConsoleCommandSender console = Bukkit.getConsoleSender(); + private final PluginDescriptionFile pluginInfo = getDescription(); + private final String pluginVersion = pluginInfo.getVersion(); - private PluginDescriptionFile pluginInfo = getDescription(); - private String pluginVersion = pluginInfo.getVersion(); - private static RedLightGreenLight plugin; - private static FoliaLib foliaLib; - private static VersionCheckerUtils versionCheckerUtils; + private FoliaLib foliaLib; + private VersionCheckerUtils versionCheckerUtils; + private BukkitAudiences bukkitAudiences; + private ServerVersion serverVersion; + // File Managers + private MessagesFileManager messagesFileManager; + + // Config Managers + private ConfigManager configManager; + private MessagesManager messagesManager; + + // Booleans + private boolean isPluginEnabled = true; + private boolean isUpdateAvailable = false; + private boolean isPluginReloading = false; + + // Commands + private CommandManager commandManager; + + // Lists public List onlinePlayers = new ArrayList<>(Bukkit.getServer().getOnlinePlayers()); + // Tasks + private WrappedTask onlinePlayerUpdateTasks; + @Override - public void onEnable() { - //Plugin startup logic + public void onLoad() { + // Plugin load logic plugin = this; - foliaLib = new FoliaLib(plugin); + foliaLib = new FoliaLib(this); + + // Load the plugin configs + getConfig().options().copyDefaults(); + saveDefaultConfig(); + + // Load config manager + setConfigManager(new ConfigManager(getConfig())); + getConfigManager().loadConfigVales(); + + // Load messages.yml + setMessagesFileManager(new MessagesFileManager(this)); + + // Load messages manager + setMessagesManager(new MessagesManager(getMessagesFileManager().getMessagesConfig())); + getMessagesManager().loadMessagesValues(); + MessageUtils.setDebug(getConfigManager().isDebugMode()); + + // Check server version and set it + setVersion(); versionCheckerUtils = new VersionCheckerUtils(); versionCheckerUtils.setVersion(); - //Server version compatibility check - if (getVersionCheckerUtils().getVersion() < 13||getVersionCheckerUtils().getVersion() > 20){ - console.sendMessage(ColorUtils.translateColorCodes("&4-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Your server version is: &d" + Bukkit.getServer().getVersion())); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4This plugin is only supported on the Minecraft versions listed below:")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.13.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.14.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.15.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.16.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.17.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.18.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.19.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &41.20.x")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Is now disabling!")); - console.sendMessage(ColorUtils.translateColorCodes("&4-------------------------------------------")); - Bukkit.getPluginManager().disablePlugin(this); + // Server version compatibility check + if (versionCheckerUtils.getVersion() < 16 || versionCheckerUtils.getVersion() > 21 + || !versionCheckerUtils.isVersionCheckedSuccessfully() + && !serverVersion.serverVersionEqual(ServerVersion.Other)) { + MessageUtils.sendConsole("&4-------------------------------------------"); + MessageUtils.sendConsole("&4Your server version is: &d" + Bukkit.getVersion()); + MessageUtils.sendConsole("&4This plugin is only supported on the Minecraft versions listed below:"); + MessageUtils.sendConsole("&41.16.x"); + MessageUtils.sendConsole("&41.17.x"); + MessageUtils.sendConsole("&41.18.x"); + MessageUtils.sendConsole("&41.19.x"); + MessageUtils.sendConsole("&41.20.x"); + MessageUtils.sendConsole("&41.21.x"); + MessageUtils.sendConsole("&4Is now disabling!"); + MessageUtils.sendConsole("&4-------------------------------------------"); + setPluginEnabled(false); + return; + } else { + MessageUtils.sendConsole("&a-------------------------------------------"); + MessageUtils.sendConsole("&aA supported Minecraft version has been detected"); + MessageUtils.sendConsole("&aYour server version is: &d" + Bukkit.getVersion()); + MessageUtils.sendConsole("&6Continuing plugin startup"); + MessageUtils.sendConsole("&a-------------------------------------------"); + } + + if (foliaLib.isUnsupported()) { + MessageUtils.sendConsole("&4-------------------------------------------"); + MessageUtils.sendConsole("&4Your server appears to running a version other than Spigot based!"); + MessageUtils.sendConsole("&4This plugin uses features that your server most likely doesn't have!"); + MessageUtils.sendConsole("&4Is now disabling!"); + MessageUtils.sendConsole("&4-------------------------------------------"); + setPluginEnabled(false); return; - }else { - console.sendMessage(ColorUtils.translateColorCodes("&a-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &aA supported Minecraft version has been detected")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &aYour server version is: &d" + Bukkit.getServer().getVersion())); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &6Continuing plugin startup")); - console.sendMessage(ColorUtils.translateColorCodes("&a-------------------------------------------")); } - //Suggest PaperMC if not using - if (foliaLib.isUnsupported()||foliaLib.isSpigot()){ + if (foliaLib.isSpigot()) { PaperLib.suggestPaper(this); } - //Check if PlugManX is enabled - if (Bukkit.getServer().getPluginManager().isPluginEnabled("PlugManX")||PlugManXAPI.isPlugManXEnabled()){ - if (!PlugManAPI.iDoNotWantToBeUnOrReloaded("RedLightGreenLight")){ - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&4WARNING WARNING WARNING WARNING!")); - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4You appear to be using an unsupported version of &d&lPlugManX")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Please &4&lDO NOT USE PLUGMANX TO LOAD/UNLOAD/RELOAD THIS PLUGIN!")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Please &4&lFULLY RESTART YOUR SERVER!")); - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4This plugin &4&lHAS NOT &4been validated to use this version of PlugManX!")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4&lNo official support will be given to you if you use this!")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4&lUnless Loving11ish has explicitly agreed to help!")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Please add RedLightGreenLight to the ignored-plugins list in PlugManX's config.yml")); - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &6Continuing plugin startup")); - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - }else { - console.sendMessage(ColorUtils.translateColorCodes("&a-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &aSuccessfully hooked into PlugManX")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &aSuccessfully added RedLightGreenLight to ignoredPlugins list.")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &6Continuing plugin startup")); - console.sendMessage(ColorUtils.translateColorCodes("&a-------------------------------------------")); - } - }else { - console.sendMessage(ColorUtils.translateColorCodes("-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &cPlugManX not found!")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &cDisabling PlugManX hook loader")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &6Continuing plugin startup")); - console.sendMessage(ColorUtils.translateColorCodes("-------------------------------------------")); + // Signal end of onLoad method + MessageUtils.sendDebugConsole("End of onLoad method"); + } + + @Override + public void onEnable() { + // Plugin startup logic + MessageUtils.sendDebugConsole("Start of onEnable method"); + + // Check plugin was not disabled during onLoad + if (!isPluginEnabled()) { + MessageUtils.sendConsole("&4Plugin has been disabled during onLoad!"); + Bukkit.getPluginManager().disablePlugin(this); + return; } - //Load the main config file - getConfig().options().copyDefaults(); - saveDefaultConfig(); + // Initial startup message + MessageUtils.sendConsole("&a-------------------------------------------"); + MessageUtils.sendConsole("&aDetected Version &d" + Bukkit.getVersion()); + MessageUtils.sendConsole("&aLoading settings for Version &d" + Bukkit.getVersion()); + + // Load BukkitAudiences + try { + setBukkitAudiences(BukkitAudiences.create(this)); + MessageUtils.sendConsole("&aBukkitAudiences has been created successfully!"); + } catch (Exception e) { + MessageUtils.sendConsole("severe", "&4-------------------------------------------"); + MessageUtils.sendConsole("severe", "&4BukkitAudiences failed to be created!"); + MessageUtils.sendConsole("severe", "&4This plugin uses Adventure Library to function properly!"); + MessageUtils.sendConsole("severe", "&4Please send this error to the developer of RL-GL using below link!"); + MessageUtils.sendConsole("severe", "&4https://discord.gg/crapticraft"); + MessageUtils.sendConsole("severe", "&4Is now disabling!"); + MessageUtils.sendConsole("severe", "&4-------------------------------------------"); + Bukkit.getPluginManager().disablePlugin(this); + setPluginEnabled(false); + return; + } //Register commands here - getCommand("redlight").setExecutor(new CommandManager()); + setCommandManager(new CommandManager()); + getCommand("redlight").setExecutor(getCommandManager()); //Register events here - getServer().getPluginManager().registerEvents(new PlayerCommand(),this); + getServer().getPluginManager().registerEvents(new PlayerCommand(), this); getServer().getPluginManager().registerEvents(new PlayerHungerChange(), this); getServer().getPluginManager().registerEvents(new PlayerInventoryAction(), this); getServer().getPluginManager().registerEvents(new PlayerJoin(), this); getServer().getPluginManager().registerEvents(new PlayerMove(), this); - getServer().getPluginManager().registerEvents(new PlayerQuit(),this); + getServer().getPluginManager().registerEvents(new PlayerQuit(), this); getServer().getPluginManager().registerEvents(new PlayerKick(), this); getServer().getPluginManager().registerEvents(new JoinEvent(this), this); - //Plugin startup message - console.sendMessage(ColorUtils.translateColorCodes("-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Plugin by: &b&lLoving11ish")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3has been loaded successfully")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Plugin Version: &d&l" + pluginVersion)); - console.sendMessage(ColorUtils.translateColorCodes("-------------------------------------------")); + // Final startup message + MessageUtils.sendConsole("&aPlugin by: &b&lLoving11ish"); + MessageUtils.sendConsole("&ahas been loaded successfully"); + MessageUtils.sendConsole("&aPlugin Version: &d&l" + pluginVersion); + MessageUtils.sendDebugConsole("&e&lDeveloper debug mode enabled!"); + MessageUtils.sendDebugConsole("&e&lThis WILL fill the console"); + MessageUtils.sendDebugConsole("&e&lwith additional UStats information!"); + MessageUtils.sendDebugConsole("&e&lThis setting is not intended for "); + MessageUtils.sendDebugConsole("&e&lcontinuous use!"); + MessageUtils.sendConsole("-------------------------------------------"); - //Check for available updates + // Start online player update task + this.onlinePlayerUpdateTasks = foliaLib.getScheduler().runTimer(new OnlinePlayerTasks(), 5L, 300L, TimeUnit.SECONDS); + + // Check for available updates new UpdateChecker(96866).getVersion(version -> { if (this.getDescription().getVersion().equalsIgnoreCase(version)) { - console.sendMessage(ColorUtils.translateColorCodes(getConfig().getString("No-update-1"))); - console.sendMessage(ColorUtils.translateColorCodes(getConfig().getString("No-update-2"))); - console.sendMessage(ColorUtils.translateColorCodes(getConfig().getString("No-update-3"))); - }else { - console.sendMessage(ColorUtils.translateColorCodes(getConfig().getString("Update-1"))); - console.sendMessage(ColorUtils.translateColorCodes(getConfig().getString("Update-2"))); - console.sendMessage(ColorUtils.translateColorCodes(getConfig().getString("Update-3"))); + MessageUtils.sendConsole(getMessagesManager().getNoUpdateAvailable1()); + MessageUtils.sendConsole(getMessagesManager().getNoUpdateAvailable2()); + MessageUtils.sendConsole(getMessagesManager().getNoUpdateAvailable3()); + setUpdateAvailable(false); + } else { + MessageUtils.sendConsole(getMessagesManager().getUpdateAvailable1()); + MessageUtils.sendConsole(getMessagesManager().getUpdateAvailable2()); + MessageUtils.sendConsole(getMessagesManager().getUpdateAvailable3()); + setUpdateAvailable(true); } }); + + // Signal end of onEnable method + MessageUtils.sendDebugConsole("End of onEnable method"); } @Override public void onDisable() { - //Plugin shutdown logic + // Plugin shutdown logic + + // Check if the server is reloading and warn users + if (ReloadingUtils.isCurrentlyReloading()) { + MessageUtils.sendConsole("error", "&4╔══════════════════════════════════════════════════════════════════╗"); + MessageUtils.sendConsole("error", "&4║ WARNING ║"); + MessageUtils.sendConsole("error", "&4║ RELOADING THE SERVER WHILE RL-GL IS ENABLED MIGHT ║"); + MessageUtils.sendConsole("error", "&4║ LEAD TO UNEXPECTED ERRORS! ║"); + MessageUtils.sendConsole("error", "&4║ ║"); + MessageUtils.sendConsole("error", "&4║ Please to fully restart your server if you encounter issues! ║"); + MessageUtils.sendConsole("error", "&4╚══════════════════════════════════════════════════════════════════╝"); + } + + // Shutdown message start + MessageUtils.sendConsole("-----------------------------------------"); - //Unregister plugin listeners + // Set plugin to disabled + setPluginEnabled(false); + MessageUtils.sendConsole("&aPlugin has been disabled!"); + + // Unregister plugin listeners HandlerList.unregisterAll(this); + MessageUtils.sendConsole("&aListeners have unregistered successfully!"); + + // End all games + GameManager.endGameArena1(); - //Cancel background tasks - console.sendMessage(ColorUtils.translateColorCodes("-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Plugin by: &b&lLoving11ish")); + // Cancel background tasks try { - if (!CountDownTasksUtils.wrappedTask1.isCancelled()){ + if (!CountDownTasksUtils.wrappedTask1.isCancelled()) { CountDownTasksUtils.wrappedTask1.cancel(); } - if (!CountDownTasksUtils.wrappedTask2.isCancelled()){ + if (!CountDownTasksUtils.wrappedTask2.isCancelled()) { CountDownTasksUtils.wrappedTask2.cancel(); } - if (!CountDownTasksUtils.wrappedTask3.isCancelled()){ + if (!CountDownTasksUtils.wrappedTask3.isCancelled()) { CountDownTasksUtils.wrappedTask3.cancel(); } - if (!CountDownTasksUtils.wrappedTask4.isCancelled()){ + if (!CountDownTasksUtils.wrappedTask4.isCancelled()) { CountDownTasksUtils.wrappedTask4.cancel(); } - if (foliaLib.isUnsupported()){ + if (!this.onlinePlayerUpdateTasks.isCancelled()) { + this.onlinePlayerUpdateTasks.cancel(); + } + if (foliaLib.isUnsupported()) { Bukkit.getScheduler().cancelTasks(this); } - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Background tasks have disabled successfully!")); - }catch (Exception e){ - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Background tasks have disabled successfully!")); + MessageUtils.sendConsole("&aBackground tasks have disabled successfully!"); + } catch (Exception e) { + MessageUtils.sendConsole("&aBackground tasks have disabled successfully!"); } - //Restore players invs & leave active game + // Restore players inv's & leave active game for (Player onlinePlayer : onlinePlayers) { String onPlayerName = onlinePlayer.getName(); Player onlinePlayerName = Bukkit.getServer().getPlayer(onPlayerName); - if (onlinePlayerName != null){ + if (onlinePlayerName != null) { UUID onlineUUID = onlinePlayerName.getUniqueId(); if (GameManager.getGame1().contains(onlineUUID)) { onlinePlayerName.setInvulnerable(false); @@ -197,27 +286,142 @@ public void onDisable() { } } - //Final plugin shutdown message - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Plugin Version: &d&l" + pluginVersion)); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Has been shutdown successfully")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &3Goodbye!")); - console.sendMessage(ColorUtils.translateColorCodes("-------------------------------------------")); + // Final plugin shutdown message + MessageUtils.sendConsole("&aPlugin Version: &d&l" + pluginVersion); + MessageUtils.sendConsole("&aHas been shutdown successfully"); + MessageUtils.sendConsole("&aGoodbye!"); + MessageUtils.sendConsole("-----------------------------------------"); - //Cleanup any plugin remains + // Clear lists + onlinePlayers.clear(); + bukkitAudiences.close(); + + // Cleanup any plugin remains + onlinePlayerUpdateTasks = null; + commandManager = null; + messagesManager = null; + configManager = null; + messagesFileManager = null; + serverVersion = null; + bukkitAudiences = null; versionCheckerUtils = null; foliaLib = null; plugin = null; } - public static RedLightGreenLight getPlugin(){ + private void setVersion() { + try { + String packageName = Bukkit.getServer().getClass().getPackage().getName(); + String bukkitVersion = Bukkit.getServer().getBukkitVersion(); + if (bukkitVersion.contains("1.20.5")) { + serverVersion = ServerVersion.v1_20_R5; + } else if (bukkitVersion.contains("1.20.6")) { + serverVersion = ServerVersion.v1_20_R5; + } else if (bukkitVersion.contains("1.21")) { + serverVersion = ServerVersion.v1_21_R1; + } else if (bukkitVersion.contains("1.21.1")) { + serverVersion = ServerVersion.v1_21_R2; + } else if (bukkitVersion.contains("1.21.2")) { + serverVersion = ServerVersion.v1_21_R3; + } else if (bukkitVersion.contains("1.21.3")) { + serverVersion = ServerVersion.v1_21_R3; + } else if (bukkitVersion.contains("1.21.4")) { + serverVersion = ServerVersion.v1_21_R4; + } else { + serverVersion = ServerVersion.valueOf(packageName.replace("org.bukkit.craftbukkit.", "")); + } + } catch (Exception e) { + serverVersion = ServerVersion.Other; + MessageUtils.sendDebugConsole("Failed to detect server version, defaulting to: " + serverVersion); + } + MessageUtils.sendDebugConsole("Set server version: " + serverVersion); + } + + public static RedLightGreenLight getPlugin() { return plugin; } - public static FoliaLib getFoliaLib() { + public FoliaLib getFoliaLib() { return foliaLib; } - public static VersionCheckerUtils getVersionCheckerUtils() { + public VersionCheckerUtils getVersionCheckerUtils() { return versionCheckerUtils; } + + public BukkitAudiences getBukkitAudiences() { + return bukkitAudiences; + } + + public void setBukkitAudiences(BukkitAudiences bukkitAudiences) { + this.bukkitAudiences = bukkitAudiences; + } + + public ServerVersion getServerVersion() { + return serverVersion; + } + + public MessagesFileManager getMessagesFileManager() { + return messagesFileManager; + } + + public void setMessagesFileManager(MessagesFileManager messagesFileManager) { + this.messagesFileManager = messagesFileManager; + } + + public ConfigManager getConfigManager() { + return configManager; + } + + public void setConfigManager(ConfigManager configManager) { + this.configManager = configManager; + } + + public MessagesManager getMessagesManager() { + return messagesManager; + } + + public void setMessagesManager(MessagesManager messagesManager) { + this.messagesManager = messagesManager; + } + + public boolean isPluginEnabled() { + return isPluginEnabled; + } + + public void setPluginEnabled(boolean pluginEnabled) { + isPluginEnabled = pluginEnabled; + } + + public boolean isUpdateAvailable() { + return isUpdateAvailable; + } + + public void setUpdateAvailable(boolean updateAvailable) { + isUpdateAvailable = updateAvailable; + } + + public boolean isPluginReloading() { + return isPluginReloading; + } + + public void setPluginReloading(boolean pluginReloading) { + isPluginReloading = pluginReloading; + } + + public CommandManager getCommandManager() { + return commandManager; + } + + public void setCommandManager(CommandManager commandManager) { + this.commandManager = commandManager; + } + + public WrappedTask getOnlinePlayerUpdateTasks() { + return onlinePlayerUpdateTasks; + } + + public void setOnlinePlayerUpdateTasks(WrappedTask onlinePlayerUpdateTasks) { + this.onlinePlayerUpdateTasks = onlinePlayerUpdateTasks; + } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/CommandManager.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/CommandManager.java index 0f95f57..f5e0d82 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/CommandManager.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/CommandManager.java @@ -1,45 +1,54 @@ package me.loving11ish.redlightgreenlight.commands; +import com.tcoded.folialib.FoliaLib; import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.consolecommands.ConsoleHelp; import me.loving11ish.redlightgreenlight.commands.consolecommands.ConsoleJoinAll; import me.loving11ish.redlightgreenlight.commands.consolecommands.ConsoleLeaveAll; import me.loving11ish.redlightgreenlight.commands.consolecommands.ConsoleReload; import me.loving11ish.redlightgreenlight.commands.subcommands.*; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; +import me.loving11ish.redlightgreenlight.files.MessagesFileManager; +import me.loving11ish.redlightgreenlight.managers.filemanagers.ConfigManager; +import me.loving11ish.redlightgreenlight.managers.filemanagers.MessagesManager; +import me.loving11ish.redlightgreenlight.updatesystem.UpdateChecker; +import me.loving11ish.redlightgreenlight.utils.CountDownTasksUtils; +import me.loving11ish.redlightgreenlight.utils.GameManager; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; +import me.loving11ish.redlightgreenlight.utils.PlayerInventoryHandler; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; public class CommandManager implements TabExecutor { - ConsoleCommandSender console = Bukkit.getConsoleSender(); - - private ArrayList subcommands = new ArrayList<>(); - private ArrayList consolecommands = new ArrayList<>(); + private final ArrayList subCommands = new ArrayList<>(); + private final ArrayList consoleCommands = new ArrayList<>(); public CommandManager() { //Get the subcommands so we can access them in the command manager class(here) - consolecommands.add(new ConsoleReload()); - consolecommands.add(new ConsoleJoinAll()); - consolecommands.add(new ConsoleLeaveAll()); - consolecommands.add(new ConsoleHelp()); - subcommands.add(new Reload()); - subcommands.add(new JoinGame()); - subcommands.add(new LeaveGame()); - subcommands.add(new LeaveAll()); - subcommands.add(new JoinAll()); - subcommands.add(new Help()); + consoleCommands.add(new ConsoleReload()); + consoleCommands.add(new ConsoleJoinAll()); + consoleCommands.add(new ConsoleLeaveAll()); + consoleCommands.add(new ConsoleHelp()); + subCommands.add(new Reload()); + subCommands.add(new JoinGame()); + subCommands.add(new LeaveGame()); + subCommands.add(new LeaveAll()); + subCommands.add(new JoinAll()); + subCommands.add(new Help()); } @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; if (args.length > 0) { @@ -57,24 +66,22 @@ public boolean onCommand(CommandSender sender, Command command, String label, St } } } else { - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Syntax-error-1"))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Syntax-error-2"))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Syntax-error-3"))); + MessageUtils.sendConsole(consoleSyntaxMessage()); } } return true; } public ArrayList getSubCommands() { - return subcommands; + return subCommands; } public ArrayList getConsoleCommands() { - return consolecommands; + return consoleCommands; } @Override - public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { if (args.length == 1) { //redlight ArrayList subcommandsArguments = new ArrayList<>(); for (int i = 0; i < getSubCommands().size(); i++) { @@ -90,4 +97,117 @@ public List onTabComplete(CommandSender sender, Command command, String } return null; } + + private String consoleSyntaxMessage() { + List messages = RedLightGreenLight.getPlugin().getMessagesManager().getConsoleSyntaxError(); + StringBuilder message = new StringBuilder(); + for (String msg : messages) { + message.append(msg); + } + return message.toString(); + } + + public void reloadPlugin() { + FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); + RedLightGreenLight.getPlugin().setPluginReloading(true); + + MessageUtils.sendConsole("-----------------------------------------"); + + // End all games + GameManager.endGameArena1(); + + // Cancel all tasks + try { + if (!CountDownTasksUtils.wrappedTask1.isCancelled()) { + CountDownTasksUtils.wrappedTask1.cancel(); + } + if (!CountDownTasksUtils.wrappedTask2.isCancelled()) { + CountDownTasksUtils.wrappedTask2.cancel(); + } + if (!CountDownTasksUtils.wrappedTask3.isCancelled()) { + CountDownTasksUtils.wrappedTask3.cancel(); + } + if (!CountDownTasksUtils.wrappedTask4.isCancelled()) { + CountDownTasksUtils.wrappedTask4.cancel(); + } + if (!RedLightGreenLight.getPlugin().getOnlinePlayerUpdateTasks().isCancelled()) { + RedLightGreenLight.getPlugin().getOnlinePlayerUpdateTasks().cancel(); + } + if (foliaLib.isUnsupported()) { + Bukkit.getScheduler().cancelTasks(RedLightGreenLight.getPlugin()); + } + MessageUtils.sendConsole("&aBackground tasks have disabled successfully!"); + } catch (Exception e) { + MessageUtils.sendConsole("&aBackground tasks have disabled successfully!"); + } + + // Restore players inv's & leave active game + for (Player onlinePlayer : RedLightGreenLight.getPlugin().onlinePlayers) { + String onPlayerName = onlinePlayer.getName(); + Player onlinePlayerName = Bukkit.getServer().getPlayer(onPlayerName); + if (onlinePlayerName != null) { + UUID onlineUUID = onlinePlayerName.getUniqueId(); + if (GameManager.getGame1().contains(onlineUUID)) { + onlinePlayerName.setInvulnerable(false); + if (PlayerInventoryHandler.getItems().contains(onlineUUID) && PlayerInventoryHandler.getArmor().contains(onlineUUID)) { + PlayerInventoryHandler.clearInventory(onlinePlayerName); + PlayerInventoryHandler.restoreInventory(onlinePlayerName); + } + if (GameManager.getPlayersInRound().contains(onlineUUID)) { + GameManager.leaveRound(onlinePlayerName); + } + GameManager.leaveGame1(onlinePlayerName); + if (GameManager.getSpectatingPlayers().contains(onlineUUID)) { + GameManager.leaveSpectating(onlinePlayerName); + } + } + } + } + + foliaLib.getScheduler().runLaterAsync(() -> { + // Reload main config.yml + RedLightGreenLight.getPlugin().reloadConfig(); + + // Load data from config.yml + ConfigManager configManager = new ConfigManager(RedLightGreenLight.getPlugin().getConfig()); + configManager.loadConfigVales(); + RedLightGreenLight.getPlugin().setConfigManager(configManager); + MessageUtils.sendConsole("&aReloading config.yml..."); + + // Reload messages.yml + MessagesFileManager messagesFileManager = new MessagesFileManager(RedLightGreenLight.getPlugin()); + RedLightGreenLight.getPlugin().setMessagesFileManager(messagesFileManager); + + // Load data from messages.yml + MessagesManager messagesManager = new MessagesManager(RedLightGreenLight.getPlugin().getMessagesFileManager().getMessagesConfig()); + messagesManager.loadMessagesValues(); + RedLightGreenLight.getPlugin().setMessagesManager(messagesManager); + MessageUtils.prefix = RedLightGreenLight.getPlugin().getMessagesManager().getPrefix(); + MessageUtils.setDebug(RedLightGreenLight.getPlugin().getConfigManager().isDebugMode()); + MessageUtils.sendConsole("&aReloading messages.yml..."); + + foliaLib.getScheduler().runLaterAsync(() -> { + // Signal that the plugin has been reloaded + MessageUtils.sendConsole("&aPlugin has been reloaded successfully!"); + MessageUtils.sendConsole("-----------------------------------------"); + + RedLightGreenLight.getPlugin().setPluginReloading(false); + }, 6L, TimeUnit.SECONDS); + }, 2L, TimeUnit.SECONDS); + + // Check for available updates + new UpdateChecker(96866).getVersion(version -> { + if (RedLightGreenLight.getPlugin().getDescription().getVersion().equalsIgnoreCase(version)) { + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getNoUpdateAvailable1()); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getNoUpdateAvailable2()); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getNoUpdateAvailable3()); + RedLightGreenLight.getPlugin().setUpdateAvailable(false); + } else { + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getUpdateAvailable1()); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getUpdateAvailable2()); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getUpdateAvailable3()); + RedLightGreenLight.getPlugin().setUpdateAvailable(true); + } + }); + } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/ConsoleCommand.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/ConsoleCommand.java index fce19a1..160d6e8 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/ConsoleCommand.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/ConsoleCommand.java @@ -8,6 +8,6 @@ public abstract class ConsoleCommand { public abstract String getSyntax(); - public abstract void perform(String args[]); + public abstract void perform(String[] args); } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleHelp.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleHelp.java index 97e1622..e8a4feb 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleHelp.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleHelp.java @@ -2,17 +2,15 @@ import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.ConsoleCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import org.bukkit.plugin.PluginDescriptionFile; -public class ConsoleHelp extends ConsoleCommand { +import java.util.List; - ConsoleCommandSender console = Bukkit.getConsoleSender(); +public class ConsoleHelp extends ConsoleCommand { - private PluginDescriptionFile pluginInfo = RedLightGreenLight.getPlugin().getDescription(); - private String pluginVersion = pluginInfo.getVersion(); + private final PluginDescriptionFile pluginInfo = RedLightGreenLight.getPlugin().getDescription(); + private final String pluginVersion = pluginInfo.getVersion(); @Override public String getName() { @@ -31,25 +29,15 @@ public String getSyntax() { @Override public void perform(String[] args) { - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-1").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-2").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-3").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-4").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-5").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-6").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-7").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-8").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-9").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-10").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-11").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-12").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-13").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-14").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-15").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-16").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-17").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-18").replace("%version%", pluginVersion))); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-19").replace("%version%", pluginVersion))); + MessageUtils.sendConsole(this.getHelpMessage()); + } + private String getHelpMessage() { + List helpMessage = RedLightGreenLight.getPlugin().getMessagesManager().getHelpCommand(); + StringBuilder stringBuilder = new StringBuilder(); + for (String message : helpMessage) { + stringBuilder.append(message); + } + return stringBuilder.toString().replace("%version%", pluginVersion); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleJoinAll.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleJoinAll.java index 465db6a..1538ad3 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleJoinAll.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleJoinAll.java @@ -2,21 +2,17 @@ import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.ConsoleCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; import me.loving11ish.redlightgreenlight.utils.GameManager; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import me.loving11ish.redlightgreenlight.utils.PlayerInventoryHandler; import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; import java.util.List; import java.util.UUID; public class ConsoleJoinAll extends ConsoleCommand { - ConsoleCommandSender console = Bukkit.getConsoleSender(); - @Override public String getName() { return "joinall"; @@ -34,9 +30,9 @@ public String getSyntax() { @Override public void perform(String[] args) { - List onlinePlayers = new ArrayList<>(Bukkit.getServer().getOnlinePlayers()); + List onlinePlayers = RedLightGreenLight.getPlugin().onlinePlayers; if (!(GameManager.getGameRunning() == 0)) { - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-already-running"))); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getGameRunning()); return; } for (Player onlinePlayer : onlinePlayers) { @@ -49,7 +45,7 @@ public void perform(String[] args) { PlayerInventoryHandler.storeAndClearInventory(onlinePlayerName); GameManager.startGameArena1(onlinePlayerName); } else { - onlinePlayerName.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Failed-join-arena"))); + MessageUtils.sendPlayer(onlinePlayerName, RedLightGreenLight.getPlugin().getMessagesManager().getFailedJoinArena()); } } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleLeaveAll.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleLeaveAll.java index c298a38..8ff76b6 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleLeaveAll.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleLeaveAll.java @@ -2,15 +2,11 @@ import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.ConsoleCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; import me.loving11ish.redlightgreenlight.utils.GameManager; -import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; public class ConsoleLeaveAll extends ConsoleCommand { - ConsoleCommandSender console = Bukkit.getConsoleSender(); - @Override public String getName() { return "leaveall"; @@ -29,7 +25,7 @@ public String getSyntax() { @Override public void perform(String[] args) { if (GameManager.getGameRunning() == 0) { - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("No-game-running"))); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getNoGameRunning()); return; } GameManager.endSpectatingGame(); diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java index f24f197..751e3dc 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java @@ -3,17 +3,12 @@ import com.tcoded.folialib.FoliaLib; import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.ConsoleCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.ConsoleCommandSender; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import java.util.concurrent.TimeUnit; public class ConsoleReload extends ConsoleCommand { - ConsoleCommandSender console = Bukkit.getConsoleSender(); - @Override public String getName() { return "reload"; @@ -21,25 +16,23 @@ public String getName() { @Override public String getDescription() { - return ChatColor.AQUA + "This reloads the plugin config file."; + return "This reloads the plugin config file."; } @Override public String getSyntax() { - return ChatColor.AQUA + "redlight reload"; + return "redlight reload"; } @Override public void perform(String[] args) { - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Plugin-reload-beginning"))); - FoliaLib foliaLib = RedLightGreenLight.getFoliaLib(); - RedLightGreenLight.getPlugin().onDisable(); - foliaLib.getImpl().runLater(() -> { - Bukkit.getPluginManager().getPlugin("RedLightGreenLight").onEnable(); - }, 5L, TimeUnit.SECONDS); - foliaLib.getImpl().runLater(() -> { - RedLightGreenLight.getPlugin().reloadConfig(); - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Plugin-reload-successful"))); - }, 5L, TimeUnit.SECONDS); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadStart()); + + RedLightGreenLight.getPlugin().getCommandManager().reloadPlugin(); + + FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); + foliaLib.getScheduler().runLater(() -> { + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); + }, 8L, TimeUnit.SECONDS); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Help.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Help.java index 7a1fa18..f5e116c 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Help.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Help.java @@ -2,7 +2,7 @@ import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.SubCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; @@ -10,8 +10,8 @@ public class Help extends SubCommand { - private PluginDescriptionFile pluginInfo = RedLightGreenLight.getPlugin().getDescription(); - private String pluginVersion = pluginInfo.getVersion(); + private final PluginDescriptionFile pluginInfo = RedLightGreenLight.getPlugin().getDescription(); + private final String pluginVersion = pluginInfo.getVersion(); @Override public String getName() { @@ -30,28 +30,10 @@ public String getSyntax() { @Override public void perform(Player player, String[] args) { - if (player.hasPermission("redlight.help")||player.hasPermission("redlight.*")||player.isOp()){ - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-1").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-2").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-3").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-4").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-5").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-6").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-7").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-8").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-9").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-10").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-11").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-12").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-13").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-14").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-15").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-16").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-17").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-18").replace("%version%", pluginVersion))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-19").replace("%version%", pluginVersion))); - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Help-command-no-permission"))); + if (player.hasPermission("redlight.help") || player.hasPermission("redlight.*") || player.isOp()) { + MessageUtils.sendPlayer(player, this.getHelpMessage()); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getNoPermission()); } } @@ -59,4 +41,13 @@ public void perform(Player player, String[] args) { public List getSubcommandArguments(Player player, String[] args) { return null; } + + private String getHelpMessage() { + List helpMessage = RedLightGreenLight.getPlugin().getMessagesManager().getHelpCommand(); + StringBuilder stringBuilder = new StringBuilder(); + for (String message : helpMessage) { + stringBuilder.append(message); + } + return stringBuilder.toString().replace("%version%", pluginVersion); + } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinAll.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinAll.java index c54ea9d..da09c1e 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinAll.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinAll.java @@ -2,17 +2,17 @@ import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.SubCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; import me.loving11ish.redlightgreenlight.utils.GameManager; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import me.loving11ish.redlightgreenlight.utils.PlayerInventoryHandler; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.util.ArrayList; import java.util.List; import java.util.UUID; public class JoinAll extends SubCommand { + @Override public String getName() { return "joinall"; @@ -30,33 +30,33 @@ public String getSyntax() { @Override public void perform(Player player, String[] args) { - if (player.hasPermission("redlight.command.joinall")||player.hasPermission("redlight.command.*")|| - player.hasPermission("redlight.*")||player.isOp()){ - List onlinePlayers = new ArrayList<>(Bukkit.getServer().getOnlinePlayers()); - if (!(RedLightGreenLight.getPlugin().getConfig().getList("Disabled-worlds").contains(player.getWorld().getName()))){ - if (!(GameManager.getGameRunning() == 0)){ - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-already-running"))); + if (player.hasPermission("redlight.command.joinall") || player.hasPermission("redlight.command.*") || + player.hasPermission("redlight.*") || player.isOp()) { + List onlinePlayers = RedLightGreenLight.getPlugin().onlinePlayers; + if (!(RedLightGreenLight.getPlugin().getConfigManager().getDisabledWorldsList().contains(player.getWorld().getName()))) { + if (!(GameManager.getGameRunning() == 0)) { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getGameRunning()); return; } for (Player onlinePlayer : onlinePlayers) { String onPlayerName = onlinePlayer.getName(); Player onlinePlayerName = Bukkit.getServer().getPlayer(onPlayerName); - if (onlinePlayerName != null){ + if (onlinePlayerName != null) { UUID onlineUUID = onlinePlayerName.getUniqueId(); if (!(GameManager.getGame1().contains(onlineUUID))) { GameManager.addToGame1(onlinePlayerName); PlayerInventoryHandler.storeAndClearInventory(onlinePlayerName); GameManager.startGameArena1(onlinePlayerName); } else { - onlinePlayerName.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Failed-join-arena"))); + MessageUtils.sendPlayer(onlinePlayerName, RedLightGreenLight.getPlugin().getMessagesManager().getFailedJoinArena()); } } } - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Disabled-world-message"))); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getDisabledWorld()); } - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Joinall-command-no-permission"))); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getNoPermission()); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinGame.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinGame.java index 1e0c4be..5daa44d 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinGame.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/JoinGame.java @@ -9,6 +9,7 @@ import java.util.UUID; public class JoinGame extends SubCommand { + @Override public String getName() { return "join"; @@ -27,20 +28,20 @@ public String getSyntax() { @Override public void perform(Player player, String[] args) { UUID uuid = player.getUniqueId(); - if (!(RedLightGreenLight.getPlugin().getConfig().getList("Disabled-worlds").contains(player.getWorld().getName()))){ - if (!(GameManager.getGameRunning() == 0)){ - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-already-running"))); + if (!(RedLightGreenLight.getPlugin().getConfigManager().getDisabledWorldsList().contains(player.getWorld().getName()))) { + if (!(GameManager.getGameRunning() == 0)) { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getGameRunning()); return; } - if (!(GameManager.getGame1().contains(uuid))){ + if (!(GameManager.getGame1().contains(uuid))) { GameManager.addToGame1(player); PlayerInventoryHandler.storeAndClearInventory(player); GameManager.startGameArena1(player); - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Failed-join-arena"))); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getFailedJoinArena()); } - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Disabled-world-message"))); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getDisabledWorld()); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveAll.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveAll.java index 31170fc..944773f 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveAll.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveAll.java @@ -2,13 +2,14 @@ import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.SubCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; import me.loving11ish.redlightgreenlight.utils.GameManager; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import org.bukkit.entity.Player; import java.util.List; public class LeaveAll extends SubCommand { + @Override public String getName() { return "leaveall"; @@ -28,22 +29,21 @@ public String getSyntax() { public void perform(Player player, String[] args) { if (player.hasPermission("redlight.command.leaveall") || player.hasPermission("redlight.command.*") || player.hasPermission("redlight.*") || player.isOp()) { - if (!(RedLightGreenLight.getPlugin().getConfig().getList("Disabled-worlds").contains(player.getWorld().getName()))) { + if (!(RedLightGreenLight.getPlugin().getConfigManager().getDisabledWorldsList().contains(player.getWorld().getName()))) { if (GameManager.getGameRunning() == 0) { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("No-game-running"))); + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getNoGameRunning()); return; } GameManager.endSpectatingGame(); GameManager.endGameArena1(); - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Disabled-world-message"))); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getDisabledWorld()); } - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Leaveall-command-no-permission"))); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getNoPermission()); } } - @Override public List getSubcommandArguments(Player player, String[] args) { return null; diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveGame.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveGame.java index 256a2c3..2dd4a98 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveGame.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/LeaveGame.java @@ -2,8 +2,8 @@ import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.SubCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; import me.loving11ish.redlightgreenlight.utils.GameManager; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import me.loving11ish.redlightgreenlight.utils.PlayerInventoryHandler; import org.bukkit.entity.Player; @@ -11,6 +11,7 @@ import java.util.UUID; public class LeaveGame extends SubCommand { + @Override public String getName() { return "leave"; @@ -29,24 +30,25 @@ public String getSyntax() { @Override public void perform(Player player, String[] args) { UUID uuid = player.getUniqueId(); - if (!(RedLightGreenLight.getPlugin().getConfig().getList("Disabled-worlds").contains(player.getWorld().getName()))){ - if (GameManager.getGame1().contains(uuid)||GameManager.getSpectatingPlayers().contains(uuid)){ - if (GameManager.getPlayersInRound().contains(uuid)){ + if (!(RedLightGreenLight.getPlugin().getConfigManager().getDisabledWorldsList().contains(player.getWorld().getName()))) { + if (GameManager.getGame1().contains(uuid) || GameManager.getSpectatingPlayers().contains(uuid)) { + if (GameManager.getPlayersInRound().contains(uuid)) { GameManager.leaveRound(player); } - if (GameManager.getSpectatingPlayers().contains(uuid)){ + if (GameManager.getSpectatingPlayers().contains(uuid)) { GameManager.leaveSpectating(player); } GameManager.teleportToLobby(player); PlayerInventoryHandler.clearInventory(player); PlayerInventoryHandler.restoreInventory(player); GameManager.leaveGame1(player); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Successful-leave-game"))); - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Player-not-in-game"))); + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getSuccessfulLeaveGame()); + + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getPlayerNotInGame()); } - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Disabled-world-message"))); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getDisabledWorld()); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java index b247561..95493ae 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java @@ -3,17 +3,23 @@ import com.tcoded.folialib.FoliaLib; import me.loving11ish.redlightgreenlight.RedLightGreenLight; import me.loving11ish.redlightgreenlight.commands.SubCommand; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; +import me.loving11ish.redlightgreenlight.files.MessagesFileManager; +import me.loving11ish.redlightgreenlight.managers.filemanagers.ConfigManager; +import me.loving11ish.redlightgreenlight.managers.filemanagers.MessagesManager; +import me.loving11ish.redlightgreenlight.updatesystem.UpdateChecker; +import me.loving11ish.redlightgreenlight.utils.CountDownTasksUtils; +import me.loving11ish.redlightgreenlight.utils.GameManager; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; +import me.loving11ish.redlightgreenlight.utils.PlayerInventoryHandler; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.entity.Player; import java.util.List; +import java.util.UUID; import java.util.concurrent.TimeUnit; public class Reload extends SubCommand { - @Override public String getName() { return "reload"; @@ -21,29 +27,31 @@ public String getName() { @Override public String getDescription() { - return ChatColor.AQUA + "This reloads the plugin config file."; + return "This reloads the plugin config file."; } @Override public String getSyntax() { - return ChatColor.AQUA + "/redlight reload"; + return "/redlight reload"; } @Override public void perform(Player player, String[] args) { - if (player.hasPermission("redlight.reload")||player.hasPermission("redlight.*")||player.isOp()){ - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Plugin-reload-beginning"))); - FoliaLib foliaLib = RedLightGreenLight.getFoliaLib(); - RedLightGreenLight.getPlugin().onDisable(); - foliaLib.getImpl().runLater(() -> { - Bukkit.getPluginManager().getPlugin("RedLightGreenLight").onEnable(); - }, 5L, TimeUnit.SECONDS); - foliaLib.getImpl().runLater(() -> { - RedLightGreenLight.getPlugin().reloadConfig(); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Plugin-reload-successful"))); - }, 5L, TimeUnit.SECONDS); - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Reload-command-no-permission"))); + if (player.hasPermission("redlight.reload") || player.hasPermission("redlight.*") || player.isOp()) { + + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadStart()); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadStart()); + + RedLightGreenLight.getPlugin().getCommandManager().reloadPlugin(); + + FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); + foliaLib.getScheduler().runLater(() -> { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); + MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); + }, 8L, TimeUnit.SECONDS); + + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getNoPermission()); } } @@ -51,4 +59,5 @@ public void perform(Player player, String[] args) { public List getSubcommandArguments(Player player, String[] args) { return null; } + } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerCommand.java b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerCommand.java index 4ff0d1b..f317e5d 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerCommand.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerCommand.java @@ -1,8 +1,8 @@ package me.loving11ish.redlightgreenlight.events; import me.loving11ish.redlightgreenlight.RedLightGreenLight; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; import me.loving11ish.redlightgreenlight.utils.GameManager; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -14,7 +14,7 @@ public class PlayerCommand implements Listener { - List bannedcommands = RedLightGreenLight.getPlugin().getConfig().getStringList("Blocked-commands-in-game"); + private final List bannedCommands = RedLightGreenLight.getPlugin().getConfigManager().getBlockedInGameCommandsList(); @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerCommandSend(PlayerCommandPreprocessEvent event){ @@ -25,10 +25,10 @@ public void onPlayerCommandSend(PlayerCommandPreprocessEvent event){ String[] message = event.getMessage().split(" "); String command = message[0]; - for (String string : bannedcommands) { + for (String string : bannedCommands) { if (command.equalsIgnoreCase(string)){ event.setCancelled(true); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Command-send-error"))); + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getCommandSendError()); } } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerHungerChange.java b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerHungerChange.java index dbd27ac..d4c048b 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerHungerChange.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerHungerChange.java @@ -15,11 +15,11 @@ public class PlayerHungerChange implements Listener { public void onPlayerHungerChange(FoodLevelChangeEvent event){ Player player = (Player) event.getEntity(); UUID uuid = player.getUniqueId(); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Disable-global-hunger-drain")){ + if (RedLightGreenLight.getPlugin().getConfigManager().isDisableGlobalHunger()){ event.setCancelled(true); return; } - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Disable-in-game-hunger-drain")){ + if (RedLightGreenLight.getPlugin().getConfigManager().isDisableInGameHunger()){ if (GameManager.getGame1().contains(uuid)){ event.setCancelled(true); } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerJoin.java b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerJoin.java index eb9fcf3..99834e6 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerJoin.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerJoin.java @@ -19,9 +19,9 @@ public class PlayerJoin implements Listener { public void onPlayerJoin(PlayerJoinEvent event){ Player player = event.getPlayer(); UUID uuid = player.getUniqueId(); - player.setInvulnerable(RedLightGreenLight.getPlugin().getConfig().getBoolean("Join-player-invulnerable")); + player.setInvulnerable(RedLightGreenLight.getPlugin().getConfigManager().isJoinPlayerInvulnerable()); player.setFoodLevel(20); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Wipe-inventory-on-join")){ + if (RedLightGreenLight.getPlugin().getConfigManager().isWipeInventoryOnJoin()){ if (!(player.hasPermission("redlight.bypass.joinwipe") || player.hasPermission("redlight.*") || player.isOp())){ PlayerInventoryHandler.clearInventory(player); } @@ -35,17 +35,12 @@ public void onPlayerJoin(PlayerJoinEvent event){ if (GameManager.getSpectatingPlayers().contains(uuid)){ GameManager.leaveSpectating(player); } - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Send-welcome-title")){ - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Welcome-player-title")), - ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Welcome-player-subtitle")), 20, 100, 20); + if (RedLightGreenLight.getPlugin().getConfigManager().isSendWelcomeTitle()){ + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfigManager().getWelcomeTitle()), + ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfigManager().getWelcomeSubTitle()), 20, 100, 20); } - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Handle-player-join-spawn-event")){ - double x = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-x"); - double y = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-y"); - double z = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-z"); - float yaw = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-yaw"); - float pitch = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-pitch"); - Location location = new Location(player.getWorld(), x, y, z, yaw, pitch); + if (RedLightGreenLight.getPlugin().getConfigManager().isHandleJoinSpawnEvent()){ + Location location = RedLightGreenLight.getPlugin().getConfigManager().getLobbyLocation(); PaperLib.teleportAsync(player, location); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerMove.java b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerMove.java index 8aead46..8418d0a 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerMove.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerMove.java @@ -2,14 +2,10 @@ import com.tcoded.folialib.FoliaLib; import me.loving11ish.redlightgreenlight.RedLightGreenLight; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; -import me.loving11ish.redlightgreenlight.utils.CountDownTasksUtils; -import me.loving11ish.redlightgreenlight.utils.GameManager; -import me.loving11ish.redlightgreenlight.utils.PlayerInventoryHandler; +import me.loving11ish.redlightgreenlight.utils.*; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -22,55 +18,55 @@ public class PlayerMove implements Listener { - FoliaLib foliaLib = RedLightGreenLight.getFoliaLib(); + private final FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); - List wincommands = RedLightGreenLight.getPlugin().getConfig().getStringList("Win-commands-list"); - List losecommands = RedLightGreenLight.getPlugin().getConfig().getStringList("Lose-commands-list"); + private final List winCommands = RedLightGreenLight.getPlugin().getConfigManager().getWinCommandsList(); + private final List loseCommands = RedLightGreenLight.getPlugin().getConfigManager().getLoseCommandsList(); @EventHandler - public void countDownPlayerMove(PlayerMoveEvent event){ + public void countDownPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); UUID uuid = player.getUniqueId(); if (GameManager.getGame1().contains(uuid)) { - if (GameManager.getCountDown().equals(1)){ + if (GameManager.getCountDown().equals(1)) { event.setCancelled(true); } } } @EventHandler - public void onPlayerMove(PlayerMoveEvent event){ + public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); UUID uuid = player.getUniqueId(); String target = player.getName(); - if (GameManager.getGame1().contains(uuid)){ - if (GameManager.getPlayersInRound().contains(uuid)){ - if (!(GameManager.getLightgreen().equals(0))){ - if (!(GameManager.getCountDown().equals(0))){ + if (GameManager.getGame1().contains(uuid)) { + if (GameManager.getPlayersInRound().contains(uuid)) { + if (!(GameManager.getLightGreen().equals(0))) { + if (!(GameManager.getCountDown().equals(0))) { return; } - if (!CountDownTasksUtils.wrappedTask4.isCancelled()){ + if (!CountDownTasksUtils.wrappedTask4.isCancelled()) { return; } player.setGameMode(GameMode.SURVIVAL); - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-loose-title")), - ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-loose-subtitle")), + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameLoseTitle()), + ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameLoseSubtitle()), 10, 30, 10); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Smite-losing-players")){ - foliaLib.getImpl().runNextTick((task) -> - getServer().dispatchCommand(Bukkit.getConsoleSender(), "execute at " + player.getName() + " run summon minecraft:lightning_bolt ~ ~ ~")); + if (RedLightGreenLight.getPlugin().getConfigManager().isSmiteLosingPlayers()) { + foliaLib.getScheduler().runNextTick((task) -> + getServer().dispatchCommand(Bukkit.getConsoleSender(), "execute at " + player.getName() + " run summon minecraft:lightning_bolt ~ ~ ~")); } - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Run-lose-commands")){ - for (String string : losecommands) { - foliaLib.getImpl().runNextTick((task) -> + if (RedLightGreenLight.getPlugin().getConfigManager().isRunLoseCommands()) { + for (String string : loseCommands) { + foliaLib.getScheduler().runNextTick((task) -> getServer().dispatchCommand(Bukkit.getConsoleSender(), string.replace("%player%", target))); } } - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Losers-spectate-game")){ + if (RedLightGreenLight.getPlugin().getConfigManager().isLosersSpectateGame()) { GameManager.spectatorTeleportToArena(player); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Spectating-message"))); - }else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getSpectatingGame()); + } else { GameManager.teleportToLobby(player); PlayerInventoryHandler.clearInventory(player); PlayerInventoryHandler.restoreInventory(player); @@ -83,26 +79,26 @@ public void onPlayerMove(PlayerMoveEvent event){ } @EventHandler - public void playerBlockMove(PlayerMoveEvent event){ + public void playerBlockMove(PlayerMoveEvent event) { Player player = event.getPlayer(); UUID uuid = player.getUniqueId(); String target = player.getName(); - Location blockunder = player.getLocation(); - Location bottomblock = player.getLocation(); - blockunder.setY(blockunder.getY() - 1); - bottomblock.setY(bottomblock.getY() - 2); - if (blockunder.getBlock().getType().equals(Material.getMaterial(RedLightGreenLight.getPlugin().getConfig().getString("Top-trigger-block"))) && - bottomblock.getBlock().getType().equals(Material.getMaterial(RedLightGreenLight.getPlugin().getConfig().getString("Bottom-trigger-block")))){ - if (GameManager.getGame1().contains(uuid)){ - if (GameManager.getPlayersInRound().contains(uuid)){ - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-win-title")), - ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-win-subtitle")), + Location blockUnder = player.getLocation(); + Location bottomBlock = player.getLocation(); + blockUnder.setY(blockUnder.getY() - 1); + bottomBlock.setY(bottomBlock.getY() - 2); + if (blockUnder.getBlock().getType().equals(RedLightGreenLight.getPlugin().getConfigManager().getTopTriggerBlock()) && + bottomBlock.getBlock().getType().equals(RedLightGreenLight.getPlugin().getConfigManager().getBottomTriggerBlock())) { + if (GameManager.getGame1().contains(uuid)) { + if (GameManager.getPlayersInRound().contains(uuid)) { + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameWinTitle()), + ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameWinSubtitle()), 10, 30, 10); - foliaLib.getImpl().runNextTick((task) -> + foliaLib.getScheduler().runNextTick((task) -> getServer().dispatchCommand(Bukkit.getConsoleSender(), "execute at " + player.getName() + " run summon minecraft:firework_rocket ~ ~ ~")); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Run-win-commands")){ - for (String string : wincommands) { - foliaLib.getImpl().runNextTick((task) -> + if (RedLightGreenLight.getPlugin().getConfigManager().isRunWinCommands()) { + for (String string : winCommands) { + foliaLib.getScheduler().runNextTick((task) -> getServer().dispatchCommand(Bukkit.getConsoleSender(), string.replace("%player%", target))); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerQuit.java b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerQuit.java index 5ebce1d..449be71 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerQuit.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/events/PlayerQuit.java @@ -11,13 +11,12 @@ import org.bukkit.event.player.PlayerQuitEvent; import java.util.UUID; -import java.util.concurrent.TimeUnit; import static org.bukkit.Bukkit.getServer; public class PlayerQuit implements Listener { - FoliaLib foliaLib = RedLightGreenLight.getFoliaLib(); + private final FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); @EventHandler public void onPlayerQuit(PlayerQuitEvent event){ @@ -32,15 +31,15 @@ public void onPlayerQuit(PlayerQuitEvent event){ } } if (GameManager.getPlayersInRound().contains(uuid)){ - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Smite-losing-players")){ - foliaLib.getImpl().runNextTick((task) -> + if (RedLightGreenLight.getPlugin().getConfigManager().isSmiteLosingPlayers()){ + foliaLib.getScheduler().runNextTick((task) -> getServer().dispatchCommand(Bukkit.getConsoleSender(), "execute at " + player.getName() + " run summon minecraft:lightning_bolt ~ ~ ~")); } GameManager.leaveRound(player); } if (GameManager.getSpectatingPlayers().contains(uuid)){ - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Smite-losing-players")){ - foliaLib.getImpl().runNextTick((task) -> + if (RedLightGreenLight.getPlugin().getConfigManager().isSmiteLosingPlayers()){ + foliaLib.getScheduler().runNextTick((task) -> getServer().dispatchCommand(Bukkit.getConsoleSender(), "execute at " + player.getName() + " run summon minecraft:lightning_bolt ~ ~ ~")); } GameManager.leaveSpectating(player); diff --git a/src/main/java/me/loving11ish/redlightgreenlight/externalhooks/PlugManXAPI.java b/src/main/java/me/loving11ish/redlightgreenlight/externalhooks/PlugManXAPI.java deleted file mode 100644 index e75df35..0000000 --- a/src/main/java/me/loving11ish/redlightgreenlight/externalhooks/PlugManXAPI.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.loving11ish.redlightgreenlight.externalhooks; - -import me.loving11ish.redlightgreenlight.utils.ColorUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; - -public class PlugManXAPI { - - static ConsoleCommandSender console = Bukkit.getConsoleSender(); - - public static boolean isPlugManXEnabled() { - try { - Class.forName("com.rylinaux.plugman.PlugMan"); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &aFound PlugManX main class at:")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &dcom.rylinaux.plugman.PlugMan")); - return true; - }catch (ClassNotFoundException e){ - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &aCould not find PlugManX main class at:")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &dcom.rylinaux.plugman.PlugMan")); - return false; - } - } -} diff --git a/src/main/java/me/loving11ish/redlightgreenlight/files/MessagesFileManager.java b/src/main/java/me/loving11ish/redlightgreenlight/files/MessagesFileManager.java new file mode 100644 index 0000000..6a49779 --- /dev/null +++ b/src/main/java/me/loving11ish/redlightgreenlight/files/MessagesFileManager.java @@ -0,0 +1,64 @@ +package me.loving11ish.redlightgreenlight.files; + +import me.loving11ish.redlightgreenlight.RedLightGreenLight; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class MessagesFileManager { + + private final RedLightGreenLight plugin; + private FileConfiguration dataConfig = null; + private File configFile = null; + + public MessagesFileManager(RedLightGreenLight plugin){ + this.plugin = plugin; + saveDefaultMessagesConfig(); + } + + public void reloadMessagesConfig(){ + if (this.configFile == null){ + this.configFile = new File(plugin.getDataFolder(), "messages.yml"); + } + this.dataConfig = YamlConfiguration.loadConfiguration(this.configFile); + InputStream defaultStream = this.plugin.getResource("messages.yml"); + if (defaultStream != null){ + YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defaultStream)); + this.dataConfig.setDefaults(defaultConfig); + } + } + + public FileConfiguration getMessagesConfig(){ + if (this.dataConfig == null){ + this.reloadMessagesConfig(); + } + return this.dataConfig; + } + + public void saveMessagesConfig() { + if (this.dataConfig == null||this.configFile == null){ + return; + } + try { + this.getMessagesConfig().save(this.configFile); + }catch (IOException e){ + MessageUtils.sendConsole("severe", "&4Could not save messages.yml"); + MessageUtils.sendConsole("severe", "&4Check the below message for the reasons!"); + e.printStackTrace(); + } + } + + public void saveDefaultMessagesConfig(){ + if (this.configFile == null){ + this.configFile = new File(plugin.getDataFolder(), "messages.yml"); + } + if (!this.configFile.exists()){ + this.plugin.saveResource("messages.yml", false); + } + } +} diff --git a/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/ConfigManager.java b/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/ConfigManager.java new file mode 100644 index 0000000..1ee6747 --- /dev/null +++ b/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/ConfigManager.java @@ -0,0 +1,259 @@ +package me.loving11ish.redlightgreenlight.managers.filemanagers; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.List; + +public class ConfigManager { + + private final FileConfiguration config; + + // Strings + private String welcomeTitle; + private String welcomeSubTitle; + + // Integers + private int arenaStartPlayerAmount; + private int gameStartCountdown; + private int totalGameLength; + private int redLightDelayCheckTime; + + // Booleans + private boolean debugMode; + private boolean wipeInventoryOnJoin; + private boolean handleJoinSpawnEvent; + private boolean sendWelcomeTitle; + private boolean joinPlayerInvulnerable; + private boolean leavePlayerInvulnerable; + private boolean disableGlobalHunger; + private boolean disableInGameHunger; + private boolean losersSpectateGame; + private boolean runWinCommands; + private boolean runLoseCommands; + private boolean smiteLosingPlayers; + + // Lists + private List disabledWorldsList; + private List blockedInGameCommandsList; + private List winCommandsList; + private List loseCommandsList; + + // Materials + private Material topTriggerBlock; + private Material bottomTriggerBlock; + + // Locations + private Location lobbyLocation; + private Location arenaStartLocation; + private Location spectateLocation; + + + public ConfigManager(FileConfiguration config){ + this.config = config; + } + + public void loadConfigVales() { + // Load strings + welcomeTitle = config.getString("welcome-player-title", "&a&lWelcome To RedLight-GreenLight!"); + welcomeSubTitle = config.getString("welcome-player-subtitle", "&ePlease use /redlight join"); + + // Load integers + arenaStartPlayerAmount = config.getInt("arena-start-size", 4); + gameStartCountdown = config.getInt("game-starting-countdown-length", 10); + totalGameLength = config.getInt("total-game-length", 300); + redLightDelayCheckTime = config.getInt("redLight-delay-checking-time", 600); + + // Load booleans + debugMode = config.getBoolean("developer-debug-mode.enabled", false); + wipeInventoryOnJoin = config.getBoolean("wipe-inventory-on-join", false); + handleJoinSpawnEvent = config.getBoolean("handle-player-join-spawn-event", true); + sendWelcomeTitle = config.getBoolean("send-welcome-title", true); + joinPlayerInvulnerable = config.getBoolean("join-player-invulnerable", true); + leavePlayerInvulnerable = config.getBoolean("leave-player-invulnerable", true); + disableGlobalHunger = config.getBoolean("disable-global-hunger-drain", false); + disableInGameHunger = config.getBoolean("disable-in-game-hunger-drain", true); + losersSpectateGame = config.getBoolean("losers-spectate-game", true); + runWinCommands = config.getBoolean("run-win-commands", true); + runLoseCommands = config.getBoolean("run-lose-commands", true); + smiteLosingPlayers = config.getBoolean("smite-losing-players", true); + + // Load lists + disabledWorldsList = config.getStringList("disabled-worlds"); + blockedInGameCommandsList = config.getStringList("blocked-commands-in-game"); + winCommandsList = config.getStringList("win-commands-list"); + loseCommandsList = config.getStringList("lose-commands-list"); + + // Load materials + topTriggerBlock = Material.getMaterial(config.getString("top-trigger-block", "COAL_BLOCK")); + bottomTriggerBlock = Material.getMaterial(config.getString("bottom-trigger-block", "GOLD_BLOCK")); + + // Load locations + String lobbyWorld = config.getString("lobby-position.world-name", "world"); + double lobbyX = config.getDouble("lobby-position.x", -233.0); + double lobbyY = config.getDouble("lobby-position.y", 52.2); + double lobbyZ = config.getDouble("lobby-position.z", 24.0); + float lobbyYaw = (float) config.getDouble("lobby-position.yaw", 0.0); + float lobbyPitch = (float) config.getDouble("lobby-position.pitch", -0.0); + + World lobbyBukkitWorld; + try { + lobbyBukkitWorld = Bukkit.getWorld(lobbyWorld); + } catch (NullPointerException e) { + lobbyBukkitWorld = Bukkit.getServer().getWorlds().get(0); + } + lobbyLocation = new Location(lobbyBukkitWorld, lobbyX, lobbyY, lobbyZ, lobbyYaw, lobbyPitch); + + String arenaWorld = config.getString("arena-start.world-name", "world"); + double arenaX = config.getDouble("arena-start.x", -220.5); + double arenaY = config.getDouble("arena-start.y", 50.0); + double arenaZ = config.getDouble("arena-start.z", 161.5); + float arenaYaw = (float) config.getDouble("arena-start.yaw", 0.0); + float arenaPitch = (float) config.getDouble("arena-start.pitch", -6.0); + + World arenaBukkitWorld; + try { + arenaBukkitWorld = Bukkit.getWorld(arenaWorld); + } catch (NullPointerException e) { + arenaBukkitWorld = Bukkit.getServer().getWorlds().get(0); + } + arenaStartLocation = new Location(arenaBukkitWorld, arenaX, arenaY, arenaZ, arenaYaw, arenaPitch); + + String spectateWorld = config.getString("arena-spectate.world-name", "world"); + double spectateX = config.getDouble("arena-spectate.x", -220.5); + double spectateY = config.getDouble("arena-spectate.y", 50.0); + double spectateZ = config.getDouble("arena-spectate.z", 161.5); + float spectateYaw = (float) config.getDouble("arena-spectate.yaw", 0.0); + float spectatePitch = (float) config.getDouble("arena-spectate.pitch", -6.0); + + World spectateBukkitWorld; + try { + spectateBukkitWorld = Bukkit.getWorld(spectateWorld); + } catch (NullPointerException e) { + spectateBukkitWorld = Bukkit.getServer().getWorlds().get(0); + } + spectateLocation = new Location(spectateBukkitWorld, spectateX, spectateY, spectateZ, spectateYaw, spectatePitch); + } + + // String getters + public String getWelcomeTitle() { + return welcomeTitle; + } + + public String getWelcomeSubTitle() { + return welcomeSubTitle; + } + + + // Integer getters + public int getArenaStartPlayerAmount() { + return arenaStartPlayerAmount; + } + + public int getGameStartCountdown() { + return gameStartCountdown; + } + + public int getTotalGameLength() { + return totalGameLength; + } + + public int getRedLightDelayCheckTime() { + return redLightDelayCheckTime; + } + + + // Boolean getters + public boolean isDebugMode() { + return debugMode; + } + + public boolean isWipeInventoryOnJoin() { + return wipeInventoryOnJoin; + } + + public boolean isHandleJoinSpawnEvent() { + return handleJoinSpawnEvent; + } + + public boolean isSendWelcomeTitle() { + return sendWelcomeTitle; + } + + public boolean isJoinPlayerInvulnerable() { + return joinPlayerInvulnerable; + } + + public boolean isLeavePlayerInvulnerable() { + return leavePlayerInvulnerable; + } + + public boolean isDisableGlobalHunger() { + return disableGlobalHunger; + } + + public boolean isDisableInGameHunger() { + return disableInGameHunger; + } + + public boolean isLosersSpectateGame() { + return losersSpectateGame; + } + + public boolean isRunWinCommands() { + return runWinCommands; + } + + public boolean isRunLoseCommands() { + return runLoseCommands; + } + + public boolean isSmiteLosingPlayers() { + return smiteLosingPlayers; + } + + + // List getters + public List getDisabledWorldsList() { + return disabledWorldsList; + } + + public List getBlockedInGameCommandsList() { + return blockedInGameCommandsList; + } + + public List getWinCommandsList() { + return winCommandsList; + } + + public List getLoseCommandsList() { + return loseCommandsList; + } + + + // Material getters + public Material getTopTriggerBlock() { + return topTriggerBlock; + } + + public Material getBottomTriggerBlock() { + return bottomTriggerBlock; + } + + + // Location getters + public Location getLobbyLocation() { + return lobbyLocation; + } + + public Location getArenaStartLocation() { + return arenaStartLocation; + } + + public Location getSpectateLocation() { + return spectateLocation; + } +} diff --git a/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java b/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java new file mode 100644 index 0000000..ac5f3f5 --- /dev/null +++ b/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java @@ -0,0 +1,263 @@ +package me.loving11ish.redlightgreenlight.managers.filemanagers; + +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.List; + +public class MessagesManager { + + private final FileConfiguration messages; + + // Strings + private String prefix; + private String joinedGame; + private String commandSendError; + private String failedJoinArena; + private String successfulLeaveGame; + private String playerNotInGame; + private String waitingForPlayers; + private String gameRunning; + private String noGameRunning; + private String spectatingGame; + private String roundEndTitle; + private String roundEndSubtitle; + private String greenLight; + private String redLight; + private String gameStartTitle; + private String gameStartSubtitle; + private String gameWinTitle; + private String gameWinSubtitle; + private String gameLoseTitle; + private String gameLoseSubtitle; + private String gameLeaveTitle; + private String gameLeaveSubtitle; + private String pluginReloadStart; + private String pluginReloadComplete; + private String disabledWorld; + private String noPermission; + private String unknownCommand; + + private String updateAvailable1; + private String updateAvailable2; + private String updateAvailable3; + private String noUpdateAvailable1; + private String noUpdateAvailable2; + private String noUpdateAvailable3; + private String updateError; + + // Booleans + private boolean sendRedLightTitle; + private boolean sendLeaveTitle; + + // Lists + private List consoleSyntaxError; + private List helpCommand; + + public MessagesManager(FileConfiguration messages) { + this.messages = messages; + } + + public void loadMessagesValues() { + // Strings + prefix = messages.getString("prefix", "&f[&4&lRL&r&c-&a&lGL&f]"); + joinedGame = messages.getString("joined-game", "&aYou have joined the game.\n&aNow prepare to move only when told!"); + commandSendError = messages.getString("command-send-error", "&cSorry, that command cannot be run during gameplay!"); + failedJoinArena = messages.getString("failed-join-arena", "&cYou are already part of a game.\n&cUse &e/redlight leave &cto return to main lobby."); + successfulLeaveGame = messages.getString("successful-leave-game", "&aYou left the game and were teleported back to the lobby!"); + playerNotInGame = messages.getString("player-not-in-game", "&cYou are not currently in a game!"); + waitingForPlayers = messages.getString("waiting-for-enough-players", "&eYou are now in the queue to play.&r\n&eNow waiting for enough players to begin the game.&r\n&eUse &b/redlight leave &eto leave the game."); + gameRunning = messages.getString("game-already-running", "&cSorry there is already a game running!"); + noGameRunning = messages.getString("no-game-running", "&cSorry there is not currently a game running!"); + spectatingGame = messages.getString("spectating-message", "&aYou are now spectating the arena! \n&aUse &b/redlight leave &a to return to spawn."); + roundEndTitle = messages.getString("round-end-title", "&eNo One Won The Game!"); + roundEndSubtitle = messages.getString("round-end-subtitle", "&a&lGG's All Round"); + greenLight = messages.getString("greenLight-message", "&aGreen Light"); + redLight = messages.getString("redLight-message", "&cRed Light"); + gameStartTitle = messages.getString("game-start-title", "&a&lLet The Race Begin!"); + gameStartSubtitle = messages.getString("game-start-subtitle", "&bBeat everyone to the finish line!"); + gameWinTitle = messages.getString("game-win-title", "&6&lCongratulations! You Made it!"); + gameWinSubtitle = messages.getString("game-win-subtitle", "&bLets wait and see who will join you"); + gameLoseTitle = messages.getString("game-loose-title", "&c&lOOF You didn't stand still!"); + gameLoseSubtitle = messages.getString("game-loose-subtitle", "&4Better luck next time!"); + gameLeaveTitle = messages.getString("game-leave-title", "&a&lYou Left The Game!"); + gameLeaveSubtitle = messages.getString("game-leave-subtitle", "&eThank you for playing!"); + pluginReloadStart = messages.getString("plugin-reload-beginning", "&aBeginning plugin reload..."); + pluginReloadComplete = messages.getString("plugin-reload-successful", "&aPlugin reload complete!"); + disabledWorld = messages.getString("disabled-world-message", "&4&lRedLight&r&c-&a&lGreenLight has been disabled in this world."); + noPermission = messages.getString("no-permission", "&cYou do not have permission to do that!"); + unknownCommand = messages.getString("unknown-command", "&cCommand not found! Use &e/redlight help."); + + updateAvailable1 = messages.getString("update-available.1", "&4*-------------------------------------------*"); + updateAvailable2 = messages.getString("update-available.2", "&cA new version is available!"); + updateAvailable3 = messages.getString("update-available.3", "&4*-------------------------------------------*"); + noUpdateAvailable1 = messages.getString("no-update-available.1", "&a*-------------------------------------------*"); + noUpdateAvailable2 = messages.getString("no-update-available.2", "&aPlugin is up to date!"); + noUpdateAvailable3 = messages.getString("no-update-available.3", "&a*-------------------------------------------*"); + updateError = messages.getString("update-check-failure", "&4Unable to check for updates! - &c"); + + // Booleans + sendRedLightTitle = messages.getBoolean("redLight-title-enable", true); + sendLeaveTitle = messages.getBoolean("show-leave-game-title", false); + + // Lists + consoleSyntaxError = messages.getStringList("console-syntax-error"); + helpCommand = messages.getStringList("help-command"); + } + + // String getters + public String getPrefix() { + return prefix; + } + + public String getJoinedGame() { + return joinedGame; + } + + public String getCommandSendError() { + return commandSendError; + } + + public String getFailedJoinArena() { + return failedJoinArena; + } + + public String getSuccessfulLeaveGame() { + return successfulLeaveGame; + } + + public String getPlayerNotInGame() { + return playerNotInGame; + } + + public String getWaitingForPlayers() { + return waitingForPlayers; + } + + public String getGameRunning() { + return gameRunning; + } + + public String getNoGameRunning() { + return noGameRunning; + } + + public String getSpectatingGame() { + return spectatingGame; + } + + public String getRoundEndTitle() { + return roundEndTitle; + } + + public String getRoundEndSubtitle() { + return roundEndSubtitle; + } + + public String getGreenLight() { + return greenLight; + } + + public String getRedLight() { + return redLight; + } + + public String getGameStartTitle() { + return gameStartTitle; + } + + public String getGameStartSubtitle() { + return gameStartSubtitle; + } + + public String getGameWinTitle() { + return gameWinTitle; + } + + public String getGameWinSubtitle() { + return gameWinSubtitle; + } + + public String getGameLoseTitle() { + return gameLoseTitle; + } + + public String getGameLoseSubtitle() { + return gameLoseSubtitle; + } + + public String getGameLeaveTitle() { + return gameLeaveTitle; + } + + public String getGameLeaveSubtitle() { + return gameLeaveSubtitle; + } + + public String getPluginReloadStart() { + return pluginReloadStart; + } + + public String getPluginReloadComplete() { + return pluginReloadComplete; + } + + public String getDisabledWorld() { + return disabledWorld; + } + + public String getNoPermission() { + return noPermission; + } + + public String getUnknownCommand() { + return unknownCommand; + } + + public String getUpdateAvailable1() { + return updateAvailable1; + } + + public String getUpdateAvailable2() { + return updateAvailable2; + } + + public String getUpdateAvailable3() { + return updateAvailable3; + } + + public String getNoUpdateAvailable1() { + return noUpdateAvailable1; + } + + public String getNoUpdateAvailable2() { + return noUpdateAvailable2; + } + + public String getNoUpdateAvailable3() { + return noUpdateAvailable3; + } + + public String getUpdateError() { + return updateError; + } + + + // Boolean getters + public boolean isSendRedLightTitle() { + return sendRedLightTitle; + } + + public boolean isSendLeaveTitle() { + return sendLeaveTitle; + } + + + // List getters + public List getConsoleSyntaxError() { + return consoleSyntaxError; + } + + public List getHelpCommand() { + return helpCommand; + } +} diff --git a/src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java b/src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java new file mode 100644 index 0000000..537dde2 --- /dev/null +++ b/src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java @@ -0,0 +1,13 @@ +package me.loving11ish.redlightgreenlight.tasks; + +import me.loving11ish.redlightgreenlight.RedLightGreenLight; +import org.bukkit.Bukkit; + +public class OnlinePlayerTasks implements Runnable { + + @Override + public void run() { + RedLightGreenLight.getPlugin().onlinePlayers.clear(); + RedLightGreenLight.getPlugin().onlinePlayers.addAll(Bukkit.getOnlinePlayers()); + } +} diff --git a/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/JoinEvent.java b/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/JoinEvent.java index 5980c03..ec089d2 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/JoinEvent.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/JoinEvent.java @@ -1,7 +1,7 @@ package me.loving11ish.redlightgreenlight.updatesystem; import me.loving11ish.redlightgreenlight.RedLightGreenLight; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -9,7 +9,7 @@ public class JoinEvent implements Listener { - RedLightGreenLight plugin; + private final RedLightGreenLight plugin; public JoinEvent(RedLightGreenLight plugin) { this.plugin = plugin; @@ -22,12 +22,12 @@ public void onJoin(PlayerJoinEvent event) { new UpdateChecker(96866).getVersion(version -> { try { if (!(plugin.getDescription().getVersion().equalsIgnoreCase(version))) { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Update-1"))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Update-2"))); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Update-3"))); + MessageUtils.sendPlayer(player, this.plugin.getMessagesManager().getUpdateAvailable1()); + MessageUtils.sendPlayer(player, this.plugin.getMessagesManager().getUpdateAvailable2()); + MessageUtils.sendPlayer(player, this.plugin.getMessagesManager().getUpdateAvailable3()); } - }catch (NullPointerException e){ - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Update-check-failure"))); + } catch (NullPointerException e) { + MessageUtils.sendPlayer(player, this.plugin.getMessagesManager().getUpdateError()); } }); } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/UpdateChecker.java b/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/UpdateChecker.java index be8c99c..34917b6 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/UpdateChecker.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/updatesystem/UpdateChecker.java @@ -2,9 +2,7 @@ import com.tcoded.folialib.FoliaLib; import me.loving11ish.redlightgreenlight.RedLightGreenLight; -import me.loving11ish.redlightgreenlight.utils.ColorUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; +import me.loving11ish.redlightgreenlight.utils.MessageUtils; import org.bukkit.util.Consumer; import java.io.IOException; @@ -14,23 +12,21 @@ public class UpdateChecker { - ConsoleCommandSender console = Bukkit.getConsoleSender(); - - private int resourceId; + private final int resourceId; public UpdateChecker(int resourceId) { this.resourceId = resourceId; } public void getVersion(final Consumer consumer) { - FoliaLib foliaLib = RedLightGreenLight.getFoliaLib(); - foliaLib.getImpl().runAsync((task) -> { + FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); + foliaLib.getScheduler().runAsync((task) -> { try (InputStream inputStream = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + this.resourceId).openStream(); Scanner scanner = new Scanner(inputStream)) { if (scanner.hasNext()) { consumer.accept(scanner.next()); } } catch (IOException exception) { - console.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Update-check-failure") + exception.getMessage())); + MessageUtils.sendConsole("error", RedLightGreenLight.getPlugin().getMessagesManager().getUpdateError() + exception.getMessage()); } }); } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/ColorUtils.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/ColorUtils.java index 98a9991..12a2913 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/utils/ColorUtils.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/ColorUtils.java @@ -1,5 +1,8 @@ package me.loving11ish.redlightgreenlight.utils; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.ChatColor; public class ColorUtils { @@ -10,21 +13,39 @@ public class ColorUtils { * @param text The string of text to apply color/effects to * @return Returns a string of text with color/effects applied */ - public static String translateColorCodes(String text){ + public static String translateColorCodes(String text) { + // Optionally parse MiniMessage format + if (containsMiniMessageTags(text)) { + MiniMessage miniMessage = MiniMessage.miniMessage(); + Component component = miniMessage.deserialize(text); + return LegacyComponentSerializer.legacySection().serialize(component); + } + + // Fallback to legacy color code handling with & and hex (#) codes String[] texts = text.split(String.format(WITH_DELIMITER, "&")); StringBuilder finalText = new StringBuilder(); - for (int i = 0; i < texts.length; i++){ - if (texts[i].equalsIgnoreCase("&")){ + for (int i = 0; i < texts.length; i++) { + if (texts[i].equalsIgnoreCase("&")) { i++; - if (texts[i].charAt(0) == '#'){ + if (texts[i].charAt(0) == '#') { finalText.append(net.md_5.bungee.api.ChatColor.of(texts[i].substring(0, 7)) + texts[i].substring(7)); - }else{ + } else { finalText.append(ChatColor.translateAlternateColorCodes('&', "&" + texts[i])); } - }else{ + } else { finalText.append(texts[i]); } } return finalText.toString(); } + + /** + * Checks if a string contains MiniMessage tags, based on typical tags like , , etc. + * @param text The text to check + * @return True if MiniMessage tags are detected + */ + private static boolean containsMiniMessageTags(String text) { + // A basic check for some common MiniMessage tags like , , etc. + return text.matches(".*<(red|green|blue|bold|italic|reset|underlined|hover|click|obfuscated).*>"); + } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/CountDownTasksUtils.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/CountDownTasksUtils.java index 0a60432..ae24264 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/utils/CountDownTasksUtils.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/CountDownTasksUtils.java @@ -21,34 +21,28 @@ public class CountDownTasksUtils { - private static FoliaLib foliaLib = RedLightGreenLight.getFoliaLib(); + private static final FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); public static WrappedTask wrappedTask1; public static WrappedTask wrappedTask2; public static WrappedTask wrappedTask3; public static WrappedTask wrappedTask4; - private static List losecommands = RedLightGreenLight.getPlugin().getConfig().getStringList("Lose-commands-list"); - - final static double x = RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-Start-x"); - final static double y = RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-Start-y"); - final static double z = RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-Start-z"); - final static float yaw = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-Start-yaw"); - final static float pitch = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-Start-pitch"); + private static final List loseCommands = RedLightGreenLight.getPlugin().getConfigManager().getLoseCommandsList(); public static void runTaskStartArena1(){ - wrappedTask1 = foliaLib.getImpl().runTimerAsync(new Runnable() { - Integer time = RedLightGreenLight.getPlugin().getConfig().getInt("Game-starting-countdown-length"); + wrappedTask1 = foliaLib.getScheduler().runTimerAsync(new Runnable() { + Integer time = RedLightGreenLight.getPlugin().getConfigManager().getGameStartCountdown(); @Override public void run() { if (time == 1){ ArrayList playersInGame = new ArrayList<>(GameManager.getGame1()); for (UUID uuid : playersInGame) { Player player = (Player) Bukkit.getServer().getOfflinePlayer(uuid); - Location location = new Location(player.getWorld(), x, y, z, yaw, pitch); + Location location = RedLightGreenLight.getPlugin().getConfigManager().getArenaStartLocation(); PaperLib.teleportAsync(player, location); player.setWalkSpeed(0.0f); - foliaLib.getImpl().runAtEntityLater(player, () -> + foliaLib.getScheduler().runAtEntityLater(player, () -> player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20 * 10, 100000, false, false, false)), 50L, TimeUnit.MILLISECONDS); } CountDownTasksUtils.runTaskGoGame1(); @@ -71,7 +65,7 @@ public void run() { } public static void runTaskGoGame1(){ - wrappedTask2 = foliaLib.getImpl().runTimerAsync(new Runnable() { + wrappedTask2 = foliaLib.getScheduler().runTimerAsync(new Runnable() { Integer time = 10; @Override public void run() { @@ -79,17 +73,17 @@ public void run() { ArrayList playersInGame = new ArrayList<>(GameManager.getGame1()); for (UUID uuid : playersInGame) { Player player = (Player) Bukkit.getServer().getOfflinePlayer(uuid); - player.setInvulnerable(RedLightGreenLight.getPlugin().getConfig().getBoolean("Join-player-invulnerable")); + player.setInvulnerable(RedLightGreenLight.getPlugin().getConfigManager().isJoinPlayerInvulnerable()); player.setHealth(20.0); player.setFoodLevel(20); if (!(player.hasPermission("redlight.bypass.gamemode") || player.hasPermission("redlight.*") || player.isOp())) { player.setGameMode(GameMode.ADVENTURE); } - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-start-title")), - ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-start-subtitle")), 20, 80, 20); + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameStartTitle()), + ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameStartSubtitle()), 20, 80, 20); player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_PLACE, 2, 2); player.setWalkSpeed(0.2f); - foliaLib.getImpl().runAtEntityLater(player, () -> + foliaLib.getScheduler().runAtEntityLater(player, () -> player.removePotionEffect(PotionEffectType.JUMP), 50L, TimeUnit.MILLISECONDS); GameManager.setCountDown(0); GameManager.addToRound(player); @@ -112,8 +106,8 @@ public void run() { } public static void game1Timer() { - wrappedTask3 = foliaLib.getImpl().runTimerAsync(new Runnable() { - Integer time = RedLightGreenLight.getPlugin().getConfig().getInt("Total-game-length"); + wrappedTask3 = foliaLib.getScheduler().runTimerAsync(new Runnable() { + Integer time = RedLightGreenLight.getPlugin().getConfigManager().getTotalGameLength(); @Override public void run() { if (time == 30) { @@ -163,13 +157,13 @@ public void run() { for (UUID uuid : playersInGame) { Player player = (Player) Bukkit.getServer().getOfflinePlayer(uuid); String target = player.getName(); - foliaLib.getImpl().runNextTick((task) -> + foliaLib.getScheduler().runNextTick((task) -> getServer().dispatchCommand(Bukkit.getConsoleSender(), "execute at " + player.getName() + " run summon minecraft:lightning_bolt ~ ~ ~")); - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Round-end-title")), - ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Round-end-subtitle")), 10, 30, 10); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Run-lose-commands")) { - for (String string : losecommands) { - foliaLib.getImpl().runNextTick((task) -> + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getRoundEndTitle()), + ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getRoundEndSubtitle()), 10, 30, 10); + if (RedLightGreenLight.getPlugin().getConfigManager().isRunLoseCommands()) { + for (String string : loseCommands) { + foliaLib.getScheduler().runNextTick((task) -> getServer().dispatchCommand(Bukkit.getConsoleSender(), string.replace("%player%", target))); } } @@ -183,34 +177,34 @@ public void run() { Random random = new Random(); int r = random.nextInt(10); if (r == 5 || r == 8 || r == 2) { - if (time < RedLightGreenLight.getPlugin().getConfig().getInt("Total-game-length") -5){ + if (time < RedLightGreenLight.getPlugin().getConfigManager().getTotalGameLength() -5){ coolDownTimer(); - GameManager.setLightgreen(1); + GameManager.setLightGreen(1); ArrayList playersInGame = new ArrayList<>(GameManager.getGame1()); for (UUID uuid : playersInGame) { Player player = (Player) Bukkit.getServer().getOfflinePlayer(uuid); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("RedLight-title-enable")) { - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("RedLight-message")), + if (RedLightGreenLight.getPlugin().getMessagesManager().isSendRedLightTitle()) { + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getRedLight()), ColorUtils.translateColorCodes(" "), 10, 30, 10); } - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("RedLight-message"))); + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getRedLight()); } } }else { - GameManager.setLightgreen(0); + GameManager.setLightGreen(0); ArrayList playersInGame = new ArrayList<>(GameManager.getGame1()); for (UUID uuid : playersInGame) { Player player = (Player) Bukkit.getServer().getOfflinePlayer(uuid); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("GreenLight-message"))); + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getGreenLight()); } } - if (GameManager.getGame1().size() == 0 || GameManager.getPlayersInRound().size() == 0){ - if (!(GameManager.getSpectatingPlayers().size() == 0)){ + if (GameManager.getGame1().isEmpty() || GameManager.getPlayersInRound().isEmpty()){ + if (!(GameManager.getSpectatingPlayers().isEmpty())){ GameManager.endSpectatingGame(); } GameManager.getPlayersInRound().clear(); GameManager.getGame1().clear(); - GameManager.setLightgreen(0); + GameManager.setLightGreen(0); GameManager.setGameRunning(0); wrappedTask3.cancel(); @@ -222,10 +216,10 @@ public void run() { }, 1L, 1L, TimeUnit.SECONDS); } - private static long repeatTime = RedLightGreenLight.getPlugin().getConfig().getInt("RedLight-delay-checking-time"); + private static final long repeatTime = RedLightGreenLight.getPlugin().getConfigManager().getRedLightDelayCheckTime(); public static void coolDownTimer(){ - wrappedTask4 = foliaLib.getImpl().runTimerAsync(new Runnable() { + wrappedTask4 = foliaLib.getScheduler().runTimerAsync(new Runnable() { Integer time = 2; @Override public void run() { diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/GameManager.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/GameManager.java index 1a0a8b7..f968629 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/utils/GameManager.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/GameManager.java @@ -11,167 +11,149 @@ public class GameManager { - private static Map game1 = new HashMap<>(); - private static Map round = new HashMap<>(); - private static Map spectating = new HashMap<>(); - public static Integer lightgreen = 0; - public static Integer gamerunning = 0; - public static Integer countdown = 0; - - public static void addToGame1(Player player){ + private static final Map game1 = new HashMap<>(); + private static final Map round = new HashMap<>(); + private static final Map spectating = new HashMap<>(); + public static Integer lightGreen = 0; + public static Integer gameRunning = 0; + public static Integer countDown = 0; + + public static void addToGame1(Player player) { UUID uuid = player.getUniqueId(); game1.put(uuid, player); } - public static void leaveGame1(Player player){ + public static void leaveGame1(Player player) { UUID uuid = player.getUniqueId(); game1.remove(uuid); } - public static Set getGame1(){ + public static Set getGame1() { return game1.keySet(); } - public static void addToRound(Player player){ + public static void addToRound(Player player) { UUID uuid = player.getUniqueId(); round.put(uuid, player); } - public static void leaveRound(Player player){ + public static void leaveRound(Player player) { UUID uuid = player.getUniqueId(); round.remove(uuid); } - public static Set getPlayersInRound(){ + public static Set getPlayersInRound() { return round.keySet(); } - public static void addToSpectating(Player player){ + public static void addToSpectating(Player player) { UUID uuid = player.getUniqueId(); spectating.put(uuid, player); } - public static void leaveSpectating(Player player){ + public static void leaveSpectating(Player player) { UUID uuid = player.getUniqueId(); spectating.remove(uuid); } - public static Set getSpectatingPlayers(){ + public static Set getSpectatingPlayers() { return spectating.keySet(); } - public static Integer getLightgreen() { - return lightgreen; + public static Integer getLightGreen() { + return lightGreen; } - public static void setLightgreen(Integer lightgreen) { - GameManager.lightgreen = lightgreen; + public static void setLightGreen(Integer lightGreen) { + GameManager.lightGreen = lightGreen; } public static Integer getGameRunning() { - return gamerunning; + return gameRunning; } public static Integer getCountDown() { - return countdown; + return countDown; } public static void setCountDown(Integer countdown) { - GameManager.countdown = countdown; + GameManager.countDown = countdown; } public static void setGameRunning(Integer gamerunning) { - GameManager.gamerunning = gamerunning; + GameManager.gameRunning = gamerunning; } - public static void teleportToLobby(Player player){ - double x = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-x"); - double y = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-y"); - double z = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-z"); - float yaw = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-yaw"); - float pitch = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-pitch"); - Location location = new Location(player.getWorld(), x, y, z, yaw, pitch); + public static void teleportToLobby(Player player) { + Location location = RedLightGreenLight.getPlugin().getConfigManager().getLobbyLocation(); PaperLib.teleportAsync(player, location); - player.setInvulnerable(RedLightGreenLight.getPlugin().getConfig().getBoolean("Leave-player-invulnerable")); - if (!(player.hasPermission("redlight.bypass.gamemode")||player.hasPermission("redlight.*")||player.isOp())){ + player.setInvulnerable(RedLightGreenLight.getPlugin().getConfigManager().isLeavePlayerInvulnerable()); + if (!(player.hasPermission("redlight.bypass.gamemode") || player.hasPermission("redlight.*") || player.isOp())) { player.setGameMode(GameMode.SURVIVAL); } } - public static void spectatorTeleportToArena(Player player){ - double x = RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-spectate-x"); - double y = RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-spectate-y"); - double z = RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-spectate-z"); - float yaw = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-spectate-yaw"); - float pitch = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("Arena-spectate-pitch"); - Location location = new Location(player.getWorld(), x, y, z, yaw, pitch); + public static void spectatorTeleportToArena(Player player) { + Location location = RedLightGreenLight.getPlugin().getConfigManager().getSpectateLocation(); PaperLib.teleportAsync(player, location); player.setGameMode(GameMode.SPECTATOR); GameManager.addToSpectating(player); } - public static void startGameArena1(Player player){ - if (getGame1().size() == RedLightGreenLight.getPlugin().getConfig().getInt("Arena-start-size")){ + public static void startGameArena1(Player player) { + if (getGame1().size() == RedLightGreenLight.getPlugin().getConfigManager().getArenaStartPlayerAmount()) { CountDownTasksUtils.runTaskStartArena1(); - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Joined-game"))); - }else { - player.sendMessage(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Waiting-for-enough-players"))); + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getJoinedGame()); + } else { + MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getWaitingForPlayers()); } } - public static void endSpectatingGame(){ + public static void endSpectatingGame() { ArrayList spectators = new ArrayList<>(GameManager.getSpectatingPlayers()); - for (int i = 0; i < spectators.size(); i++){ - UUID uuid = spectators.get(i); + for (UUID uuid : spectators) { Player player = (Player) Bukkit.getServer().getOfflinePlayer(uuid); - double x = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-x"); - double y = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-y"); - double z = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-z"); - float yaw = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-yaw"); - float pitch = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-pitch"); - Location location = new Location(player.getWorld(), x, y, z, yaw, pitch); - PaperLib.teleportAsync(player, location); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Show-leave-game-title")){ - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-leave-title")), - ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-leave-subtitle")), 20, 80, 20); - } - PlayerInventoryHandler.clearInventory(player); - PlayerInventoryHandler.restoreInventory(player); - if (!(player.hasPermission("redlight.bypass.gamemode")||player.hasPermission("redlight.*")||player.isOp())){ - player.setGameMode(GameMode.SURVIVAL); - } - player.setInvulnerable(RedLightGreenLight.getPlugin().getConfig().getBoolean("Leave-player-invulnerable")); - player.setFoodLevel(20); - GameManager.leaveSpectating(player); + RedLightGreenLight.getPlugin().getFoliaLib().getScheduler().runAtEntity(player, (task) -> { + Location location = RedLightGreenLight.getPlugin().getConfigManager().getLobbyLocation(); + PaperLib.teleportAsync(player, location); + if (RedLightGreenLight.getPlugin().getMessagesManager().isSendLeaveTitle()) { + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameLeaveTitle()), + ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameLeaveSubtitle()), 20, 80, 20); + } + PlayerInventoryHandler.clearInventory(player); + PlayerInventoryHandler.restoreInventory(player); + if (!(player.hasPermission("redlight.bypass.gamemode") || player.hasPermission("redlight.*") || player.isOp())) { + player.setGameMode(GameMode.SURVIVAL); + } + player.setInvulnerable(RedLightGreenLight.getPlugin().getConfigManager().isLeavePlayerInvulnerable()); + player.setFoodLevel(20); + GameManager.leaveSpectating(player); + }); } } - public static void endGameArena1(){ + public static void endGameArena1() { ArrayList game = new ArrayList<>(GameManager.getGame1()); - for (int i = 0; i < game.size(); i++){ - UUID uuid = game.get(i); + for (UUID uuid : game) { Player player = (Player) Bukkit.getServer().getOfflinePlayer(uuid); - double x = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-x"); - double y = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-y"); - double z = RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-z"); - float yaw = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-yaw"); - float pitch = (float) RedLightGreenLight.getPlugin().getConfig().getDouble("lobby-pitch"); - Location location = new Location(player.getWorld(), x, y, z, yaw, pitch); - PaperLib.teleportAsync(player, location); - if (RedLightGreenLight.getPlugin().getConfig().getBoolean("Show-leave-game-title")){ - player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-leave-title")), - ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getConfig().getString("Game-leave-subtitle")), 20, 80, 20); - } - PlayerInventoryHandler.clearInventory(player); - PlayerInventoryHandler.restoreInventory(player); - if (!(player.hasPermission("redlight.bypass.gamemode")||player.hasPermission("redlight.*")||player.isOp())){ - player.setGameMode(GameMode.SURVIVAL); - } - player.setInvulnerable(RedLightGreenLight.getPlugin().getConfig().getBoolean("Leave-player-invulnerable")); - player.setFoodLevel(20); - GameManager.leaveGame1(player); - GameManager.leaveRound(player); - GameManager.setGameRunning(0); + RedLightGreenLight.getPlugin().getFoliaLib().getScheduler().runAtEntity(player, (task) -> { + Location location = RedLightGreenLight.getPlugin().getConfigManager().getLobbyLocation(); + PaperLib.teleportAsync(player, location); + if (RedLightGreenLight.getPlugin().getMessagesManager().isSendLeaveTitle()) { + player.sendTitle(ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameLeaveTitle()), + ColorUtils.translateColorCodes(RedLightGreenLight.getPlugin().getMessagesManager().getGameLeaveSubtitle()), 20, 80, 20); + } + PlayerInventoryHandler.clearInventory(player); + PlayerInventoryHandler.restoreInventory(player); + if (!(player.hasPermission("redlight.bypass.gamemode") || player.hasPermission("redlight.*") || player.isOp())) { + player.setGameMode(GameMode.SURVIVAL); + } + player.setInvulnerable(RedLightGreenLight.getPlugin().getConfigManager().isLeavePlayerInvulnerable()); + player.setFoodLevel(20); + GameManager.leaveGame1(player); + GameManager.leaveRound(player); + }); } + GameManager.setGameRunning(0); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java new file mode 100644 index 0000000..07ea603 --- /dev/null +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java @@ -0,0 +1,107 @@ +package me.loving11ish.redlightgreenlight.utils; + +import me.loving11ish.redlightgreenlight.RedLightGreenLight; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; + +public class MessageUtils { + + private static final ConsoleCommandSender console = Bukkit.getConsoleSender(); + + public static String prefix = RedLightGreenLight.getPlugin().getMessagesManager().getPrefix(); + + private static boolean debug; + private static String levelColor; + + /** + * @param message The message to be sent to the console with prefix applied. Supports color codes. + */ + public static void sendConsole(String message) { + console.sendMessage(ColorUtils.translateColorCodes(prefix + " &r" + message)); + } + + /** + * @param player The player to send the message too. + * @param message The message to be sent with prefix applied. Supports color codes. + */ + public static void sendPlayer(Player player, String message) { + player.sendMessage(ColorUtils.translateColorCodes(prefix + " &r" + message)); + } + + /** + * @param offlinePlayer The offlinePlayer to send the message too. + * @param message The message to be sent with prefix applied. Supports color codes. + */ + public static void sendOfflinePlayer(OfflinePlayer offlinePlayer, String message) { + Player player = offlinePlayer.getPlayer(); + if (player != null) { + player.sendMessage(ColorUtils.translateColorCodes(prefix + " &r" + message)); + } else { + sendConsole("error", "Player " + offlinePlayer.getName() + " is not online!"); + } + } + + /** + * @param message The message to be sent with prefix applied. Supports color codes. + * @param level The log level of the message. Supports info, warning, error, and severe. + */ + public static void sendConsole(String level, String message) { + level = setDebugLevel(level); + console.sendMessage(ColorUtils.translateColorCodes(prefix + " &r[" + level + "&r] - " + levelColor + message)); + } + + /** + * @param sender The command sender to send the message too. + * @param message The message to be sent with prefix applied. Supports color codes. + */ + public static void sendSender(CommandSender sender, String message) { + sender.sendMessage(ColorUtils.translateColorCodes(prefix + " &r" + message)); + } + + /** + * @param message The debug message to be sent with prefix applied. Supports color codes. + */ + public static void sendDebugConsole(String message) { + if (debug) { + console.sendMessage(ColorUtils.translateColorCodes("&6UStats-Debug&7: " + message)); + } + } + + /** + * @param message The debug message to be sent with prefix applied. Supports color codes. + * @param level The log level of the message. Supports info, warning, error, and severe. + */ + public static void sendDebugConsole(String level, String message) { + if (debug) { + level = setDebugLevel(level); + console.sendMessage(ColorUtils.translateColorCodes("&6UStats-Debug&7: [" + level + "&7] - " + levelColor + message)); + } + } + + private static String setDebugLevel(String level) { + if (level.equalsIgnoreCase("info")) { + levelColor = "&a"; + level = levelColor + level; + } else if (level.equalsIgnoreCase("warning")) { + levelColor = "&e"; + level = levelColor + level; + } else if (level.equalsIgnoreCase("error")) { + levelColor = "&c"; + level = levelColor + level; + } else if (level.equalsIgnoreCase("severe")) { + levelColor = "&4"; + level = levelColor + level; + } else { + levelColor = "&7"; + level = levelColor + level; + } + return level; + } + + public static void setDebug(boolean debug) { + MessageUtils.debug = debug; + } +} diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/PlayerInventoryHandler.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/PlayerInventoryHandler.java index 40d83fd..6a409dd 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/utils/PlayerInventoryHandler.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/PlayerInventoryHandler.java @@ -10,8 +10,8 @@ public class PlayerInventoryHandler { - private static Map items = new HashMap<>(); - private static Map armor = new HashMap<>(); + private static final Map items = new HashMap<>(); + private static final Map armor = new HashMap<>(); public static void storeAndClearInventory(Player player){ UUID uuid = player.getUniqueId(); @@ -19,11 +19,7 @@ public static void storeAndClearInventory(Player player){ ItemStack[] armorContents = player.getInventory().getArmorContents(); items.put(uuid, contents); armor.put(uuid, armorContents); - player.getInventory().clear(); - player.getInventory().setHelmet(null); - player.getInventory().setChestplate(null); - player.getInventory().setLeggings(null); - player.getInventory().setBoots(null); + clearInventory(player); } public static void restoreInventory(Player player) { UUID uuid = player.getUniqueId(); diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/ReloadingUtils.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/ReloadingUtils.java new file mode 100644 index 0000000..07735a1 --- /dev/null +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/ReloadingUtils.java @@ -0,0 +1,23 @@ +package me.loving11ish.redlightgreenlight.utils; + +public class ReloadingUtils { + + // Below method originally created by ProtocolLib! + // It is a good way of checking this so there is no point recreating the wheel! + // @ProtocolLib devs: Please don't crucify me for using this!! + + public static boolean isCurrentlyReloading() { + StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); + + for (StackTraceElement element : stackTrace) { + String clazz = element.getClassName(); + + if (clazz.startsWith("org.bukkit.craftbukkit.") + && clazz.endsWith(".CraftServer") + && element.getMethodName().equals("reload")) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/VersionCheckerUtils.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/VersionCheckerUtils.java index b8a7ab5..32808ee 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/utils/VersionCheckerUtils.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/VersionCheckerUtils.java @@ -1,34 +1,47 @@ package me.loving11ish.redlightgreenlight.utils; +import me.loving11ish.redlightgreenlight.RedLightGreenLight; import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; import java.util.regex.PatternSyntaxException; public class VersionCheckerUtils { - ConsoleCommandSender console = Bukkit.getConsoleSender(); - - private final String serverPackage = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + private String serverPackage; private int version; + private boolean versionCheckedSuccessfully = false; + + public VersionCheckerUtils() { + try { + serverPackage = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + } catch (ArrayIndexOutOfBoundsException e) { + serverPackage = null; + } + } public void setVersion() { try { - version = Integer.parseInt(serverPackage.split("_")[1]); - }catch (NumberFormatException | PatternSyntaxException e){ - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Unable to process server version!")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Some features may break unexpectedly!")); - console.sendMessage(ColorUtils.translateColorCodes("&6RedLightGreenLight: &4Report any issues to the developer!")); - console.sendMessage(ColorUtils.translateColorCodes("&c-------------------------------------------")); + version = RedLightGreenLight.getPlugin().getServerVersion().getServerMajorVersionNumber(); + versionCheckedSuccessfully = true; + } catch (NumberFormatException | PatternSyntaxException e) { + versionCheckedSuccessfully = false; + MessageUtils.sendConsole("&c-------------------------------------------"); + MessageUtils.sendConsole("&4Unable to process server version!"); + MessageUtils.sendConsole("&4Some features may break unexpectedly!"); + MessageUtils.sendConsole("&4Report any issues to the developer!"); + MessageUtils.sendConsole("&c-------------------------------------------"); } } public String getServerPackage() { - return serverPackage; + return serverPackage != null ? serverPackage : "Unknown"; } public int getVersion() { return version; } + + public boolean isVersionCheckedSuccessfully() { + return versionCheckedSuccessfully; + } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java b/src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java new file mode 100644 index 0000000..627dfd2 --- /dev/null +++ b/src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java @@ -0,0 +1,65 @@ +package me.loving11ish.redlightgreenlight.versionsystems; + +public enum ServerVersion { + + v1_8_R1, + v1_8_R2, + v1_8_R3, + v1_9_R1, + v1_9_R2, + v1_10_R1, + v1_11_R1, + v1_12_R1, + v1_13_R1, + v1_13_R2, + v1_14_R1, + v1_15_R1, + v1_16_R1, + v1_16_R2, + v1_16_R3, + v1_17_R1, + v1_18_R1, + v1_18_R2, + v1_19_R1, + v1_19_R2, + v1_19_R3, + v1_20_R1, + v1_20_R2, + v1_20_R3, + v1_20_R4, + v1_20_R5, + v1_21_R1, + v1_21_R2, + v1_21_R3, + v1_21_R4, + Other; + + public boolean serverVersionEqual(ServerVersion version) { + return this.equals(version); + } + + public boolean serverVersionGreaterThanOrEqual(ServerVersion version) { + return this.ordinal() >= version.ordinal(); + } + + + public boolean serverVersionGreaterThan(ServerVersion version1, ServerVersion version2) { + return version1.ordinal() > version2.ordinal(); + } + + public boolean serverVersionLessThan(ServerVersion version1, ServerVersion version2) { + return version1.ordinal() < version2.ordinal(); + } + + public String getServerVersionName() { + return this.name(); + } + + public int getOrdinalServerVersionNumber() { + return this.ordinal(); + } + + public int getServerMajorVersionNumber() { + return Integer.parseInt(this.name().split("_")[1]); + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index cd739b8..64809ed 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -8,49 +8,57 @@ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #RedLightGreenLight config for version: ${project.version} +#General settings +developer-debug-mode: + #Do you want to see a lot of debug messages in console when most actions are performed? + #OPTIONS: 'true'/'false', PLACEHOLDERS: none, DEFAULT:'false' + enabled: false + #Do you want players inventories to be wiped on join? #This can bypassed using permission node 'redlight.bypass.joinwipe' -Wipe-inventory-on-join: false +wipe-inventory-on-join: false #Do you want RedLight-GreenLight to handle server join spawn location (World/Server join lobby)? -Handle-player-join-spawn-event: true +handle-player-join-spawn-event: true #Do you want to send a welcome title for players joining the server? -Send-welcome-title: true +send-welcome-title: true #Welcome-player-to-server-title: -Welcome-player-title: "&a&lWelcome To RedLight-GreenLight!" -Welcome-player-subtitle: "&ePlease use /redlight join" +welcome-player-title: "&a&lWelcome To RedLight-GreenLight!" +welcome-player-subtitle: "&ePlease use /redlight join" #Do you want to disable the plugin use in certain worlds? #To not use this, comment out the world's listed below and add '[]' after 'Disabled-worlds:' -Disabled-worlds: +disabled-worlds: - "world_nether" - "world_the_end" #Do you want the player to be made invulnerable on join? -Join-player-invulnerable: true +join-player-invulnerable: true #Do you want the player to be made invulnerable on game leave? -Leave-player-invulnerable: true +leave-player-invulnerable: true #Do you want to disable ALL hunger loss? -Disable-global-hunger-drain: false +disable-global-hunger-drain: false #Do you want to disable hunger loss ONLY for players in a RedLight-GreenLight game? -Disable-in-game-hunger-drain: true +disable-in-game-hunger-drain: true #World/server join lobby position #Join-lobby-position: -lobby-x: -233.0 -lobby-y: 52.2 -lobby-z: 24.0 -lobby-yaw: 0.0 -lobby-pitch: -0.0 +lobby-position: + world-name: "world" + x: -233.0 + y: 52.2 + z: 24.0 + yaw: 0.0 + pitch: -0.0 #List below commands that are blocked during gameplay. #This can bypassed using permission node 'redlight.bypass.commands' #Any changes made to this list require a server restart or reload to take effect! -Blocked-commands-in-game: +blocked-commands-in-game: - "/spawn" - "/home" - "/sethome" @@ -70,150 +78,65 @@ Blocked-commands-in-game: #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #How many players should be in the arena for the game to start? -Arena-start-size: 4 +arena-start-size: 4 #How long do you want the game starting countdown to be? (In seconds.) -Game-starting-countdown-length: 10 +game-starting-countdown-length: 10 #How long do you want the total length of the game? (In seconds. 300 = 5 mins) -Total-game-length: 300 +total-game-length: 300 #Set the arena starting position for the players #Arena-position: -Arena-Start-x: -220.5 -Arena-Start-y: 50.0 -Arena-Start-z: 161.5 -Arena-Start-yaw: 0.0 -Arena-Start-pitch: -6.0 +arena-start: + world-name: "world" + x: -220.5 + y: 50.0 + z: 161.5 + yaw: 0.0 + pitch: -6.0 #Do you want the losers to spectate the game in progress? -Losers-spectate-game: true +losers-spectate-game: true #Set the location of the spectator spawn. #Spectator-position: -Arena-spectate-x: -220.5 -Arena-spectate-y: 50.0 -Arena-spectate-z: 161.5 -Arena-spectate-yaw: 0.0 -Arena-spectate-pitch: -6.0 +arena-spectate: + world-name: "world" + x: -220.5 + y: 50.0 + z: 161.5 + yaw: 0.0 + pitch: -6.0 #The following section sets the detection of the WINNING ZONE. #Simply make the floor of the WINNING ZONE out of the below block combination. #EXAMPLE: Block under player - COAL_BLOCK #EXAMPLE: Block under (-Y) COAL_BLOCK - GOLD_BLOCK -Top-trigger-block: COAL_BLOCK -Bottom-trigger-block: GOLD_BLOCK +top-trigger-block: COAL_BLOCK +bottom-trigger-block: GOLD_BLOCK #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #Below sets how long of a delay there is before the RedLight movement detection checks for movement.# #This can be changed from '50 - 950'. ANYTHING OVER 950 WILL CAUSE ERRORS! # # DO NOT CHANGE THIS UNLESS YOU KNOW WHAT YOU'RE DOING! # -RedLight-delay-checking-time: 600 # +redLight-delay-checking-time: 600 # #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #Do you want to run any commands when a player wins? -Run-win-commands: true +run-win-commands: true #Enter the list of commands to be run below. (All commands are executed by the console) #Any changes made to this list require a server restart or reload to take effect! -Win-commands-list: +win-commands-list: - "xp add %player% 10 levels" - "effect give %player% minecraft:speed 10 1" #Do you want to run any commands when a player loses? -Run-lose-commands: true +run-lose-commands: true #Enter the list of commands to be run below. (All commands are executed by the console) #Any changes made to this list require a server restart or reload to take effect! -Lose-commands-list: +lose-commands-list: - "effect give %player% minecraft:poison 10 0" #Do you want players to be struck with lightning whn they loose? -Smite-losing-players: true - -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +smite-losing-players: true #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# -# ----[RedLight-GreenLight]---- # -# ----[By Loving11ish]---- # -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# -# ----[Plugin Messages File]---- # -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# - -#Game messages -Joined-game: "&aYou have joined the game.\n&aNow prepare to move only when told!" -Command-send-error: "&cSorry, that command cannot be run during gameplay!" -Failed-join-arena: "&cYou are already part of a game.\n&cUse &e/redlight leave &cto return to main lobby." -Successful-leave-game: "&aYou left the game and were teleported back to the lobby!" -Player-not-in-game: "&cYou are not currently in a &4&lRedLight&r&c-&a&lGreenLight &r&cgame!" -Waiting-for-enough-players: "&eYou are now in the queue to play.&r\n&eNow waiting for enough players to begin the game.&r\n&eUse &b/redlight leave &eto leave the game." -Game-already-running: "&cSorry there is already a &4&lRedLight&r&c-&a&lGreenLight &r&cgame running!" -No-game-running: "&cSorry there is not currently a &4&lRedLight&r&c-&a&lGreenLight &r&cgame running!" -Spectating-message: "&aYou are now spectating the arena! \n&aUse &b/redlight leave &a to return to spawn." - -Round-end-title: "&eNo One Won The Game!" -Round-end-subtitle: "&a&lGG's All Round" - -GreenLight-message: "&aGreen Light" -#Do you want the RedLight message to be sent as a title & in chat? -RedLight-title-enable: true -RedLight-message: "&cRed Light" - -Game-start-title: "&a&lLet The Race Begin!" -Game-start-subtitle: "&bBeat everyone to the finish line!" - -Game-win-title: "&6&lCongratulations! You Made it!" -Game-win-subtitle: "&bLets wait and see who will join you" - -Game-loose-title: "&c&lOOF You didn't stand still!" -Game-loose-subtitle: "&4Better luck next time!" - -#Do you want the players to be shown a title when they leave the game? -Show-leave-game-title: false -Game-leave-title: "&a&lYou Left The Game!" -Game-leave-subtitle: "&eThank you for playing!" - -#Incorrect-command-syntax-console: -Syntax-error-1: "&4Please provide an argument!" -Syntax-error-2: "&4redlight reload" -Syntax-error-3: "&4redlight help" - -Plugin-reload-beginning: "&aBeginning plugin reload..." -Plugin-reload-successful: "&aPlugin reload complete!" -Reload-command-no-permission: "&4You do not have the permission &eredlight.reload &4needed to run that command" -Disabled-world-message: "&4&lRedLight&r&c-&a&lGreenLight has been disabled in this world." -Joinall-command-no-permission: "&4You do not have the permission &eredlight.command.joinall &4needed to run that command" -Leaveall-command-no-permission: "&4You do not have the permission &eredlight.command.leaveall &4needed to run that command" - -#Plugin-update-available: -Update-1: "&4*-------------------------------------------*" -Update-2: "&bRedLight-GreenLight &c- A new version is available!" -Update-3: "&4*-------------------------------------------*" - -#Plugin-no-new-update: -No-update-1: "&a*-------------------------------------------*" -No-update-2: "&bRedLight-GreenLight &a- Plugin is up to date!" -No-update-3: "&a*-------------------------------------------*" -Update-check-failure: "&bRedLight-GreenLight &4- Unable to check for updates! - &c" - -#Plugin-help-menu -Help-1: "&e[--------------- &b[RedLight-GreenLight] &e----------------]" -Help-2: "&f/red join &7- &dThis command joins the game." -Help-3: "&f/red leave &7- &dThis command leaves the game." -Help-4: "&f/red joinall &7- &dThis command adds all players to the game." -Help-5: "&f/red leaveall &7- &dThis forces all players to leave the game." -Help-6: "&f/red help &7- &dThis command shows this help menu." -Help-7: "&f/red reload &7- &dThis command reloads the config." -Help-8: "&e[------------------- &bPermissions &e---------------------]" -Help-9: "&f redlight.*" -Help-10: "&f redlight.help" -Help-11: "&f redlight.reload" -Help-12: "&f redlight.command.joinall" -Help-13: "&f redlight.command.leaveall" -Help-14: "&f redlight.bypass.joinwipe" -Help-15: "&f redlight.bypass.commands" -Help-16: "&f redlight.bypass.gamemode" -Help-17: "&e[---------------------------------------------------]" -Help-18: "&f Plugin Version: &a%version%" -Help-19: "&e[---------------------------------------------------]" - -Help-command-no-permission: "&4You do not have the permission &eredlight.help &4needed to run that command" - -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# \ No newline at end of file diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml new file mode 100644 index 0000000..8e1fa32 --- /dev/null +++ b/src/main/resources/messages.yml @@ -0,0 +1,91 @@ +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +# ----[RedLight-GreenLight]---- # +# ----[By Loving11ish]---- # +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +# ----[Plugin Messages File]---- # +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# +#RedLightGreenLight messages for version: ${project.version} + +#Prefix for all messages. +prefix: "&f[&4&lRL&r&c-&a&lGL&f]" + +#Game messages +joined-game: "&aYou have joined the game.\n&aNow prepare to move only when told!" +command-send-error: "&cSorry, that command cannot be run during gameplay!" +failed-join-arena: "&cYou are already part of a game.\n&cUse &e/redlight leave &cto return to main lobby." +successful-leave-game: "&aYou left the game and were teleported back to the lobby!" +player-not-in-game: "&cYou are not currently in a game!" +waiting-for-enough-players: "&eYou are now in the queue to play.&r\n&eNow waiting for enough players to begin the game.&r\n&eUse &b/redlight leave &eto leave the game." +game-already-running: "&cSorry there is already a game running!" +no-game-running: "&cSorry there is not currently a game running!" +spectating-message: "&aYou are now spectating the arena! \n&aUse &b/redlight leave &a to return to spawn." + +round-end-title: "&eNo One Won The Game!" +round-end-subtitle: "&a&lGG's All Round" + +greenLight-message: "&aGreen Light" +#Do you want the RedLight message to be sent as a title & in chat? +redLight-title-enable: true +redLight-message: "&cRed Light" + +game-start-title: "&a&lLet The Race Begin!" +game-start-subtitle: "&bBeat everyone to the finish line!" + +game-win-title: "&6&lCongratulations! You Made it!" +game-win-subtitle: "&bLets wait and see who will join you" + +game-loose-title: "&c&lOOF You didn't stand still!" +game-loose-subtitle: "&4Better luck next time!" + +#Do you want the players to be shown a title when they leave the game? +show-leave-game-title: false +game-leave-title: "&a&lYou Left The Game!" +game-leave-subtitle: "&eThank you for playing!" + +#Incorrect-command-syntax-console: +console-syntax-error: + - "&4Please provide an argument!\n" + - "&4redlight reload\n" + - "&4redlight help\n" + +plugin-reload-beginning: "&aBeginning plugin reload..." +plugin-reload-successful: "&aPlugin reload complete!" +disabled-world-message: "&4&lRedLight&r&c-&a&lGreenLight has been disabled in this world." +no-permission: "&cYou do not have permission to do that!" +unknown-command: "&cCommand not found! Use &e/redlight help." + +#Plugin-update-messages: +update-available: + 1: "&4*-------------------------------------------*" + 2: "&cA new version is available!" + 3: "&4*-------------------------------------------*" +no-update-available: + 1: "&a*-------------------------------------------*" + 2: "&aPlugin is up to date!" + 3: "&a*-------------------------------------------*" +update-check-failure: "&4Unable to check for updates! - &c" + +#Plugin-help-messages: +help-command: + - "&e[--------------- &b[RedLight-GreenLight] &e----------------]\n" + - "&f/red join &7- &dThis command joins the game.\n" + - "&f/red leave &7- &dThis command leaves the game.\n" + - "&f/red joinall &7- &dThis command adds all players to the game.\n" + - "&f/red leaveall &7- &dThis forces all players to leave the game.\n" + - "&f/red help &7- &dThis command shows this help menu.\n" + - "&f/red reload &7- &dThis command reloads the config.\n" + - "&e[------------------- &bPermissions &e---------------------]\n" + - "&fredlight.*\n" + - "&fredlight.help\n" + - "&fredlight.reload\n" + - "&fredlight.command.joinall\n" + - "&fredlight.command.leaveall\n" + - "&fredlight.bypass.joinwipe\n" + - "&fredlight.bypass.commands\n" + - "&fredlight.bypass.gamemode\n" + - "&e[---------------------------------------------------]\n" + - "&fPlugin Version: &a%version%\n" + - "&e[---------------------------------------------------]" +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 1284312..20471d4 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -5,8 +5,16 @@ api-version: 1.13 folia-supported: true authors: [ Loving11ish ] description: A Red Light, Green Light mini-game based off the Netflix series Squid Games. + commands: redlight: description: The main command. usage: /redlight aliases: [ rd, red ] + +permissions: + redlight.*: + description: Gives access to all RedLight-GreenLight features. + default: op + children: + From 6dfe3eefa2a7b939900391a2adb599a8a3f4a38e Mon Sep 17 00:00:00 2001 From: Loving11ish Date: Tue, 17 Dec 2024 18:21:36 +0000 Subject: [PATCH 2/2] Updated GitHub repository. Added new `messages.yml`. Added MiniMessage support. Massive recode. Added 1.21+ support. Added world-name to location settings. Changed plugin version to `2.6.0`. --- pom.xml | 2 +- .../RedLightGreenLight.java | 12 +++---- .../consolecommands/ConsoleReload.java | 2 ++ .../commands/subcommands/Reload.java | 2 ++ .../filemanagers/MessagesManager.java | 6 ++++ .../tasks/OnlinePlayerTasks.java | 11 ++++-- .../utils/MessageUtils.java | 34 ++++++++++++++++--- .../versionsystems/ServerVersion.java | 1 + src/main/resources/messages.yml | 1 + 9 files changed, 58 insertions(+), 13 deletions(-) diff --git a/pom.xml b/pom.xml index 3f87c59..047835b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.loving11ish RedLightGreenLight - 2.6.0-ALPHA-01 + 2.6.0 jar RedLightGreenLight diff --git a/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java b/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java index 3d52675..2102442 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/RedLightGreenLight.java @@ -52,12 +52,12 @@ public final class RedLightGreenLight extends JavaPlugin { // Commands private CommandManager commandManager; - // Lists - public List onlinePlayers = new ArrayList<>(Bukkit.getServer().getOnlinePlayers()); - // Tasks private WrappedTask onlinePlayerUpdateTasks; + // Lists + public final List onlinePlayers = new ArrayList<>(Bukkit.getServer().getOnlinePlayers()); + @Override public void onLoad() { // Plugin load logic @@ -188,7 +188,7 @@ public void onEnable() { MessageUtils.sendConsole("-------------------------------------------"); // Start online player update task - this.onlinePlayerUpdateTasks = foliaLib.getScheduler().runTimer(new OnlinePlayerTasks(), 5L, 300L, TimeUnit.SECONDS); + this.onlinePlayerUpdateTasks = foliaLib.getScheduler().runTimerAsync(new OnlinePlayerTasks(), 5L, 300L, TimeUnit.SECONDS); // Check for available updates new UpdateChecker(96866).getVersion(version -> { @@ -324,9 +324,9 @@ private void setVersion() { } else if (bukkitVersion.contains("1.21.2")) { serverVersion = ServerVersion.v1_21_R3; } else if (bukkitVersion.contains("1.21.3")) { - serverVersion = ServerVersion.v1_21_R3; - } else if (bukkitVersion.contains("1.21.4")) { serverVersion = ServerVersion.v1_21_R4; + } else if (bukkitVersion.contains("1.21.4")) { + serverVersion = ServerVersion.v1_21_R5; } else { serverVersion = ServerVersion.valueOf(packageName.replace("org.bukkit.craftbukkit.", "")); } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java index 751e3dc..0042e50 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/consolecommands/ConsoleReload.java @@ -27,12 +27,14 @@ public String getSyntax() { @Override public void perform(String[] args) { MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadStart()); + MessageUtils.broadcastMessage(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadBroadcast()); RedLightGreenLight.getPlugin().getCommandManager().reloadPlugin(); FoliaLib foliaLib = RedLightGreenLight.getPlugin().getFoliaLib(); foliaLib.getScheduler().runLater(() -> { MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); + MessageUtils.broadcastMessage(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); }, 8L, TimeUnit.SECONDS); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java index 95493ae..bce092b 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/commands/subcommands/Reload.java @@ -41,6 +41,7 @@ public void perform(Player player, String[] args) { MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadStart()); MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadStart()); + MessageUtils.broadcastMessage(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadBroadcast()); RedLightGreenLight.getPlugin().getCommandManager().reloadPlugin(); @@ -48,6 +49,7 @@ public void perform(Player player, String[] args) { foliaLib.getScheduler().runLater(() -> { MessageUtils.sendPlayer(player, RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); MessageUtils.sendConsole(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); + MessageUtils.broadcastMessage(RedLightGreenLight.getPlugin().getMessagesManager().getPluginReloadComplete()); }, 8L, TimeUnit.SECONDS); } else { diff --git a/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java b/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java index ac5f3f5..e48bc39 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/managers/filemanagers/MessagesManager.java @@ -33,6 +33,7 @@ public class MessagesManager { private String gameLeaveSubtitle; private String pluginReloadStart; private String pluginReloadComplete; + private String pluginReloadBroadcast; private String disabledWorld; private String noPermission; private String unknownCommand; @@ -83,6 +84,7 @@ public void loadMessagesValues() { gameLeaveSubtitle = messages.getString("game-leave-subtitle", "&eThank you for playing!"); pluginReloadStart = messages.getString("plugin-reload-beginning", "&aBeginning plugin reload..."); pluginReloadComplete = messages.getString("plugin-reload-successful", "&aPlugin reload complete!"); + pluginReloadBroadcast = messages.getString("plugin-reload-broadcast", "&aThe plugin is being reloaded!\\n&aPlease wait until the plugin is reloaded before starting a new game."); disabledWorld = messages.getString("disabled-world-message", "&4&lRedLight&r&c-&a&lGreenLight has been disabled in this world."); noPermission = messages.getString("no-permission", "&cYou do not have permission to do that!"); unknownCommand = messages.getString("unknown-command", "&cCommand not found! Use &e/redlight help."); @@ -201,6 +203,10 @@ public String getPluginReloadComplete() { return pluginReloadComplete; } + public String getPluginReloadBroadcast() { + return pluginReloadBroadcast; + } + public String getDisabledWorld() { return disabledWorld; } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java b/src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java index 537dde2..0bfddb8 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/tasks/OnlinePlayerTasks.java @@ -7,7 +7,14 @@ public class OnlinePlayerTasks implements Runnable { @Override public void run() { - RedLightGreenLight.getPlugin().onlinePlayers.clear(); - RedLightGreenLight.getPlugin().onlinePlayers.addAll(Bukkit.getOnlinePlayers()); + synchronized (RedLightGreenLight.getPlugin().onlinePlayers) { + RedLightGreenLight.getPlugin().onlinePlayers.clear(); + } + + RedLightGreenLight.getPlugin().getFoliaLib().getScheduler().runNextTick((task) -> { + synchronized (RedLightGreenLight.getPlugin().onlinePlayers) { + RedLightGreenLight.getPlugin().onlinePlayers.addAll(Bukkit.getOnlinePlayers()); + } + }); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java b/src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java index 07ea603..b31f272 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/utils/MessageUtils.java @@ -54,11 +54,37 @@ public static void sendConsole(String level, String message) { } /** - * @param sender The command sender to send the message too. + * @param message The message to be broadcast with prefix applied. Supports color codes. + */ + public static void broadcastMessage(String message) { + Bukkit.broadcastMessage(ColorUtils.translateColorCodes(prefix + " &l" + message)); + } + + /** + * @param sender The sender to send the message too. * @param message The message to be sent with prefix applied. Supports color codes. */ public static void sendSender(CommandSender sender, String message) { - sender.sendMessage(ColorUtils.translateColorCodes(prefix + " &r" + message)); + if (sender instanceof Player) { + Player player = (Player) sender; + sendPlayer(player, message); + } else { + sendConsole(message); + } + } + + /** + * @param sender The sender to send the message too. + * @param level The log level of the message. Supports: info, warning, error, and severe. + * @param message The message to be sent with prefix applied. Supports color codes. + */ + public static void sendSender(CommandSender sender, String level, String message) { + if (sender instanceof Player) { + Player player = (Player) sender; + sendPlayer(player, message); + } else { + sendConsole(level, message); + } } /** @@ -66,7 +92,7 @@ public static void sendSender(CommandSender sender, String message) { */ public static void sendDebugConsole(String message) { if (debug) { - console.sendMessage(ColorUtils.translateColorCodes("&6UStats-Debug&7: " + message)); + console.sendMessage(ColorUtils.translateColorCodes("&6RL-GL-Debug&7: " + message)); } } @@ -77,7 +103,7 @@ public static void sendDebugConsole(String message) { public static void sendDebugConsole(String level, String message) { if (debug) { level = setDebugLevel(level); - console.sendMessage(ColorUtils.translateColorCodes("&6UStats-Debug&7: [" + level + "&7] - " + levelColor + message)); + console.sendMessage(ColorUtils.translateColorCodes("&6RL-GL-Debug&7: [" + level + "&7] - " + levelColor + message)); } } diff --git a/src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java b/src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java index 627dfd2..aa93887 100644 --- a/src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java +++ b/src/main/java/me/loving11ish/redlightgreenlight/versionsystems/ServerVersion.java @@ -32,6 +32,7 @@ public enum ServerVersion { v1_21_R2, v1_21_R3, v1_21_R4, + v1_21_R5, Other; public boolean serverVersionEqual(ServerVersion version) { diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml index 8e1fa32..760f4f8 100644 --- a/src/main/resources/messages.yml +++ b/src/main/resources/messages.yml @@ -52,6 +52,7 @@ console-syntax-error: plugin-reload-beginning: "&aBeginning plugin reload..." plugin-reload-successful: "&aPlugin reload complete!" +plugin-reload-broadcast: "&aThe plugin is being reloaded!\n&aPlease wait until the plugin is reloaded before starting a new game." disabled-world-message: "&4&lRedLight&r&c-&a&lGreenLight has been disabled in this world." no-permission: "&cYou do not have permission to do that!" unknown-command: "&cCommand not found! Use &e/redlight help."