diff --git a/.checkstyle/checkstyle.xml b/.checkstyle/checkstyle.xml index 775c09f1..5e65df7f 100644 --- a/.checkstyle/checkstyle.xml +++ b/.checkstyle/checkstyle.xml @@ -1,5 +1,23 @@ + + - - org.bstats - bstats-bukkit - 2.2.1 - org.jetbrains annotations - 21.0.1 + 23.0.0 compile @@ -144,48 +91,11 @@ ${project.basedir}/lib/CorpseReborn.jar - com.google.code.findbugs - jsr305 - 3.0.2 - provided - - - - commons-io - commons-io - 2.10.0 + plugily.projects + MiniGamesBox-Classic + 1.3.1 compile - - - de.simonsator - partyandfriends - 1.0.52 - system - ${project.basedir}/lib/PAFSpigot.jar - - - de.simonsator - Party-and-Friends-MySQL-Edition-Spigot-API - 1.3.2 - provided - - - be.maximvdw - MVdWPlaceholderAPI - - - - - de.simonsator - Spigot-Party-API-For-RedisBungee - 1.0-SNAPSHOT - provided - - - redis.clients - jedis - - + true @@ -199,12 +109,12 @@ org.apache.maven.plugins maven-site-plugin - 3.9.1 + 3.12.0 org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.10.1 compile @@ -216,7 +126,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.3.0 + 3.4.0 Murder Mystery API docs for v${project.version} Minecraft survival minigame. @@ -230,12 +140,12 @@ org.apache.maven.plugins maven-jar-plugin - 3.2.0 + 3.2.2 org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.3.0 package @@ -244,27 +154,18 @@ - - plugily.projects.inventoryframework - plugily.projects.murdermystery.utils.inventoryframework - - com.zaxxer.hikari plugily.projects.murdermystery.database.hikari - me.tigerhix.lib.scoreboard - plugily.projects.murdermystery.utils.scoreboard + plugily.projects.minigamesbox + plugily.projects.murdermystery.minigamesbox plugily.projects.commonsbox plugily.projects.murdermystery.commonsbox - - org.bstats - plugily.projects.murdermystery.utils.bstats - false @@ -286,22 +187,16 @@ org.apache.maven.wagon - wagon-ftp - 3.4.3 + wagon-ssh + 3.5.2 - - plugily-projects-repo - ftp://81.19.211.8 + plugily-projects + https://maven.plugily.xyz/releases - - plugily-projects-java-docs - murdermystery - ftp://81.19.211.8 - diff --git a/.github/workflows/deploy-development.yml b/.github/workflows/deploy-development.yml new file mode 100644 index 00000000..92f16b11 --- /dev/null +++ b/.github/workflows/deploy-development.yml @@ -0,0 +1,43 @@ +name: Bump and Publish Development Branch + +on: + push: + branches: [ development ] + workflow_dispatch: +jobs: + bump: + runs-on: ubuntu-latest + steps: + - name: Checkout Latest Commit + uses: actions/checkout@v3 + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Bump Version + id: bump + uses: Plugily-Projects/version-bump-action@v8 + with: + github-token: ${{ secrets.github_token }} + auto-version-bump: true + - name: Print Version + run: "echo 'New Version: ${{steps.bump.outputs.version}}'" + publish: + needs: bump + runs-on: ubuntu-latest + steps: + - name: Checkout Latest Commit + uses: actions/checkout@v3 + with: + ref: 'development' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + java-package: jdk + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Publish with Gradle + run: ./gradlew publishMavenPublicationToSnapshotsRepository + env: + MAVEN_USERNAME: ${{ secrets.SNAPSHOTSUSERNAME }} + MAVEN_PASSWORD: ${{ secrets.SNAPSHOTSPASSWORD }} \ No newline at end of file diff --git a/.github/workflows/deploy-master.yml b/.github/workflows/deploy-master.yml new file mode 100644 index 00000000..143add43 --- /dev/null +++ b/.github/workflows/deploy-master.yml @@ -0,0 +1,46 @@ +name: Bump and Publish Master Branch + +on: + pull_request: + types: + - closed + workflow_dispatch: +jobs: + bump: + if: github.event.pull_request.merged + runs-on: ubuntu-latest + steps: + - name: Checkout Latest Commit + uses: actions/checkout@v3 + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Bump Version + id: bump + uses: Plugily-Projects/version-bump-action@v8 + with: + github-token: ${{ secrets.github_token }} + auto-version-bump: false + auto-version-bump-release: true + - name: Print Version + run: "echo 'New Version: ${{steps.bump.outputs.version}}'" + publish: + needs: bump + runs-on: ubuntu-latest + steps: + - name: Checkout Latest Commit + uses: actions/checkout@v3 + with: + ref: 'master' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + java-package: jdk + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Publish with Gradle + run: ./gradlew publishMavenPublicationToReleasesRepository + env: + MAVEN_USERNAME: ${{ secrets.RELEASESUSERNAME }} + MAVEN_PASSWORD: ${{ secrets.RELEASESPASSWORD }} \ No newline at end of file diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml deleted file mode 100644 index 8c8d64bf..00000000 --- a/.github/workflows/deploy.yml +++ /dev/null @@ -1,65 +0,0 @@ -# This is a basic workflow to help you get started with Actions - -name: deploy - -# Controls when the action will run. -on: - # Triggers the workflow on push or pull request events but only for the main branch - push: - branches: [ development ] -# pull_request: -# branches: [ main ] - - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - # This workflow contains a single job called "build" - deploy: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - uses: actions/checkout@v2 - - - name: Bump Version - id: bump - uses: Plugily-Projects/maven-version-bump-action@dev - with: - github-token: ${{ secrets.github_token }} - - - uses: actions/cache@v2 - with: - path: ~/.m2/repository - key: maven-${{ hashFiles('**/pom.xml') }} - restore-keys: maven- - - - name: Set up Maven - uses: stCarolas/setup-maven@v4 - with: - maven-version: 3.6.3 - - - name: Set up JDK 16 - uses: actions/setup-java@v1 - with: - java-version: 16 - - - name: maven-settings-action - uses: s4u/maven-settings-action@v2.4.0 - with: - servers: | - [{ - "id": "${{ secrets.PLUGILY_MAVEN }}", - "username": "${{ secrets.PLUGILY_MAVEN_USERNAME }}", - "password": "${{ secrets.PLUGILY_MAVEN_PASSWORD }}" - }, - { - "id": "${{ secrets.PLUGILY_JD }}", - "username": "${{ secrets.PLUGILY_JD_USERNAME }}", - "password": "${{ secrets.PLUGILY_JD_PASSWORD }}" - }] - - - run: mvn clean verify compile package site:site site:deploy deploy -f pom.xml diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml deleted file mode 100644 index 773a9d4b..00000000 --- a/.github/workflows/sonarcloud.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: sonarcloud -on: - push: - branches: - - development - - dev - - main - - master - pull_request: - types: [opened, synchronize, reopened] -jobs: - sonarcloud: - name: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - - name: Set up JDK 16 - uses: actions/setup-java@v1 - with: - java-version: 16 - - - name: Set up Maven - uses: stCarolas/setup-maven@v4 - with: - maven-version: 3.6.3 - - - name: Cache SonarCloud packages - uses: actions/cache@v1 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - - name: Cache Maven packages - uses: actions/cache@v1 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar diff --git a/.gitignore b/.gitignore index 479123d5..85908858 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ /out/ /generated/ -.* /minecraft/ /target/ \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..fe66e335 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,83 @@ +plugins { + id("signing") + `maven-publish` + id("com.github.johnrengelman.shadow") version "8.1.1" + java +} + +repositories { + mavenLocal() + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://oss.sonatype.org/content/repositories/snapshots") + maven("https://oss.sonatype.org/content/repositories/central") + maven(uri("https://papermc.io/repo/repository/maven-public/")) + maven(uri("https://maven.plugily.xyz/releases")) + maven(uri("https://maven.plugily.xyz/snapshots")) + maven(uri("https://repo.maven.apache.org/maven2/")) +} + +dependencies { + implementation("plugily.projects:MiniGamesBox-Classic:1.3.1") { isTransitive = false } + compileOnly("org.spigotmc:spigot-api:1.19.3-R0.1-SNAPSHOT") + compileOnly("io.papermc.paper:paper-api:1.19.3-R0.1-SNAPSHOT") + compileOnly("org.jetbrains:annotations:24.0.1") + compileOnly(files("lib/CorpseReborn.jar")) +} + +group = "plugily.projects" +version = "1.7.9-SNAPSHOT48" +description = "MurderMystery" + +java { + withJavadocJar() +} + +tasks { + build { + dependsOn(shadowJar) + } + + shadowJar { + archiveClassifier.set("") + relocate("plugily.projects.minigamesbox", "plugily.projects.murdermystery.minigamesbox") + relocate("com.zaxxer.hikari", "plugily.projects.murdermystery.database.hikari") + minimize() + } + + processResources { + filesMatching("**/plugin.yml") { + expand(project.properties) + } + } + + javadoc { + options.encoding = "UTF-8" + } + +} + +publishing { + repositories { + maven { + name = "Releases" + url = uri("https://maven.plugily.xyz/releases") + credentials { + username = System.getenv("MAVEN_USERNAME") + password = System.getenv("MAVEN_PASSWORD") + } + } + maven { + name = "Snapshots" + url = uri("https://maven.plugily.xyz/snapshots") + credentials { + username = System.getenv("MAVEN_USERNAME") + password = System.getenv("MAVEN_PASSWORD") + } + } + } + publications { + create("mavenJava") { + from(components["java"]) + } + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..c1962a79 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..37aef8d3 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..aeb74cbb --- /dev/null +++ b/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/PAFSpigot.jar b/lib/PAFSpigot.jar deleted file mode 100644 index 38f5c113..00000000 Binary files a/lib/PAFSpigot.jar and /dev/null differ diff --git a/lib/README.md b/lib/README.md index 1c6b674d..b51b0ac7 100644 --- a/lib/README.md +++ b/lib/README.md @@ -1,10 +1,5 @@ _This lib folder contains external libs that are not provided by their author with Maven._ -**(The following libraries located in this folder have been approved by their author!)** - -PAFSpigot (Simonsator#5834 | https://www.spigotmc.org/resources/authors/simonsator.67188/ ) - - **(The following libraries located in this folder have been released in compliance with the license therein)** CorpseReborn (License: No License | https://www.spigotmc.org/resources/authors/ericgolde555.23398/ | https://github.com/egold555/CorpseReborn ) diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..5b416215 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "murdermystery" diff --git a/src/main/java/plugily/projects/murdermystery/ConfigPreferences.java b/src/main/java/plugily/projects/murdermystery/ConfigPreferences.java deleted file mode 100644 index 95cab014..00000000 --- a/src/main/java/plugily/projects/murdermystery/ConfigPreferences.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery; - -import org.bukkit.inventory.ItemStack; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.murdermystery.utils.Debugger; -import plugily.projects.murdermystery.utils.MessageUtils; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Plajer - *

- * Created at 22.12.2018 - */ -public class ConfigPreferences { - - private final Main plugin; - private ItemStack murdererSword; - private final Map options = new HashMap<>(); - - public ConfigPreferences(Main plugin) { - this.plugin = plugin; - loadOptions(); - loadMurdererSword(); - } - - private void loadMurdererSword() { - try { - murdererSword = XMaterial.matchXMaterial(plugin.getConfig().getString("Murderer-Sword-Material", "IRON_SWORD").toUpperCase()).get().parseItem(); - } catch(Exception ex) { - MessageUtils.errorOccurred(); - Debugger.sendConsoleMsg("Can not found Material " + plugin.getConfig().getString("Murderer-Sword-Material")); - //Set the murdererSword to avoid errors - murdererSword = XMaterial.IRON_SWORD.parseItem(); - } - } - - /** - * Returns whether option value is true or false - * - * @param option option to get value from - * @return true or false based on user configuration - */ - public boolean getOption(Option option) { - return options.get(option); - } - - private void loadOptions() { - for(Option option : Option.values()) { - options.put(option, plugin.getConfig().getBoolean(option.getPath(), option.getDefault())); - } - } - - public ItemStack getMurdererSword() { - return murdererSword; - } - - public enum Option { - BOSSBAR_ENABLED("Bossbar-Enabled", true), BUNGEE_ENABLED("BungeeActivated", false), CHAT_FORMAT_ENABLED("ChatFormat-Enabled", true), - DATABASE_ENABLED("DatabaseActivated", false), INVENTORY_MANAGER_ENABLED("InventoryManager", true), NAMETAGS_HIDDEN("Nametags-Hidden", true), - DISABLE_FALL_DAMAGE("Disable-Fall-Damage", false), ENABLE_SHORT_COMMANDS("Enable-Short-Commands", false), ENABLE_KILL_DETECTIVE_IF_INNOCENT_KILLED("Enable-Kill-Detective-If-Innocent-Killed", true), - MURDERER_SPEED_ENABLED("Speed-Effect-Murderer.Enabled", true), SPAWN_GOLD_EVERY_SPAWNER_MODE("Change-Gold-Spawner-Mode-To-All", false), DISABLE_GOLD_LIMITER("Disable-Gold-Limiter", false), - DISABLE_SEPARATE_CHAT("Disable-Separate-Chat", false), DISABLE_PARTIES("Disable-Parties", true), INNOCENT_LOCATOR("Enable-Innocent-Locator", true), - DISABLE_DEATH_MESSAGE("Hide-Death", false); - - private final String path; - private final boolean def; - - Option(String path, boolean def) { - this.path = path; - this.def = def; - } - - public String getPath() { - return path; - } - - /** - * @return default value of option if absent in config - */ - public boolean getDefault() { - return def; - } - } -} diff --git a/src/main/java/plugily/projects/murdermystery/HookManager.java b/src/main/java/plugily/projects/murdermystery/HookManager.java index 879a951c..d2d1cb98 100644 --- a/src/main/java/plugily/projects/murdermystery/HookManager.java +++ b/src/main/java/plugily/projects/murdermystery/HookManager.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,7 +19,8 @@ package plugily.projects.murdermystery; import org.bukkit.Bukkit; -import plugily.projects.murdermystery.utils.Debugger; +import org.bukkit.plugin.java.JavaPlugin; +import plugily.projects.murdermystery.Main; import java.util.EnumMap; import java.util.Map; @@ -30,10 +31,12 @@ * Created at 28.04.2019 */ public class HookManager { - + //todo implement in minigamescore as bb citiziens could benefit from too private final Map hooks = new EnumMap<>(HookFeature.class); + private final Main plugin; - public HookManager() { + public HookManager(Main plugin) { + this.plugin = plugin; enableHooks(); } @@ -41,28 +44,26 @@ private void enableHooks() { for(HookFeature feature : HookFeature.values()) { boolean hooked = true; for(Hook requiredHook : feature.getRequiredHooks()) { - if(!Bukkit.getPluginManager().isPluginEnabled(requiredHook.pluginName)) { + if(!Bukkit.getPluginManager().isPluginEnabled(requiredHook.getPluginName())) { hooks.put(feature, false); - Debugger.debug("[HookManager] Feature {0} won't be enabled because {1} is not installed! Please install it in order to enable this feature in-game!", - feature.name(), requiredHook.pluginName); + plugin.getDebugger().debug("[HookManager] Feature {0} won't be enabled because " + requiredHook.getPluginName() + " is not installed! Please install it in order to enable this feature in-game!", + feature.name()); hooked = false; break; } } if(hooked) { hooks.put(feature, true); - Debugger.debug("[HookManager] Feature {0} enabled!", feature.name()); + plugin.getDebugger().debug("[HookManager] Feature {0} enabled!", feature.name()); } } } public boolean isFeatureEnabled(HookFeature feature) { - Boolean b = hooks.get(feature); - return b != null && b; + return hooks.getOrDefault(feature, false); } public enum HookFeature { - //todo hidden name tags hook CORPSES(Hook.CORPSE_REBORN); private final Hook[] requiredHooks; diff --git a/src/main/java/plugily/projects/murdermystery/Main.java b/src/main/java/plugily/projects/murdermystery/Main.java index ab2faad1..da9345cf 100644 --- a/src/main/java/plugily/projects/murdermystery/Main.java +++ b/src/main/java/plugily/projects/murdermystery/Main.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,330 +18,137 @@ package plugily.projects.murdermystery; -import me.tigerhix.lib.scoreboard.ScoreboardLib; -import org.bstats.bukkit.Metrics; -import org.bukkit.GameMode; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import plugily.projects.commonsbox.database.MysqlDatabase; -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.compat.events.EventsInitializer; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.hologram.HologramManager; -import plugily.projects.commonsbox.minecraft.misc.MiscUtils; -import plugily.projects.commonsbox.minecraft.serialization.InventorySerializer; -import plugily.projects.murdermystery.api.StatsStorage; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.java.JavaPluginLoader; +import org.jetbrains.annotations.TestOnly; +import plugily.projects.minigamesbox.classic.PluginMain; +import plugily.projects.minigamesbox.classic.handlers.setup.SetupInventory; +import plugily.projects.minigamesbox.classic.handlers.setup.categories.PluginSetupCategoryManager; +import plugily.projects.minigamesbox.classic.utils.services.metrics.Metrics; import plugily.projects.murdermystery.arena.Arena; import plugily.projects.murdermystery.arena.ArenaEvents; +import plugily.projects.murdermystery.arena.ArenaManager; import plugily.projects.murdermystery.arena.ArenaRegistry; import plugily.projects.murdermystery.arena.ArenaUtils; import plugily.projects.murdermystery.arena.special.SpecialBlockEvents; import plugily.projects.murdermystery.arena.special.mysterypotion.MysteryPotionRegistry; import plugily.projects.murdermystery.arena.special.pray.PrayerRegistry; +import plugily.projects.murdermystery.boot.AdditionalValueInitializer; +import plugily.projects.murdermystery.boot.MessageInitializer; +import plugily.projects.murdermystery.boot.PlaceholderInitializer; import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.events.ChatEvents; -import plugily.projects.murdermystery.events.Events; -import plugily.projects.murdermystery.events.JoinEvent; -import plugily.projects.murdermystery.events.LobbyEvent; -import plugily.projects.murdermystery.events.QuitEvent; -import plugily.projects.murdermystery.events.spectator.SpectatorEvents; -import plugily.projects.murdermystery.events.spectator.SpectatorItemEvents; -import plugily.projects.murdermystery.handlers.BungeeManager; -import plugily.projects.murdermystery.handlers.ChatManager; +import plugily.projects.murdermystery.events.PluginEvents; import plugily.projects.murdermystery.handlers.CorpseHandler; -import plugily.projects.murdermystery.handlers.PermissionsManager; -import plugily.projects.murdermystery.handlers.PlaceholderManager; -import plugily.projects.murdermystery.handlers.items.SpecialItemManager; -import plugily.projects.murdermystery.handlers.language.LanguageManager; import plugily.projects.murdermystery.handlers.lastwords.LastWordsManager; -import plugily.projects.murdermystery.handlers.party.PartyHandler; -import plugily.projects.murdermystery.handlers.party.PartySupportInitializer; -import plugily.projects.murdermystery.handlers.rewards.RewardsFactory; -import plugily.projects.murdermystery.handlers.sign.SignManager; +import plugily.projects.murdermystery.handlers.setup.SetupCategoryManager; +import plugily.projects.murdermystery.handlers.skins.sword.SwordSkinManager; import plugily.projects.murdermystery.handlers.trails.BowTrailsHandler; import plugily.projects.murdermystery.handlers.trails.TrailsManager; -import plugily.projects.murdermystery.user.User; -import plugily.projects.murdermystery.user.UserManager; -import plugily.projects.murdermystery.user.data.MysqlManager; -import plugily.projects.murdermystery.utils.Debugger; -import plugily.projects.murdermystery.utils.ExceptionLogHandler; -import plugily.projects.murdermystery.utils.MessageUtils; -import plugily.projects.murdermystery.utils.UpdateChecker; -import plugily.projects.murdermystery.utils.Utils; -import plugily.projects.murdermystery.utils.services.ServiceRegistry; import java.io.File; -import java.util.Arrays; -import java.util.logging.Level; /** - * @author Plajer - *

- * Created at 03.08.2018 + * Created by Tigerpanzer_02 on 13.03.2022 */ -public class Main extends JavaPlugin { - - private ExceptionLogHandler exceptionLogHandler; - private boolean forceDisable = false; - private BungeeManager bungeeManager; - private RewardsFactory rewardsHandler; - private MysqlDatabase database; - private SignManager signManager; - private CorpseHandler corpseHandler; - private PartyHandler partyHandler; - private ConfigPreferences configPreferences; +public class Main extends PluginMain { + private ArenaRegistry arenaRegistry; + private ArenaManager arenaManager; private ArgumentsRegistry argumentsRegistry; - private HookManager hookManager; - private UserManager userManager; - private ChatManager chatManager; private LastWordsManager lastWordsManager; private TrailsManager trailsManager; - private SpecialItemManager specialItemManager; - - @Override - public void onEnable() { - if(!validateIfPluginShouldStart()) { - return; - } - - long start = System.currentTimeMillis(); - - ServiceRegistry.registerService(this); - exceptionLogHandler = new ExceptionLogHandler(this); - LanguageManager.init(this); - saveDefaultConfig(); - - Debugger.setEnabled(getDescription().getVersion().contains("debug") || getConfig().getBoolean("Debug")); - - Debugger.debug("[System] Initialization start"); - if(getConfig().getBoolean("Developer-Mode")) { - Debugger.deepDebug(true); - Debugger.debug(Level.FINE, "Deep debug enabled"); - for(String listenable : getConfig().getStringList("Performance-Listenable")) { - Debugger.monitorPerformance(listenable); - } - } - - configPreferences = new ConfigPreferences(this); - setupFiles(); - initializeClasses(); - checkUpdate(); - Debugger.debug("[System] Initialization finished took {0}ms", System.currentTimeMillis() - start); - - Debugger.debug("Plugin loaded!"); + private SwordSkinManager swordSkinManager; + private HookManager hookManager; + private CorpseHandler corpseHandler; - if(configPreferences.getOption(ConfigPreferences.Option.NAMETAGS_HIDDEN)) { - getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> - getServer().getOnlinePlayers().forEach(ArenaUtils::updateNameTagsVisibility), 60, 140); - } + @TestOnly + public Main() { + super(); } - private boolean validateIfPluginShouldStart() { - if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_8_R1)) { - MessageUtils.thisVersionIsNotSupported(); - Debugger.sendConsoleMsg("&cYour server version is not supported by Murder Mystery!"); - Debugger.sendConsoleMsg("&cSadly, we must shut off. Maybe you consider changing your server version?"); - forceDisable = true; - getServer().getPluginManager().disablePlugin(this); - return false; - } - try { - Class.forName("org.spigotmc.SpigotConfig"); - } catch(Exception e) { - MessageUtils.thisVersionIsNotSupported(); - Debugger.sendConsoleMsg("&cYour server software is not supported by Murder Mystery!"); - Debugger.sendConsoleMsg("&cWe support only Spigot and Spigot forks only! Shutting off..."); - forceDisable = true; - getServer().getPluginManager().disablePlugin(this); - return false; - } - return true; + @TestOnly + protected Main( + JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { + super(loader, description, dataFolder, file); } @Override - public void onDisable() { - if(forceDisable) { - return; - } - Debugger.debug("System disable initialized"); + public void onEnable() { long start = System.currentTimeMillis(); - - getLogger().removeHandler(exceptionLogHandler); - saveAllUserStatistics(); - if(configPreferences.getOption(ConfigPreferences.Option.DATABASE_ENABLED)) { - getMysqlDatabase().shutdownConnPool(); - } - for(ArmorStand armorStand : HologramManager.getArmorStands()) { - armorStand.remove(); - armorStand.setCustomNameVisible(false); - } - HologramManager.getArmorStands().clear(); - for(Arena arena : ArenaRegistry.getArenas()) { - arena.getScoreboardManager().stopAllScoreboards(); - for(Player player : arena.getPlayers()) { - arena.doBarAction(Arena.BarAction.REMOVE, player); - arena.teleportToEndLocation(player); - player.setFlySpeed(0.1f); - player.getInventory().clear(); - player.getInventory().setArmorContents(null); - player.getActivePotionEffects().forEach(pe -> player.removePotionEffect(pe.getType())); - player.setWalkSpeed(0.2f); - player.setGameMode(GameMode.SURVIVAL); - if(configPreferences.getOption(ConfigPreferences.Option.INVENTORY_MANAGER_ENABLED)) { - InventorySerializer.loadInventory(this, player); - } - } - arena.cleanUpArena(); + MessageInitializer messageInitializer = new MessageInitializer(this); + super.onEnable(); + getDebugger().debug("[System] [Plugin] Initialization start"); + arenaRegistry = new ArenaRegistry(this); + new PlaceholderInitializer(this); + messageInitializer.registerMessages(); + new AdditionalValueInitializer(this); + initializePluginClasses(); + + if(getConfigPreferences().getOption("HIDE_NAMETAGS")) { + getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> + getServer().getOnlinePlayers().forEach(ArenaUtils::updateNameTagsVisibility), 60, 140); } - Debugger.debug("System disable finished took {0}ms", System.currentTimeMillis() - start); - } - private void initializeClasses() { - chatManager = new ChatManager(this); - ScoreboardLib.setPluginInstance(this); - if(getConfig().getBoolean("BungeeActivated")) { - bungeeManager = new BungeeManager(this); - } - if(configPreferences.getOption(ConfigPreferences.Option.DATABASE_ENABLED)) { - FileConfiguration config = ConfigUtils.getConfig(this, "mysql"); - database = new MysqlDatabase(config.getString("user"), config.getString("password"), config.getString("address"), config.getLong("maxLifeTime", 1800000)); - } - argumentsRegistry = new ArgumentsRegistry(this); - userManager = new UserManager(this); - hookManager = new HookManager(); - Utils.init(this); - PermissionsManager.init(); + getDebugger().debug("Full {0} plugin enabled", getName()); + getDebugger() + .debug( + "[System] [Plugin] Initialization finished took {0}ms", + System.currentTimeMillis() - start); + } + + public void initializePluginClasses() { + addFileName("lastwords"); + addFileName("powerups"); + addFileName("skins"); + addFileName("special_blocks"); + addFileName("trails"); + Arena.init(this); + ArenaUtils.init(this); new ArenaEvents(this); - new SpectatorEvents(this); - new QuitEvent(this); - new JoinEvent(this); - new ChatEvents(this); - registerSoftDependenciesAndServices(); - User.cooldownHandlerTask(); - signManager = new SignManager(this); - ArenaRegistry.registerArenas(); - signManager.loadSigns(); - signManager.updateSigns(); - new Events(this); - new LobbyEvent(this); - new SpectatorItemEvents(this); - rewardsHandler = new RewardsFactory(this); - specialItemManager = new SpecialItemManager(this); - corpseHandler = new CorpseHandler(this); - partyHandler = new PartySupportInitializer().initialize(this); + arenaManager = new ArenaManager(this); + arenaRegistry.registerArenas(); + getSignManager().loadSigns(); + getSignManager().updateSigns(); + argumentsRegistry = new ArgumentsRegistry(this); + + lastWordsManager = new LastWordsManager(this); new BowTrailsHandler(this); MysteryPotionRegistry.init(this); PrayerRegistry.init(this); new SpecialBlockEvents(this); - new EventsInitializer().initialize(this); - lastWordsManager = new LastWordsManager(this); trailsManager = new TrailsManager(this); - MiscUtils.sendStartUpMessage(this, "MurderMystery", getDescription(), true, true); - } - - private void registerSoftDependenciesAndServices() { - Debugger.debug("Hooking into soft dependencies"); - long start = System.currentTimeMillis(); - - startPluginMetrics(); - if(getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) { - Debugger.debug("Hooking into PlaceholderAPI"); - new PlaceholderManager().register(); - } - Debugger.debug("Hooked into soft dependencies took {0}ms", System.currentTimeMillis() - start); - } - - private void startPluginMetrics() { - Metrics metrics = new Metrics(this, 3038); - - metrics.addCustomChart(new org.bstats.charts.SimplePie("database_enabled", () -> String.valueOf(configPreferences.getOption(ConfigPreferences.Option.DATABASE_ENABLED)))); - metrics.addCustomChart(new org.bstats.charts.SimplePie("bungeecord_hooked", () -> String.valueOf(configPreferences.getOption(ConfigPreferences.Option.BUNGEE_ENABLED)))); - metrics.addCustomChart(new org.bstats.charts.SimplePie("locale_used", () -> LanguageManager.getPluginLocale().getPrefix())); - metrics.addCustomChart(new org.bstats.charts.SimplePie("update_notifier", () -> { - if(getConfig().getBoolean("Update-Notifier.Enabled", true)) { - return getConfig().getBoolean("Update-Notifier.Notify-Beta-Versions", true) ? "Enabled with beta notifier" : "Enabled"; - } - return getConfig().getBoolean("Update-Notifier.Notify-Beta-Versions", true) ? "Beta notifier only" : "Disabled"; - })); - } - - private void checkUpdate() { - if(!getConfig().getBoolean("Update-Notifier.Enabled", true)) { - return; - } - UpdateChecker.init(this, 66614).requestUpdateCheck().whenComplete((result, exception) -> { - if(!result.requiresUpdate()) { - return; - } - if(result.getNewestVersion().contains("b")) { - if(getConfig().getBoolean("Update-Notifier.Notify-Beta-Versions", true)) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Your software is ready for update! However it's a BETA VERSION. Proceed with caution."); - Debugger.sendConsoleMsg("&c[Murder Mystery] Current version %old%, latest version %new%".replace("%old%", getDescription().getVersion()).replace("%new%", - result.getNewestVersion())); - } - return; - } - MessageUtils.updateIsHere(); - Debugger.sendConsoleMsg("&aYour MurderMystery plugin is outdated! Download it to keep with latest changes and fixes."); - Debugger.sendConsoleMsg("&aDisable this option in config.yml if you wish."); - Debugger.sendConsoleMsg("&eCurrent version: &c" + getDescription().getVersion() + "&e Latest version: &a" + result.getNewestVersion()); - }); - } - - private void setupFiles() { - for(String fileName : Arrays.asList("arenas", "bungee", "rewards", "stats", "special_items", "mysql", "specialblocks")) { - File file = new File(getDataFolder() + File.separator + fileName + ".yml"); - if(!file.exists()) { - saveResource(fileName + ".yml", false); - } - } - } - - public RewardsFactory getRewardsHandler() { - return rewardsHandler; - } - - public BungeeManager getBungeeManager() { - return bungeeManager; - } - - public PartyHandler getPartyHandler() { - return partyHandler; - } - - public ChatManager getChatManager() { - return chatManager; - } - - public ConfigPreferences getConfigPreferences() { - return configPreferences; - } - - public MysqlDatabase getMysqlDatabase() { - return database; + hookManager = new HookManager(this); + corpseHandler = new CorpseHandler(this); + swordSkinManager = new SwordSkinManager(this); + new PluginEvents(this); + addPluginMetrics(); } - public SignManager getSignManager() { - return signManager; + private void addPluginMetrics() { + getMetrics() + .addCustomChart( + new Metrics.SimplePie( + "hooked_addons", + () -> { + if(getServer().getPluginManager().getPlugin("MurderMystery-Extension") != null) { + return "Extension"; + } + return "None"; + })); } - public CorpseHandler getCorpseHandler() { - return corpseHandler; + @Override + public ArenaRegistry getArenaRegistry() { + return arenaRegistry; } + @Override public ArgumentsRegistry getArgumentsRegistry() { return argumentsRegistry; } - public HookManager getHookManager() { - return hookManager; - } - - public UserManager getUserManager() { - return userManager; + @Override + public ArenaManager getArenaManager() { + return arenaManager; } public LastWordsManager getLastWordsManager() { @@ -352,33 +159,20 @@ public TrailsManager getTrailsManager() { return trailsManager; } - public SpecialItemManager getSpecialItemManager() { - return specialItemManager; + public SwordSkinManager getSwordSkinManager() { + return swordSkinManager; } - private void saveAllUserStatistics() { - for(Player player : getServer().getOnlinePlayers()) { - User user = userManager.getUser(player); - if(userManager.getDatabase() instanceof MysqlManager) { - StringBuilder update = new StringBuilder(" SET "); - for(StatsStorage.StatisticType stat : StatsStorage.StatisticType.values()) { - if(!stat.isPersistent()) continue; - if(update.toString().equalsIgnoreCase(" SET ")) { - update.append(stat.getName()).append('=').append(user.getStat(stat)); - } - update.append(", ").append(stat.getName()).append('=').append(user.getStat(stat)); - } - String finalUpdate = update.toString(); - //copy of userManager#saveStatistic but without async database call that's not allowed in onDisable method. - ((MysqlManager) userManager.getDatabase()).getDatabase().executeUpdate("UPDATE " + ((MysqlManager) getUserManager().getDatabase()).getTableName() - + finalUpdate + " WHERE UUID='" + user.getUniqueId().toString() + "';"); - continue; - } - for(StatsStorage.StatisticType stat : StatsStorage.StatisticType.values()) { - userManager.getDatabase().saveStatistic(user, stat); - } - } + public HookManager getHookManager() { + return hookManager; } + public CorpseHandler getCorpseHandler() { + return corpseHandler; + } + @Override + public PluginSetupCategoryManager getSetupCategoryManager(SetupInventory setupInventory) { + return new SetupCategoryManager(setupInventory); + } } diff --git a/src/main/java/plugily/projects/murdermystery/api/StatsStorage.java b/src/main/java/plugily/projects/murdermystery/api/StatsStorage.java deleted file mode 100644 index 3f677630..00000000 --- a/src/main/java/plugily/projects/murdermystery/api/StatsStorage.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.api; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; - -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.sorter.SortUtils; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.user.data.MysqlManager; -import plugily.projects.murdermystery.utils.MessageUtils; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.TreeMap; -import java.util.UUID; -import java.util.logging.Level; - -/** - * @author Plajer - * @since 0.0.1-alpha - *

- * Class for accessing users statistics. - */ -public class StatsStorage { - - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - - /** - * Get all UUID's sorted ascending by Statistic Type - * - * @param stat Statistic type to get (kills, deaths etc.) - * @return Map of UUID keys and Integer values sorted in ascending order of requested statistic type - */ - @NotNull - @Contract("null -> fail") - public static Map getStats(StatisticType stat) { - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DATABASE_ENABLED)) { - try(Connection connection = plugin.getMysqlDatabase().getConnection()) { - Statement statement = connection.createStatement(); - ResultSet set = statement.executeQuery("SELECT UUID, " + stat.getName() + " FROM " + ((MysqlManager) plugin.getUserManager().getDatabase()).getTableName() + " ORDER BY " + stat.getName()); - Map column = new LinkedHashMap<>(); - while(set.next()) { - column.put(UUID.fromString(set.getString("UUID")), set.getInt(stat.getName())); - } - return column; - } catch(SQLException e) { - plugin.getLogger().log(Level.WARNING, "SQLException occurred! " + e.getSQLState() + " (" + e.getErrorCode() + ")"); - MessageUtils.errorOccurred(); - Bukkit.getConsoleSender().sendMessage("Cannot get contents from MySQL database!"); - Bukkit.getConsoleSender().sendMessage("Check configuration of mysql.yml file or disable mysql option in config.yml"); - return Collections.emptyMap(); - } - } - FileConfiguration config = ConfigUtils.getConfig(plugin, "stats"); - Map stats = new TreeMap<>(); - for(String string : config.getKeys(false)) { - if(string.equals("data-version")) { - continue; - } - stats.put(UUID.fromString(string), config.getInt(string + "." + stat.getName())); - } - return SortUtils.sortByValue(stats); - } - - /** - * Get user statistic based on StatisticType - * - * @param player Online player to get data from - * @param statisticType Statistic type to get (kills, deaths etc.) - * @return int of statistic - * @see StatisticType - */ - public static int getUserStats(Player player, StatisticType statisticType) { - return plugin.getUserManager().getUser(player).getStat(statisticType); - } - - /** - * Set user statistic based on StatisticType - * - * @param player Online player to get data from - * @param statisticType Statistic type to get (kills, deaths etc.) - * @param value int of statistic - * @see StatisticType - */ - public static void setUserStat(Player player, StatisticType statisticType, int value) { - plugin.getUserManager().getUser(player).setStat(statisticType, value); - } - - /** - * Available statistics to get. - */ - public enum StatisticType { - CONTRIBUTION_DETECTIVE("contribdetective", true), - CONTRIBUTION_MURDERER("contribmurderer", true), DEATHS("deaths", true), GAMES_PLAYED("gamesplayed", true), HIGHEST_SCORE("highestscore", true), - KILLS("kills", true), LOSES("loses", true), WINS("wins", true), LOCAL_CURRENT_PRAY("local_pray", false), LOCAL_GOLD("gold", false), LOCAL_KILLS("local_kills", false), - LOCAL_PRAISES("local_praises", false), LOCAL_SCORE("local_score", false), MURDERER_PASS("murderer_pass", true), DETECTIVE_PASS("murderer_pass", true); - - private final String name; - private final boolean persistent; - - StatisticType(String name, boolean persistent) { - this.name = name; - this.persistent = persistent; - } - - public String getName() { - return name; - } - - public boolean isPersistent() { - return persistent; - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/api/events/MurderMysteryEvent.java b/src/main/java/plugily/projects/murdermystery/api/events/MurderMysteryEvent.java deleted file mode 100644 index f81c32f0..00000000 --- a/src/main/java/plugily/projects/murdermystery/api/events/MurderMysteryEvent.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.api.events; - -import org.bukkit.event.Event; -import plugily.projects.murdermystery.arena.Arena; - -/** - * Represents Murder Mystery game related events. - */ -public abstract class MurderMysteryEvent extends Event { - - protected Arena arena; - - public MurderMysteryEvent(Arena eventArena) { - arena = eventArena; - } - - /** - * Returns event arena - * - * @return event arena - */ - public Arena getArena() { - return arena; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameLeaveAttemptEvent.java b/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameLeaveAttemptEvent.java deleted file mode 100644 index 27ad8dab..00000000 --- a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameLeaveAttemptEvent.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.api.events.game; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import plugily.projects.murdermystery.api.events.MurderMysteryEvent; -import plugily.projects.murdermystery.arena.Arena; - -/** - * @author Plajer - * @since 0.0.3b - *

- * Called when player is attempting to leave arena. - */ -public class MMGameLeaveAttemptEvent extends MurderMysteryEvent { - - private static final HandlerList HANDLERS = new HandlerList(); - private final Player player; - - public MMGameLeaveAttemptEvent(Player player, Arena targetArena) { - super(targetArena); - this.player = player; - } - - public static HandlerList getHandlerList() { - return HANDLERS; - } - - public Player getPlayer() { - return player; - } - - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStateChangeEvent.java b/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStateChangeEvent.java deleted file mode 100644 index d2c478e4..00000000 --- a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStateChangeEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.api.events.game; - -import org.bukkit.event.HandlerList; -import plugily.projects.murdermystery.api.events.MurderMysteryEvent; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaState; - -/** - * @author Plajer - * @since 0.0.1-alpha - *

- * Called when arena game state has changed. - */ -public class MMGameStateChangeEvent extends MurderMysteryEvent { - - private static final HandlerList HANDLERS = new HandlerList(); - private final ArenaState arenaState; - - public MMGameStateChangeEvent(Arena eventArena, ArenaState arenaState) { - super(eventArena); - this.arenaState = arenaState; - } - - public static HandlerList getHandlerList() { - return HANDLERS; - } - - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - - public ArenaState getArenaState() { - return arenaState; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStopEvent.java b/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStopEvent.java deleted file mode 100644 index 98a3d2e1..00000000 --- a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStopEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.api.events.game; - -import org.bukkit.event.HandlerList; -import plugily.projects.murdermystery.api.events.MurderMysteryEvent; -import plugily.projects.murdermystery.arena.Arena; - -/** - * @author Plajer - * @since 0.0.3b - *

- * Called when arena is stopped. - */ -public class MMGameStopEvent extends MurderMysteryEvent { - - private static final HandlerList HANDLERS = new HandlerList(); - - public MMGameStopEvent(Arena arena) { - super(arena); - } - - public static HandlerList getHandlerList() { - return HANDLERS; - } - - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameJoinAttemptEvent.java b/src/main/java/plugily/projects/murdermystery/api/events/game/MurderGameCorpseSpawnEvent.java similarity index 66% rename from src/main/java/plugily/projects/murdermystery/api/events/game/MMGameJoinAttemptEvent.java rename to src/main/java/plugily/projects/murdermystery/api/events/game/MurderGameCorpseSpawnEvent.java index 3582c4e5..9763807d 100644 --- a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameJoinAttemptEvent.java +++ b/src/main/java/plugily/projects/murdermystery/api/events/game/MurderGameCorpseSpawnEvent.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,51 +18,56 @@ package plugily.projects.murdermystery.api.events.game; +import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; -import plugily.projects.murdermystery.api.events.MurderMysteryEvent; +import plugily.projects.minigamesbox.classic.api.event.PlugilyEvent; import plugily.projects.murdermystery.arena.Arena; /** - * @author Plajer - * @since 0.0.1-alpha + * @author Tigerpanzer_02 *

- * Called when player is attempting to join arena. + * Created at 15.04.2022 */ -public class MMGameJoinAttemptEvent extends MurderMysteryEvent implements Cancellable { +public class MurderGameCorpseSpawnEvent extends PlugilyEvent implements Cancellable { private static final HandlerList HANDLERS = new HandlerList(); + private boolean isCancelled = false; private final Player player; - private boolean isCancelled; + private final Location location; - public MMGameJoinAttemptEvent(Player player, Arena targetArena) { - super(targetArena); + public MurderGameCorpseSpawnEvent(Arena arena, Player player, Location location) { + super(arena); this.player = player; - this.isCancelled = false; + this.location = location; } public static HandlerList getHandlerList() { return HANDLERS; } + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + @Override public boolean isCancelled() { - return this.isCancelled; + return isCancelled; } @Override - public void setCancelled(boolean isCancelled) { - this.isCancelled = isCancelled; + public void setCancelled(boolean cancelled) { + isCancelled = cancelled; } public Player getPlayer() { return player; } - @Override - public HandlerList getHandlers() { - return HANDLERS; + public Location getLocation() { + return location; } } diff --git a/src/main/java/plugily/projects/murdermystery/api/events/game/package-info.java b/src/main/java/plugily/projects/murdermystery/api/events/game/package-info.java index 00527341..a8aff1a0 100644 --- a/src/main/java/plugily/projects/murdermystery/api/events/game/package-info.java +++ b/src/main/java/plugily/projects/murdermystery/api/events/game/package-info.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/main/java/plugily/projects/murdermystery/api/events/player/MMPlayerStatisticChangeEvent.java b/src/main/java/plugily/projects/murdermystery/api/events/player/MMPlayerStatisticChangeEvent.java deleted file mode 100644 index 917f4223..00000000 --- a/src/main/java/plugily/projects/murdermystery/api/events/player/MMPlayerStatisticChangeEvent.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/* - * Murder Mystery is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * Murder Mystery is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Murder Mystery. If not, see . - */ - -/* - * Murder Mystery is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * Murder Mystery is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Murder Mystery. If not, see . - */ - -package plugily.projects.murdermystery.api.events.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.api.events.MurderMysteryEvent; -import plugily.projects.murdermystery.arena.Arena; - -/** - * @author Plajer - * @see StatsStorage.StatisticType - * @since 0.0.3b - *

- * Called when player receive new statistic. - */ -public class MMPlayerStatisticChangeEvent extends MurderMysteryEvent { - - private static final HandlerList HANDLERS = new HandlerList(); - private final Player player; - private final StatsStorage.StatisticType statisticType; - private final int number; - - public MMPlayerStatisticChangeEvent(Arena eventArena, Player player, StatsStorage.StatisticType statisticType, int number) { - super(eventArena); - this.player = player; - this.statisticType = statisticType; - this.number = number; - } - - public static HandlerList getHandlerList() { - return HANDLERS; - } - - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - - public Player getPlayer() { - return player; - } - - public StatsStorage.StatisticType getStatisticType() { - return statisticType; - } - - public int getNumber() { - return number; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/api/events/player/package-info.java b/src/main/java/plugily/projects/murdermystery/api/events/player/package-info.java index ae78c82b..f030aa7d 100644 --- a/src/main/java/plugily/projects/murdermystery/api/events/player/package-info.java +++ b/src/main/java/plugily/projects/murdermystery/api/events/player/package-info.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/main/java/plugily/projects/murdermystery/api/package-info.java b/src/main/java/plugily/projects/murdermystery/api/package-info.java index 3537ca1e..706cc423 100644 --- a/src/main/java/plugily/projects/murdermystery/api/package-info.java +++ b/src/main/java/plugily/projects/murdermystery/api/package-info.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/main/java/plugily/projects/murdermystery/arena/Arena.java b/src/main/java/plugily/projects/murdermystery/arena/Arena.java index 79be513f..e9ba6bf4 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/Arena.java +++ b/src/main/java/plugily/projects/murdermystery/arena/Arena.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,115 +18,93 @@ package plugily.projects.murdermystery.arena; -import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; -import org.bukkit.GameMode; import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarStyle; -import org.bukkit.boss.BossBar; import org.bukkit.entity.Item; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; -import org.golde.bukkit.corpsereborn.CorpseAPI.CorpseAPI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; - -import plugily.projects.commonsbox.number.NumberUtils; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.compat.xseries.XSound; -import plugily.projects.commonsbox.minecraft.hologram.ArmorStandHologram; -import plugily.projects.commonsbox.minecraft.serialization.InventorySerializer; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.HookManager; +import plugily.projects.minigamesbox.classic.arena.ArenaState; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.managers.PluginMapRestorerManager; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.hologram.ArmorStandHologram; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.api.events.game.MMGameStartEvent; -import plugily.projects.murdermystery.api.events.game.MMGameStateChangeEvent; import plugily.projects.murdermystery.arena.corpse.Corpse; import plugily.projects.murdermystery.arena.corpse.Stand; +import plugily.projects.murdermystery.arena.managers.MapRestorerManager; import plugily.projects.murdermystery.arena.managers.ScoreboardManager; -import plugily.projects.murdermystery.arena.options.ArenaOption; import plugily.projects.murdermystery.arena.role.Role; +import plugily.projects.murdermystery.arena.states.InGameState; +import plugily.projects.murdermystery.arena.states.RestartingState; +import plugily.projects.murdermystery.arena.states.StartingState; +import plugily.projects.murdermystery.HookManager; import plugily.projects.murdermystery.arena.special.SpecialBlock; -import plugily.projects.murdermystery.arena.special.pray.PrayerRegistry; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.rewards.Reward; -import plugily.projects.murdermystery.user.User; -import plugily.projects.murdermystery.utils.Debugger; -import plugily.projects.murdermystery.utils.ItemPosition; -import plugily.projects.murdermystery.utils.Utils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Random; -import java.util.Set; -import java.util.logging.Level; -import java.util.stream.Collectors; - -public class Arena extends BukkitRunnable { - - private static final Random random = new Random(); - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private final ChatManager chatManager = plugin.getChatManager(); - private final String id; - - private final Set players = new HashSet<>(); +import plugily.projects.murdermystery.arena.states.WaitingState; + +import java.util.*; + +/** + * @author Tigerpanzer_02 + *

+ * Created at 17.12.2021 + */ +public class Arena extends PluginArena { + + private static Main plugin; + + private final List spectators = new ArrayList<>(); + private final List deaths = new ArrayList<>(); + private final List detectives = new ArrayList<>(); + private final List murderers = new ArrayList<>(); private final List goldSpawned = new ArrayList<>(); private final List corpses = new ArrayList<>(); private final List stands = new ArrayList<>(); private final List specialBlocks = new ArrayList<>(); - private final List allMurderer = new ArrayList<>(), allDetectives = new ArrayList<>(), - spectators = new ArrayList<>(), deaths = new ArrayList<>(); - - //contains murderer, detective, fake detective and hero + private List goldSpawnPoints = new ArrayList<>(); + private List playerSpawnPoints = new ArrayList<>(); + private int spawnGoldTimer = 0; + private int spawnGoldTime = 0; + private boolean detectiveDead; + private boolean murdererLocatorReceived; + private boolean hideChances; + private boolean goldVisuals = false; private final Map gameCharacters = new EnumMap<>(CharacterType.class); - //all arena values that are integers, contains constant and floating values - private final Map arenaOptions = new EnumMap<>(ArenaOption.class); - //instead of 3 location fields we use map with GameLocation enum - private final Map gameLocations = new EnumMap<>(GameLocation.class); + private MapRestorerManager mapRestorerManager; + private ArmorStandHologram bowHologram; - private final ScoreboardManager scoreboardManager; + public Arena(String id) { + super(id); + setPluginValues(); + setScoreboardManager(new ScoreboardManager(this)); + mapRestorerManager = new MapRestorerManager(this); + setMapRestorerManager(mapRestorerManager); + addGameStateHandler(ArenaState.IN_GAME, new InGameState()); + addGameStateHandler(ArenaState.RESTARTING, new RestartingState()); + addGameStateHandler(ArenaState.STARTING, new StartingState()); + addGameStateHandler(ArenaState.WAITING_FOR_PLAYERS, new WaitingState()); + } - private List goldSpawnPoints = new ArrayList<>(), playerSpawnPoints = new ArrayList<>(); + public static void init(Main plugin) { + Arena.plugin = plugin; + } - private int murderers = 0, detectives = 0, spawnGoldTimer = 0, spawnGoldTime = 0; + @Override + public Main getPlugin() { + return plugin; + } - private boolean detectiveDead, murdererLocatorReceived, hideChances, ready = true, forceStart = false, goldVisuals = false; - private ArenaState arenaState = ArenaState.WAITING_FOR_PLAYERS; - private BossBar gameBar; - private String mapName = ""; - public Arena(String id) { - this.id = id; - for(ArenaOption option : ArenaOption.values()) { - arenaOptions.put(option, option.getDefaultValue()); - } - if(ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_9_R1) && plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BOSSBAR_ENABLED)) { - gameBar = Bukkit.createBossBar(chatManager.colorMessage("Bossbar.Main-Title"), BarColor.BLUE, BarStyle.SOLID); - } - scoreboardManager = new ScoreboardManager(this); + @Override + public PluginMapRestorerManager getMapRestorerManager() { + return mapRestorerManager; } - public boolean isReady() { - return ready; - } - public void setReady(boolean ready) { - this.ready = ready; + private void setPluginValues() { } public void addCorpse(Corpse corpse) { @@ -139,466 +117,12 @@ public List getCorpses() { return corpses; } - public void addHead(Stand stand) { - stands.add(stand); + public List getStands() { + return stands; } - @Override - public void run() { - //idle task - if(arenaState == ArenaState.WAITING_FOR_PLAYERS && players.isEmpty()) { - return; - } - Debugger.performance("ArenaTask", "[PerformanceMonitor] [{0}] Running game task", getId()); - long start = System.currentTimeMillis(); - - boolean bossBarEnabled = ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_9_R1) && plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BOSSBAR_ENABLED); - - switch(arenaState) { - case WAITING_FOR_PLAYERS: - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - plugin.getServer().setWhitelist(false); - } - int minPlayers = getMinimumPlayers(); - if(players.size() < minPlayers) { - if(getTimer() <= 0) { - setTimer(45); - chatManager.broadcast(this, chatManager.formatMessage(this, chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Waiting-For-Players"), minPlayers)); - break; - } - } else { - if(bossBarEnabled) { - gameBar.setTitle(chatManager.colorMessage("Bossbar.Waiting-For-Players")); - } - chatManager.broadcast(this, chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Enough-Players-To-Start")); - setArenaState(ArenaState.STARTING); - setTimer(plugin.getConfig().getInt("Starting-Waiting-Time", 60)); - showPlayers(); - } - setTimer(getTimer() - 1); - break; - case STARTING: - int startTimeFull = plugin.getConfig().getInt("Start-Time-On-Full-Lobby", 15); - - if(!forceStart && players.size() == getMaximumPlayers() && getTimer() >= startTimeFull) { - setTimer(startTimeFull); - chatManager.broadcast(this, chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Start-In").replace("%TIME%", Integer.toString(getTimer()))); - } - - int timer = getTimer(); - double startWaitingTime = plugin.getConfig().getDouble("Starting-Waiting-Time", 60); - - if(bossBarEnabled) { - gameBar.setTitle(chatManager.colorMessage("Bossbar.Starting-In").replace("%time%", Integer.toString(timer))); - gameBar.setProgress(timer / startWaitingTime); - } - - for(Player player : players) { - player.setExp((float) (timer / startWaitingTime)); - player.setLevel(timer); - } - - int minimumPlayers = getMinimumPlayers(); - - if(!forceStart && players.size() < minimumPlayers) { - if(bossBarEnabled) { - gameBar.setTitle(chatManager.colorMessage("Bossbar.Waiting-For-Players")); - gameBar.setProgress(1.0); - } - - chatManager.broadcast(this, chatManager.formatMessage(this, chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Waiting-For-Players"), minimumPlayers)); - setArenaState(ArenaState.WAITING_FOR_PLAYERS); - Bukkit.getPluginManager().callEvent(new MMGameStartEvent(this)); - setTimer(15); - - for(Player player : players) { - player.setExp(1); - player.setLevel(0); - } - - if(forceStart) { - forceStart = false; - } - - break; - } - - int totalMurderer = 0; - int totalDetective = 0; - - for(Player p : players) { - User user = plugin.getUserManager().getUser(p); - totalMurderer += user.getStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER); - totalDetective += user.getStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE); - } - - if(!hideChances) { - for(Player p : players) { - VersionUtils.sendActionBar(p, formatRoleChance(plugin.getUserManager().getUser(p), totalMurderer, totalDetective)); - } - } - - if(forceStart || getTimer() == 0) { - Bukkit.getPluginManager().callEvent(new MMGameStartEvent(this)); - setArenaState(ArenaState.IN_GAME); - - if(bossBarEnabled) { - gameBar.setProgress(1.0); - } - - setTimer(5); - - if(players.isEmpty()) { - break; - } - - for(Player player : players) { - teleportToStartLocation(player); - - //reset local variables to be 100% sure - User user = plugin.getUserManager().getUser(player); - user.setStat(StatsStorage.StatisticType.LOCAL_GOLD, 0); - user.setStat(StatsStorage.StatisticType.LOCAL_CURRENT_PRAY, 0); - user.setStat(StatsStorage.StatisticType.LOCAL_KILLS, 0); - user.setStat(StatsStorage.StatisticType.LOCAL_PRAISES, 0); - user.setStat(StatsStorage.StatisticType.LOCAL_SCORE, 0); - - ArenaUtils.updateNameTagsVisibility(player); - player.getInventory().clear(); - player.setGameMode(GameMode.ADVENTURE); - ArenaUtils.hidePlayersOutsideTheGame(player, this); - player.updateInventory(); - user.addStat(StatsStorage.StatisticType.GAMES_PLAYED, 1); - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Game-Started")); - } - - setTimer(plugin.getConfig().getInt("Classic-Gameplay-Time", 270)); - - Map murdererChances = new HashMap<>(), detectiveChances = new HashMap<>(); - for(Player p : players) { - User user = plugin.getUserManager().getUser(p); - murdererChances.put(user, ((double) user.getStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER) / (double) totalMurderer) * 100.0); - detectiveChances.put(user, ((double) user.getStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE) / (double) totalDetective) * 100.0); - } - //shuffling map to avoid the same murders on the next round - List> shuffledMurderer = new ArrayList<>(murdererChances.entrySet()); - Collections.shuffle(shuffledMurderer); - // - Map sortedMurderer = shuffledMurderer.stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).collect( - Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new)); - - Set playersToSet = new HashSet<>(players); - int maxmurderer = 1; - int maxdetectives = 1; - int playersSize = players.size(); - - Debugger.debug("Before: Arena: {0} | Detectives = {1}, Murders = {2}, Players = {3} | Configured: Detectives = {4}, Murders = {5}", - getId(), maxdetectives, maxmurderer, playersSize, detectives, murderers); - if(murderers > 1 && playersSize > murderers) { - maxmurderer = (playersSize / murderers); - } - if(detectives > 1 && playersSize > detectives) { - maxdetectives = (playersSize / detectives); - } - if(playersSize - (maxmurderer + maxdetectives) < 1) { - Debugger.debug("{0} Murderers and detectives amount was reduced because there are not enough players", getId()); - //Make sure to have one innocent! - if(maxdetectives > 1) { - maxdetectives--; - } else if(maxmurderer > 1) { - maxmurderer--; - } - } - - Debugger.debug("After: Arena: {0} | Detectives = {1}, Murders = {2}, Players = {3} | Configured: Detectives = {4}, Murders = {5}", - getId(), maxdetectives, maxmurderer, playersSize, detectives, murderers); - - Object[] sortedMurdererArray = sortedMurderer.keySet().toArray(); - - for(int i = 0; i < maxmurderer; i++) { - if (i >= sortedMurdererArray.length) - break; - - Player murderer = ((User) sortedMurdererArray[i]).getPlayer(); - setCharacter(CharacterType.MURDERER, murderer); - allMurderer.add(murderer); - plugin.getUserManager().getUser(murderer).setStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, 1); - playersToSet.remove(murderer); - VersionUtils.sendTitles(murderer, chatManager.colorMessage("In-Game.Messages.Role-Set.Murderer-Title"), - chatManager.colorMessage("In-Game.Messages.Role-Set.Murderer-Subtitle"), 5, 40, 5); - detectiveChances.remove(sortedMurdererArray[i]); - } - - //shuffling map to avoid the same detectives on the next round - List> shuffledDetectives = new ArrayList<>(detectiveChances.entrySet()); - Collections.shuffle(shuffledDetectives); - - Map sortedDetective = shuffledDetectives.stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).collect( - Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new)); - - Object[] sortedDetArray = sortedDetective.keySet().toArray(); - - for(int i = 0; i < maxdetectives; i++) { - if (i >= sortedDetArray.length) - break; - - Player detective = ((User) sortedDetArray[i]).getPlayer(); - setCharacter(CharacterType.DETECTIVE, detective); - allDetectives.add(detective); - plugin.getUserManager().getUser(detective).setStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, 1); - VersionUtils.sendTitles(detective, chatManager.colorMessage("In-Game.Messages.Role-Set.Detective-Title"), - chatManager.colorMessage("In-Game.Messages.Role-Set.Detective-Subtitle"), 5, 40, 5); - playersToSet.remove(detective); - detective.getInventory().setHeldItemSlot(0); - ItemPosition.setItem(detective, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); - ItemPosition.setItem(detective, ItemPosition.INFINITE_ARROWS, new ItemStack(Material.ARROW, plugin.getConfig().getInt("Detective-Default-Arrows", 3))); - } - Debugger.debug("Arena: {0} | Detectives = {1}, Murders = {2}, Players = {3} | Players: Detectives = {4}, Murders = {5}", - getId(), maxdetectives, maxmurderer, playersSize, allDetectives, allMurderer); - - for(Player p : playersToSet) { - VersionUtils.sendTitles(p, chatManager.colorMessage("In-Game.Messages.Role-Set.Innocent-Title"), - chatManager.colorMessage("In-Game.Messages.Role-Set.Innocent-Subtitle"), 5, 40, 5); - } - if(bossBarEnabled) { - gameBar.setTitle(chatManager.colorMessage("Bossbar.In-Game-Info")); - } - - // Load and append special blocks hologram - specialBlocks.forEach(this::loadSpecialBlock); - } - if(forceStart) { - forceStart = false; - } - setTimer(getTimer() - 1); - break; - case IN_GAME: - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - plugin.getServer().setWhitelist(getMaximumPlayers() <= players.size()); - } - if(getTimer() <= 0) { - ArenaManager.stopGame(false, this); - } - - int currentTimer = getTimer(); - int classicGameplayTime = plugin.getConfig().getInt("Classic-Gameplay-Time", 270); - - if(currentTimer <= (classicGameplayTime - 10) && currentTimer > (classicGameplayTime - 15)) { - String murdererGetSword = chatManager.colorMessage("In-Game.Messages.Murderer-Get-Sword") - .replace("%time%", Integer.toString(currentTimer - (classicGameplayTime - 15))); - - for(Player p : players) { - p.sendMessage(murdererGetSword); - XSound.UI_BUTTON_CLICK.play(p.getLocation(), 1, 1); - } - - if(currentTimer == (classicGameplayTime - 14)) { - if(allMurderer.isEmpty()) ArenaManager.stopGame(false, this); - - for(Player p : allMurderer) { - User murderer = plugin.getUserManager().getUser(p); - - if(murderer.isSpectator() || !p.isOnline() || ArenaRegistry.getArena(p) != this) - continue; - - p.getInventory().setHeldItemSlot(0); - ItemPosition.setItem(p, ItemPosition.MURDERER_SWORD, plugin.getConfigPreferences().getMurdererSword()); - } - } - } - - // Cache at least once for fast processing - List playersLeft = getPlayersLeft(); - - //every 30 secs survive reward - if(currentTimer % 30 == 0) { - for(Player p : playersLeft) { - if(Role.isRole(Role.INNOCENT, p, this)) { - ArenaUtils.addScore(plugin.getUserManager().getUser(p), ArenaUtils.ScoreAction.SURVIVE_TIME, 0); - } - } - } - - if(currentTimer == 30 || currentTimer == 60) { - String strTimer = Integer.toString(currentTimer); - String title = chatManager.colorMessage("In-Game.Messages.Seconds-Left-Title").replace("%time%", strTimer); - String subtitle = chatManager.colorMessage("In-Game.Messages.Seconds-Left-Subtitle").replace("%time%", strTimer); - for(Player p : players) { - VersionUtils.sendTitles(p, title, subtitle, 5, 40, 5); - } - } - - if(currentTimer <= 30 || playersLeft.size() == aliveMurderer() + 1) { - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.INNOCENT_LOCATOR)) { - ArenaUtils.updateInnocentLocator(this); - } - } - //no players - stop game - if(playersLeft.isEmpty()) { - ArenaManager.stopGame(false, this); - } else { - //winner check - if(playersLeft.size() == aliveMurderer()) { - String loseTitle = chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Titles.Lose"); - String murdererKill = chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Subtitles.Murderer-Kill-Everyone"); - String titleWin = chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Titles.Win"); - - for(Player p : players) { - VersionUtils.sendTitles(p, loseTitle, murdererKill, 5, 40, 5); - - if(allMurderer.contains(p)) { - VersionUtils.sendTitles(p, titleWin, null, 5, 40, 5); - } - } - - ArenaManager.stopGame(false, this); - //murderer speed add - } else if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.MURDERER_SPEED_ENABLED) && playersLeft.size() == aliveMurderer() + 1) { - int multiplier = plugin.getConfig().getInt("Speed-Effect-Murderer.Speed", 3); - - if(multiplier > 1 && multiplier <= 10) { - for(Player p : allMurderer) { - if(isMurderAlive(p)) { - //no potion because it adds particles which can be identified - p.setWalkSpeed(0.1f * multiplier); - } - } - } - } - } - //don't spawn it every time - if(spawnGoldTimer == spawnGoldTime) { - spawnSomeGold(); - spawnGoldTimer = 0; - } else { - spawnGoldTimer++; - } - setTimer(getTimer() - 1); - break; - case ENDING: - scoreboardManager.stopAllScoreboards(); - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - plugin.getServer().setWhitelist(false); - } - if(getTimer() <= 0) { - if(bossBarEnabled) { - gameBar.setTitle(chatManager.colorMessage("Bossbar.Game-Ended")); - } - - for(Player player : new ArrayList<>(players)) { - plugin.getUserManager().getUser(player).removeScoreboard(this); - player.setGameMode(GameMode.SURVIVAL); - for(Player players : Bukkit.getOnlinePlayers()) { - VersionUtils.showPlayer(plugin, player, players); - if(!ArenaRegistry.isInArena(players)) { - VersionUtils.showPlayer(plugin, players, player); - } - } - player.getActivePotionEffects().forEach(effect -> player.removePotionEffect(effect.getType())); - player.setWalkSpeed(0.2f); - player.setFlying(false); - player.setAllowFlight(false); - player.getInventory().clear(); - - player.getInventory().setArmorContents(null); - doBarAction(BarAction.REMOVE, player); - player.setFireTicks(0); - player.setFoodLevel(20); - PrayerRegistry.getRush().remove(player); - PrayerRegistry.getBan().remove(player); - teleportToEndLocation(player); - } - - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.INVENTORY_MANAGER_ENABLED)) { - for(Player player : players) { - InventorySerializer.loadInventory(plugin, player); - } - } - - chatManager.broadcast(this, chatManager.colorMessage("Commands.Teleported-To-The-Lobby")); - - for(User user : plugin.getUserManager().getUsers(this)) { - user.setSpectator(false); - VersionUtils.setCollidable(user.getPlayer(), true); - plugin.getUserManager().saveAllStatistic(user); - } - plugin.getRewardsHandler().performReward(this, Reward.RewardType.END_GAME); - players.clear(); - - deaths.clear(); - spectators.clear(); - - cleanUpArena(); - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED) - && ConfigUtils.getConfig(plugin, "bungee").getBoolean("Shutdown-When-Game-Ends")) { - plugin.getServer().shutdown(); - } - setArenaState(ArenaState.RESTARTING); - } - setTimer(getTimer() - 1); - break; - case RESTARTING: - players.clear(); - setArenaState(ArenaState.WAITING_FOR_PLAYERS); - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - ArenaRegistry.shuffleBungeeArena(); - for(Player player : Bukkit.getOnlinePlayers()) { - ArenaManager.joinAttempt(player, ArenaRegistry.getArenas().get(ArenaRegistry.getBungeeArena())); - } - } - if(bossBarEnabled) { - gameBar.setTitle(chatManager.colorMessage("Bossbar.Waiting-For-Players")); - } - - if(goldVisuals) { - startGoldVisuals(); - } - - break; - default: - break; //o.o? - } - Debugger.performance("ArenaTask", "[PerformanceMonitor] [{0}] Game task finished took {1}ms", - - getId(), System. - - currentTimeMillis() - start); - } - - private String formatRoleChance(User user, int murdererPts, int detectivePts) throws NumberFormatException { - String message = chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Role-Chances-Action-Bar"); - message = StringUtils.replace(message, "%murderer_chance%", NumberUtils.round(((double) user.getStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER) / (double) murdererPts) * 100.0, 2) + "%"); - message = StringUtils.replace(message, "%detective_chance%", NumberUtils.round(((double) user.getStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE) / (double) detectivePts) * 100.0, 2) + "%"); - return message; - } - - private void spawnSomeGold() { - int spawnPointsSize = goldSpawnPoints.size(); - - if(spawnPointsSize == 0) { - return; - } - - //may users want to disable it and want much gold on there map xD - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DISABLE_GOLD_LIMITER)) { - //do not exceed amount of gold per spawn - if(goldSpawned.size() >= spawnPointsSize) { - return; - } - } - - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.SPAWN_GOLD_EVERY_SPAWNER_MODE)) { - for(Location location : goldSpawnPoints) { - goldSpawned.add(location.getWorld().dropItem(location, new ItemStack(Material.GOLD_INGOT, 1))); - } - } else { - Location loc = goldSpawnPoints.get(spawnPointsSize == 1 ? 0 : random.nextInt(spawnPointsSize)); - goldSpawned.add(loc.getWorld().dropItem(loc, new ItemStack(Material.GOLD_INGOT, 1))); - } - } - - public void setMurderers(int murderers) { - this.murderers = murderers; + public void addHead(Stand stand) { + stands.add(stand); } public void setSpawnGoldTime(int spawnGoldTime) { @@ -617,10 +141,6 @@ public void setDetectiveDead(boolean detectiveDead) { this.detectiveDead = detectiveDead; } - public void setDetectives(int detectives) { - this.detectives = detectives; - } - public boolean isMurdererLocatorReceived() { return murdererLocatorReceived; } @@ -629,12 +149,12 @@ public void setMurdererLocatorReceived(boolean murdererLocatorReceived) { this.murdererLocatorReceived = murdererLocatorReceived; } - public void setForceStart(boolean forceStart) { - this.forceStart = forceStart; + public Map getGameCharacters() { + return gameCharacters; } - public ScoreboardManager getScoreboardManager() { - return scoreboardManager; + public boolean isHideChances() { + return hideChances; } @NotNull @@ -651,34 +171,22 @@ public void setGoldSpawnPoints(@NotNull List goldSpawnPoints) { this.goldSpawnPoints = goldSpawnPoints; } - public void toggleGoldVisuals() { - if(goldSpawnPoints.isEmpty() || goldVisuals) { - goldVisuals = false; - return; - } - setGoldVisuals(true); - } - private BukkitTask visualTask; - private void startGoldVisuals() { + public void startGoldVisuals() { if(visualTask != null) { return; } visualTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> { - if(!goldVisuals || !plugin.isEnabled() || goldSpawnPoints.isEmpty() || arenaState != ArenaState.WAITING_FOR_PLAYERS) { + if(!goldVisuals || !plugin.isEnabled() || goldSpawnPoints.isEmpty() || getArenaState() != ArenaState.WAITING_FOR_PLAYERS) { //we need to cancel it that way as the arena class is an task visualTask.cancel(); return; } - for(Location goldLocations : goldSpawnPoints) { Location goldLocation = goldLocations.clone(); goldLocation.add(0, 0.4, 0); - java.util.Iterator iterator = Bukkit.getOnlinePlayers().iterator(); - if (iterator.hasNext()) { - VersionUtils.sendParticles("REDSTONE", iterator.next(), goldLocation, 10); - } + Bukkit.getOnlinePlayers().forEach(player -> VersionUtils.sendParticles("REDSTONE", player, goldLocation, 10)); } }, 20L, 20L); } @@ -694,269 +202,19 @@ public void setGoldVisuals(boolean goldVisuals) { } } - /** - * Get arena identifier used to get arenas by string. - * - * @return arena name - * @see ArenaRegistry#getArena(String) - */ - public String getId() { - return id; - } - - /** - * Get minimum players needed. - * - * @return minimum players needed to start arena - */ - public int getMinimumPlayers() { - return getOption(ArenaOption.MINIMUM_PLAYERS); - } - - /** - * Set minimum players needed. - * - * @param minimumPlayers players needed to start arena - */ - public void setMinimumPlayers(int minimumPlayers) { - if(minimumPlayers < 2) { - Debugger.debug(Level.WARNING, "Minimum players amount for arena cannot be less than 2! Got {0}", minimumPlayers); - minimumPlayers = 2; - } - - setOptionValue(ArenaOption.MINIMUM_PLAYERS, minimumPlayers); - } - - /** - * Get arena map name. - * - * @return arena map name, it's not arena id - * @see #getId() - */ - @NotNull - public String getMapName() { - return mapName; - } - - /** - * Set arena map name. - * - * @param mapname new map name, it's not arena id - */ - public void setMapName(@NotNull String mapname) { - this.mapName = mapname; - } - - /** - * Get timer of arena. - * - * @return timer of lobby time / time to next wave - */ - public int getTimer() { - return getOption(ArenaOption.TIMER); - } - - /** - * Modify game timer. - * - * @param timer timer of lobby / time to next wave - */ - public void setTimer(int timer) { - setOptionValue(ArenaOption.TIMER, timer); - } - - /** - * Return maximum players arena can handle. - * - * @return maximum players arena can handle - */ - public int getMaximumPlayers() { - return getOption(ArenaOption.MAXIMUM_PLAYERS); - } - - /** - * Set maximum players arena can handle. - * - * @param maximumPlayers how many players arena can handle - */ - public void setMaximumPlayers(int maximumPlayers) { - setOptionValue(ArenaOption.MAXIMUM_PLAYERS, maximumPlayers); - } - - /** - * Return game state of arena. - * - * @return game state of arena - * @see ArenaState - */ - @NotNull - public ArenaState getArenaState() { - return arenaState; - } - - /** - * Set game state of arena. - * - * @param arenaState new game state of arena - * @see ArenaState - */ - public void setArenaState(@NotNull ArenaState arenaState) { - this.arenaState = arenaState; - - Bukkit.getPluginManager().callEvent(new MMGameStateChangeEvent(this, arenaState)); - - plugin.getSignManager().updateSigns(); - } - - /** - * Get all players in arena. - * - * @return set of players in arena - */ - @NotNull - public Set getPlayers() { - return players; - } - - public void teleportToLobby(Player player) { - player.setFoodLevel(20); - player.setFlying(false); - player.setAllowFlight(false); - player.getActivePotionEffects().forEach(effect -> player.removePotionEffect(effect.getType())); - player.setWalkSpeed(0.2f); - Location location = getLobbyLocation(); - if(location == null) { - System.out.print("LobbyLocation isn't intialized for arena " + getId()); - return; - } - player.teleport(location); - } - - /** - * Executes boss bar action for arena - * - * @param action add or remove a player from boss bar - * @param p player - */ - public void doBarAction(BarAction action, Player p) { - if(!ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_9_R1) - || !plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BOSSBAR_ENABLED)) { - return; - } - switch(action) { - case ADD: - gameBar.addPlayer(p); - break; - case REMOVE: - gameBar.removePlayer(p); - break; - default: - break; - } - } - - /** - * Get lobby location of arena. - * - * @return lobby location of arena - */ - @Nullable - public Location getLobbyLocation() { - return gameLocations.get(GameLocation.LOBBY); - } - - /** - * Set lobby location of arena. - * - * @param loc new lobby location of arena - */ - public void setLobbyLocation(Location loc) { - gameLocations.put(GameLocation.LOBBY, loc); - } - - public void teleportToStartLocation(Player player) { - int size = playerSpawnPoints.size(); - player.teleport(playerSpawnPoints.get(size == 1 ? 0 : random.nextInt(size))); - } - - public void teleportAllToEndLocation() { - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED) - && ConfigUtils.getConfig(plugin, "bungee").getBoolean("End-Location-Hub", true)) { - players.forEach(plugin.getBungeeManager()::connectToHub); - return; - } - - Location location = getEndLocation(); - if(location == null) { - location = getLobbyLocation(); - System.out.print("EndLocation for arena " + getId() + " isn't intialized!"); - } - - if(location != null) { - for(Player player : players) { - player.teleport(location); - } - } - } - - public void teleportToEndLocation(Player player) { - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED) - && ConfigUtils.getConfig(plugin, "bungee").getBoolean("End-Location-Hub", true)) { - plugin.getBungeeManager().connectToHub(player); - return; - } - - Location location = getEndLocation(); - if(location == null) { - System.out.print("EndLocation for arena " + getId() + " isn't intialized!"); - location = getLobbyLocation(); - } - - if(location != null) { - player.teleport(location); - } - } - - public List getPlayerSpawnPoints() { - return playerSpawnPoints; - } - - public void setPlayerSpawnPoints(@NotNull List playerSpawnPoints) { - this.playerSpawnPoints = playerSpawnPoints; - } - - /** - * Get end location of arena. - * - * @return end location of arena - */ - @Nullable - public Location getEndLocation() { - return gameLocations.get(GameLocation.END); - } - - /** - * Set end location of arena. - * - * @param endLoc new end location of arena - */ - public void setEndLocation(Location endLoc) { - gameLocations.put(GameLocation.END, endLoc); - } - public void loadSpecialBlock(SpecialBlock block) { - if (!specialBlocks.contains(block)) { + if(!specialBlocks.contains(block)) { specialBlocks.add(block); } switch(block.getSpecialBlockType()) { case MYSTERY_CAULDRON: - block.setArmorStandHologram(new ArmorStandHologram(Utils.getBlockCenter(block.getLocation()), chatManager.colorMessage("In-Game.Messages.Special-Blocks.Cauldron-Hologram"))); + block.setArmorStandHologram(new ArmorStandHologram(plugin.getBukkitHelper().getBlockCenter(block.getLocation()), new MessageBuilder(plugin.getLanguageManager().getLanguageMessage("In-Game.Messages.Arena.Playing.Special-Blocks.Cauldron.Hologram")).build())); break; case PRAISE_DEVELOPER: - ArmorStandHologram prayer = new ArmorStandHologram(Utils.getBlockCenter(block.getLocation())); - for(String str : chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praise-Hologram").split(";")) { - prayer.appendLine(str); + ArmorStandHologram prayer = new ArmorStandHologram(plugin.getBukkitHelper().getBlockCenter(block.getLocation())); + for(String str : plugin.getLanguageManager().getLanguageMessage("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Hologram").split(";")) { + prayer.appendLine(new MessageBuilder(str).build()); } block.setArmorStandHologram(prayer); break; @@ -972,101 +230,37 @@ public List getSpecialBlocks() { return specialBlocks; } - public void start() { - Debugger.debug("[{0}] Game instance started", getId()); - runTaskTimer(plugin, 20L, 20L); - setArenaState(ArenaState.RESTARTING); - } - - void addPlayer(Player player) { - players.add(player); - } - - void removePlayer(Player player) { - if(player != null) { - players.remove(player); - } - } - - public List getPlayersLeft() { - List list = new ArrayList<>(); - - for (Player player : players) { - User user = plugin.getUserManager().getUser(player); - if (!user.isSpectator()) { - list.add(user.getPlayer()); - } - } - - return list; - } - - void showPlayers() { - for(Player player : players) { - for(Player p : players) { - VersionUtils.showPlayer(plugin, player, p); - VersionUtils.showPlayer(plugin, p, player); - } - } - } - - public void cleanUpArena() { - removeBowHolo(); + public int getTotalRoleChances(Role role) { + int totalRoleChances = 0; - murdererLocatorReceived = false; - gameCharacters.clear(); - allMurderer.clear(); - allDetectives.clear(); - setDetectiveDead(false); - clearCorpses(); - clearGold(); - } - - public void clearGold() { - goldSpawned.stream().filter(Objects::nonNull).forEach(Item::remove); - goldSpawned.clear(); - } - - public void clearCorpses() { - if(!plugin.getHookManager().isFeatureEnabled(HookManager.HookFeature.CORPSES)) { - for(Stand stand : stands) { - if(!stand.getHologram().isDeleted()) { - stand.getHologram().delete(); - } - if(stand.getStand() != null) { - stand.getStand().remove(); - } - } - stands.clear(); - return; - } - for(Corpse corpse : corpses) { - if(!corpse.getHologram().isDeleted()) { - corpse.getHologram().delete(); - } - if(corpse.getCorpseData() != null) { - corpse.getCorpseData().destroyCorpseFromEveryone(); - CorpseAPI.removeCorpse(corpse.getCorpseData()); - } + for(Player p : getPlayers()) { + User user = getPlugin().getUserManager().getUser(p); + totalRoleChances += getContributorValue(role, user); } - corpses.clear(); + //avoid division / 0 + Bukkit.getConsoleSender().sendMessage(role.name() + "->T:" + totalRoleChances); + return totalRoleChances == 0 ? 1 : totalRoleChances; } - public boolean isCharacterSet(CharacterType type) { + public boolean isCharacterSet(Arena.CharacterType type) { return gameCharacters.containsKey(type); } - public void setCharacter(CharacterType type, Player player) { + public void setCharacter(Arena.CharacterType type, Player player) { gameCharacters.put(type, player); } + public void setCharacter(Role role, Player player) { + gameCharacters.put(role == Role.MURDERER ? CharacterType.MURDERER : CharacterType.DETECTIVE, player); + } + @Nullable - public Player getCharacter(CharacterType type) { + public Player getCharacter(Arena.CharacterType type) { return gameCharacters.get(type); } public void addToDetectiveList(Player player) { - allDetectives.add(player); + detectives.add(player); } public boolean lastAliveDetective() { @@ -1075,8 +269,8 @@ public boolean lastAliveDetective() { public int aliveDetective() { int alive = 0; - for(Player p : getPlayersLeft()) { - if(Role.isRole(Role.ANY_DETECTIVE, p, this) && isDetectiveAlive(p)) { + for(Player player : getPlayersLeft()) { + if(Role.isRole(Role.ANY_DETECTIVE, plugin.getUserManager().getUser(player), this) && isDetectiveAlive(player)) { alive++; } } @@ -1085,7 +279,7 @@ public int aliveDetective() { public boolean isDetectiveAlive(Player player) { for(Player p : getPlayersLeft()) { - if(p == player && allDetectives.contains(p)) { + if(p == player && detectives.contains(p)) { return true; } } @@ -1093,15 +287,15 @@ public boolean isDetectiveAlive(Player player) { } public List getDetectiveList() { - return allDetectives; + return detectives; } public void addToMurdererList(Player player) { - allMurderer.add(player); + murderers.add(player); } public void removeFromMurdererList(Player player) { - allMurderer.remove(player); + murderers.remove(player); } @@ -1111,8 +305,8 @@ public boolean lastAliveMurderer() { public int aliveMurderer() { int alive = 0; - for(Player p : getPlayersLeft()) { - if(Role.isRole(Role.MURDERER, p, this) && isMurderAlive(p)) { + for(Player player : getPlayersLeft()) { + if(Role.isRole(Role.MURDERER, plugin.getUserManager().getUser(player), this) && isMurderAlive(player)) { alive++; } } @@ -1121,7 +315,7 @@ public int aliveMurderer() { public boolean isMurderAlive(Player player) { for(Player p : getPlayersLeft()) { - if(p == player && allMurderer.contains(p)) { + if(p == player && murderers.contains(p)) { return true; } } @@ -1129,42 +323,7 @@ public boolean isMurderAlive(Player player) { } public List getMurdererList() { - return allMurderer; - } - - public int getOption(@NotNull ArenaOption option) { - return arenaOptions.getOrDefault(option, 0); - } - - public void setOptionValue(ArenaOption option, int value) { - arenaOptions.put(option, value); - } - - public void addOptionValue(ArenaOption option, int value) { - arenaOptions.put(option, getOption(option) + value); - } - - public enum BarAction { - ADD, REMOVE - } - - public enum GameLocation { - LOBBY, END - } - - public enum CharacterType { - MURDERER, DETECTIVE, FAKE_DETECTIVE, HERO - } - - - private ArmorStandHologram bowHologram; - - public void removeBowHolo() { - if(bowHologram != null && !bowHologram.isDeleted()) { - bowHologram.delete(); - } - - bowHologram = null; + return murderers; } public void setBowHologram(ArmorStandHologram bowHologram) { @@ -1192,6 +351,10 @@ public boolean isDeathPlayer(Player player) { return deaths.contains(player); } + public List getDeaths() { + return deaths; + } + public void addSpectatorPlayer(Player player) { spectators.add(player); } @@ -1204,4 +367,68 @@ public boolean isSpectatorPlayer(Player player) { return spectators.contains(player); } -} + public List getPlayerSpawnPoints() { + return playerSpawnPoints; + } + + public int getSpawnGoldTime() { + return spawnGoldTime; + } + + public int getSpawnGoldTimer() { + return spawnGoldTimer; + } + + public void setSpawnGoldTimer(int spawnGoldTimer) { + this.spawnGoldTimer = spawnGoldTimer; + } + + + public void setPlayerSpawnPoints(@NotNull List playerSpawnPoints) { + this.playerSpawnPoints = playerSpawnPoints; + } + + public void adjustContributorValue(Role role, User user, int number) { + user.adjustStatistic("CONTRIBUTION_" + role.name(), number); + } + + private Map murdererContributions = new HashMap<>(); + private Map detectiveContributions = new HashMap<>(); + + public Map getMurdererContributions() { + return murdererContributions; + } + + public Map getDetectiveContributions() { + return detectiveContributions; + } + + public int getContributorValue(Role role, User user) { + if(role == Role.MURDERER && murdererContributions.containsKey(user)) { + return murdererContributions.get(user); + } else if(detectiveContributions.containsKey(user)) { + return detectiveContributions.get(user); + } + Player player = user.getPlayer(); + int contributor = user.getStatistic("CONTRIBUTION_" + role.name()); + Bukkit.getConsoleSender().sendMessage(user.getPlayer().getName() + role.name() + "->C:" + contributor + user.getStatistic(plugin.getStatsStorage().getStatisticType("CONTRIBUTION_" + role.name()))); + int increase = plugin.getPermissionsManager().getPermissionCategoryValue(role.name() + "_BOOSTER", player); + int multiplicator = plugin.getPermissionsManager().getPermissionCategoryValue("CHANCES_BOOSTER", player); + int calculatedContributor = (contributor + increase) * (multiplicator == 0 ? 1 :multiplicator); + if(role == Role.MURDERER) { + murdererContributions.put(user, calculatedContributor); + } else { + detectiveContributions.put(user, calculatedContributor); + } + Bukkit.getConsoleSender().sendMessage(user.getPlayer().getName() + role.name() + "->" + calculatedContributor); + return calculatedContributor; + } + + public void resetContributorValue(Role role, User user) { + user.setStatistic("CONTRIBUTION_" + role.name(), 1); + } + + public enum CharacterType { + MURDERER, DETECTIVE, FAKE_DETECTIVE, HERO + } +} \ No newline at end of file diff --git a/src/main/java/plugily/projects/murdermystery/arena/ArenaEvents.java b/src/main/java/plugily/projects/murdermystery/arena/ArenaEvents.java index b4430b51..486de01b 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/ArenaEvents.java +++ b/src/main/java/plugily/projects/murdermystery/arena/ArenaEvents.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -23,18 +23,17 @@ import org.bukkit.Material; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Arrow; +import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; @@ -42,155 +41,110 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.spigotmc.event.entity.EntityDismountEvent; -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.compat.events.api.CBEntityPickupItemEvent; -import plugily.projects.commonsbox.minecraft.compat.events.api.CBPlayerPickupArrow; -import plugily.projects.commonsbox.minecraft.compat.xseries.XSound; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; -import plugily.projects.murdermystery.ConfigPreferences; +import plugily.projects.minigamesbox.classic.arena.ArenaState; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.PluginArenaEvents; +import plugily.projects.minigamesbox.classic.handlers.items.SpecialItem; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.handlers.language.TitleBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.misc.complement.ComplementAccessor; +import plugily.projects.minigamesbox.classic.utils.version.ServerVersion; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; +import plugily.projects.minigamesbox.classic.utils.version.events.api.PlugilyEntityPickupItemEvent; +import plugily.projects.minigamesbox.classic.utils.version.events.api.PlugilyPlayerPickupArrow; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XSound; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; +import plugily.projects.murdermystery.arena.managers.MapRestorerManager; import plugily.projects.murdermystery.arena.role.Role; import plugily.projects.murdermystery.arena.special.pray.PrayerRegistry; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.items.SpecialItem; -import plugily.projects.murdermystery.handlers.rewards.Reward; -import plugily.projects.murdermystery.user.User; import plugily.projects.murdermystery.utils.ItemPosition; -import plugily.projects.murdermystery.utils.Utils; /** * @author Plajer - *

- * Created at 13.03.2018 + *

Created at 13.03.2018 */ -public class ArenaEvents implements Listener { +public class ArenaEvents extends PluginArenaEvents { private final Main plugin; - private final ChatManager chatManager; public ArenaEvents(Main plugin) { + super(plugin); this.plugin = plugin; - chatManager = plugin.getChatManager(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } - @EventHandler - public void onArmorStandEject(EntityDismountEvent e) { - if(!(e.getEntity() instanceof ArmorStand) || !"MurderMysteryArmorStand".equals(e.getEntity().getCustomName())) { - return; - } - if(!(e.getDismounted() instanceof Player)) { + @Override + public void handleIngameVoidDeath(Player victim, PluginArena arena) { + Arena pluginArena = plugin.getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { return; } - if(e.getDismounted().isDead()) { - e.getEntity().remove(); + victim.damage(1000.0); + if(arena.getArenaState() == ArenaState.IN_GAME) { + VersionUtils.teleport(victim, pluginArena.getPlayerSpawnPoints().get(0)); } - //we could use setCancelled here but for 1.12 support we cannot (no api) - e.getDismounted().addPassenger(e.getEntity()); } @EventHandler - public void onEntityDamage(EntityDamageEvent e) { - if(!(e.getEntity() instanceof Player)) { - return; - } - Player victim = (Player) e.getEntity(); - Arena arena = ArenaRegistry.getArena(victim); - if(arena == null) { + public void onBowShot(EntityShootBowEvent event) { + if(event.getEntityType() != EntityType.PLAYER) { return; } - - switch (e.getCause()) { - case DROWNING: - e.setCancelled(true); - break; - case FALL: - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DISABLE_FALL_DAMAGE)) { - if(e.getDamage() >= 20.0) { - //kill the player for suicidal death, else do not - victim.damage(1000.0); - } - } - - e.setCancelled(true); - break; - case VOID: //kill the player and move to the spawn point - victim.damage(1000.0); - - if(arena.getArenaState() == ArenaState.WAITING_FOR_PLAYERS || arena.getArenaState() == ArenaState.STARTING) { - victim.teleport(arena.getLobbyLocation()); - } else { - victim.teleport(arena.getPlayerSpawnPoints().get(0)); - } - - break; - default: - break; - } - } - - @EventHandler - public void onBowShot(EntityShootBowEvent e) { - if(!(e.getEntity() instanceof Player)) { + Player player = (Player) event.getEntity(); + User user = plugin.getUserManager().getUser(player); + if(!Role.isRole(Role.ANY_DETECTIVE, user)) { return; } - Player player = (Player) e.getEntity(); - if(!Role.isRole(Role.ANY_DETECTIVE, player)) { + if(user.getCooldown("bow_shot") > 0) { + event.setCancelled(true); return; } - User user = plugin.getUserManager().getUser(player); - if(user.getCooldown("bow_shot") == 0) { - int bowCooldown = plugin.getConfig().getInt("Detective-Bow-Cooldown", 5); - - user.setCooldown("bow_shot", bowCooldown); - Utils.applyActionBarCooldown(player, bowCooldown); - VersionUtils.setDurability(e.getBow(), (short) 0); - } else { - e.setCancelled(true); - } + int bowCooldown = plugin.getConfig().getInt("Bow.Cooldown", 5); + user.setCooldown("bow_shot", bowCooldown); + plugin.getBukkitHelper().applyActionBarCooldown(player, bowCooldown); + VersionUtils.setMaterialCooldown(player, event.getBow().getType(), 20 * (plugin.getConfig().getInt("Bow.Cooldown", 5))); } @EventHandler - public void onArrowPickup(CBPlayerPickupArrow e) { - if(ArenaRegistry.isInArena(e.getPlayer())) { + public void onArrowPickup(PlugilyPlayerPickupArrow e) { + if(plugin.getArenaRegistry().isInArena(e.getPlayer())) { e.getItem().remove(); e.setCancelled(true); } } @EventHandler - public void onItemPickup(CBEntityPickupItemEvent e) { + public void onItemPickup(PlugilyEntityPickupItemEvent e) { if(!(e.getEntity() instanceof Player)) { return; } Player player = (Player) e.getEntity(); - Arena arena = ArenaRegistry.getArena(player); + Arena arena = plugin.getArenaRegistry().getArena(player); if(arena == null) { return; } + User user = plugin.getUserManager().getUser(player); e.setCancelled(true); - if(arena.getBowHologram() != null && e.getItem().equals(arena.getBowHologram().getEntityItem())) { - if(plugin.getUserManager().getUser(player).isSpectator()) { - return; - } - - if(Role.isRole(Role.INNOCENT, player)) { + if(arena.getBowHologram() != null + && e.getItem().equals(arena.getBowHologram().getEntityItem())) { + if(!user.isSpectator() && Role.isRole(Role.INNOCENT, user, arena)) { XSound.BLOCK_LAVA_POP.play(player.getLocation(), 1F, 2F); - arena.removeBowHolo(); + + ((MapRestorerManager) arena.getMapRestorerManager()).removeBowHolo(); e.getItem().remove(); for(Player loopPlayer : arena.getPlayersLeft()) { - if(Role.isRole(Role.INNOCENT, loopPlayer)) { - ItemPosition.setItem(loopPlayer, ItemPosition.BOW_LOCATOR, new ItemStack(Material.AIR, 1)); + User loopUser = plugin.getUserManager().getUser(loopPlayer); + if(Role.isRole(Role.INNOCENT, loopUser)) { + ItemPosition.setItem(loopUser, ItemPosition.BOW_LOCATOR, new ItemStack(Material.AIR, 1)); } } arena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, player); - ItemPosition.setItem(player, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); - ItemPosition.setItem(player, ItemPosition.INFINITE_ARROWS, new ItemStack(Material.ARROW, plugin.getConfig().getInt("Detective-Fake-Arrows", 3))); - chatManager.broadcast(arena, chatManager.colorMessage("In-Game.Messages.Bow-Messages.Pickup-Bow-Message", player)); + ItemPosition.setItem(user, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); + ItemPosition.setItem(user, ItemPosition.INFINITE_ARROWS, new ItemStack(Material.ARROW, plugin.getConfig().getInt("Bow.Amount.Arrows.Fake", 3))); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_BOW_PICKUP").asKey().player(player).arena(arena).sendArena(); } return; @@ -200,7 +154,6 @@ public void onItemPickup(CBEntityPickupItemEvent e) { return; } - User user = plugin.getUserManager().getUser(player); if(user.isSpectator() || arena.getArenaState() != ArenaState.IN_GAME) { return; } @@ -220,35 +173,48 @@ public void onItemPickup(CBEntityPickupItemEvent e) { stack.setAmount(3 * e.getItem().getItemStack().getAmount()); } - ItemPosition.addItem(player, ItemPosition.GOLD_INGOTS, stack); - user.addStat(StatsStorage.StatisticType.LOCAL_GOLD, stack.getAmount()); + ItemPosition.addItem(user, ItemPosition.GOLD_INGOTS, stack); + user.adjustStatistic("LOCAL_GOLD", stack.getAmount()); ArenaUtils.addScore(user, ArenaUtils.ScoreAction.GOLD_PICKUP, stack.getAmount()); - player.sendMessage(chatManager.colorMessage("In-Game.Messages.Picked-Up-Gold", player)); - plugin.getRewardsHandler().performReward(player, Reward.RewardType.GOLD_PICKUP); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_GOLD").asKey().player(player).arena(arena).sendPlayer(); + plugin.getRewardsHandler().performReward(player, plugin.getRewardsHandler().getRewardType("GOLD_PICKUP")); - if(Role.isRole(Role.ANY_DETECTIVE, player)) { - ItemPosition.addItem(player, ItemPosition.ARROWS, new ItemStack(Material.ARROW, e.getItem().getItemStack().getAmount() * plugin.getConfig().getInt("Detective-Gold-Pick-Up-Arrows", 3))); + if(Role.isRole(Role.ANY_DETECTIVE, user, arena)) { + ItemPosition.addItem(user, ItemPosition.ARROWS, new ItemStack(Material.ARROW, e.getItem().getItemStack().getAmount() * plugin.getConfig().getInt("Bow.Amount.Arrows.Detective", 3))); return; } - if(user.getStat(StatsStorage.StatisticType.LOCAL_GOLD) >= plugin.getConfig().getInt("Gold-For-Bow", 10)) { - user.setStat(StatsStorage.StatisticType.LOCAL_GOLD, 0); - VersionUtils.sendTitles(player, chatManager.colorMessage("In-Game.Messages.Bow-Messages.Bow-Shot-For-Gold", player), - chatManager.colorMessage("In-Game.Messages.Bow-Messages.Bow-Shot-Subtitle", player), 5, 40, 5); - ItemPosition.setItem(player, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); - ItemPosition.addItem(player, ItemPosition.ARROWS, new ItemStack(Material.ARROW, plugin.getConfig().getInt("Gold-Bow-Arrows", 3))); - player.getInventory().setItem(/* same for all roles */ ItemPosition.GOLD_INGOTS.getOtherRolesItemPosition(), new ItemStack(Material.GOLD_INGOT, 0)); + if(user.getStatistic("LOCAL_GOLD") >= plugin.getConfig().getInt("Gold.Amount.Bow", 10)) { + user.setStatistic("LOCAL_GOLD", 0); + new TitleBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_BOW_SHOT_TITLE") + .asKey() + .player(player) + .arena(arena) + .sendPlayer(); + ItemPosition.setItem(user, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); + ItemPosition.addItem( + user, + ItemPosition.ARROWS, + new ItemStack(Material.ARROW, plugin.getConfig().getInt("Bow.Amount.Arrows.Gold", 3))); + player + .getInventory() + .setItem( + /* same for all roles */ ItemPosition.GOLD_INGOTS.getOtherRolesItemPosition(), + new ItemStack(Material.GOLD_INGOT, 0)); } } + @EventHandler public void onMurdererDamage(EntityDamageByEntityEvent e) { - if(!(e.getDamager() instanceof Player) || !(e.getEntity() instanceof Player)) { + if(!(e.getDamager() instanceof Player) || e.getEntityType() != EntityType.PLAYER) { return; } Player attacker = (Player) e.getDamager(); + User userAttacker = plugin.getUserManager().getUser(attacker); Player victim = (Player) e.getEntity(); + User userVictim = plugin.getUserManager().getUser(victim); if(!ArenaUtils.areInSameArena(attacker, victim)) { return; } @@ -256,18 +222,19 @@ public void onMurdererDamage(EntityDamageByEntityEvent e) { e.setCancelled(true); //better check this for future even if anyone else cannot use sword - if(!Role.isRole(Role.MURDERER, attacker)) { + if(!Role.isRole(Role.MURDERER, userAttacker)) { return; } //check if victim is murderer - if(Role.isRole(Role.MURDERER, victim)) { + if(Role.isRole(Role.MURDERER, userVictim)) { + return; + } + if(VersionUtils.getItemInHand(attacker) == null || plugin.getSwordSkinManager().getMurdererSword(attacker) == null) { return; } - - //todo support for skins later //just don't kill user if item isn't murderer sword - if(VersionUtils.getItemInHand(attacker).getType() != plugin.getConfigPreferences().getMurdererSword().getType()) { + if(VersionUtils.getItemInHand(attacker).getType() != plugin.getSwordSkinManager().getMurdererSword(attacker).getType()) { return; } @@ -276,14 +243,14 @@ public void onMurdererDamage(EntityDamageByEntityEvent e) { if(plugin.getUserManager().getUser(attacker).getCooldown("sword_attack") > 0) { return; } - } else if(attacker.hasCooldown(plugin.getConfigPreferences().getMurdererSword().getType())) { + } else if(attacker.hasCooldown(plugin.getSwordSkinManager().getMurdererSword(attacker).getType())) { return; } - if(Role.isRole(Role.MURDERER, victim)) { - plugin.getRewardsHandler().performReward(attacker, Reward.RewardType.MURDERER_KILL); - } else if(Role.isRole(Role.ANY_DETECTIVE, victim)) { - plugin.getRewardsHandler().performReward(attacker, Reward.RewardType.DETECTIVE_KILL); + if(Role.isRole(Role.MURDERER, userVictim)) { + plugin.getRewardsHandler().performReward(attacker, plugin.getRewardsHandler().getRewardType("KILL_MURDERER")); + } else if(Role.isRole(Role.ANY_DETECTIVE, userVictim)) { + plugin.getRewardsHandler().performReward(attacker, plugin.getRewardsHandler().getRewardType("KILL_DETECTIVE")); } XSound.ENTITY_PLAYER_DEATH.play(victim.getLocation(), 50, 1); @@ -291,21 +258,22 @@ public void onMurdererDamage(EntityDamageByEntityEvent e) { User user = plugin.getUserManager().getUser(attacker); - user.addStat(StatsStorage.StatisticType.KILLS, 1); - user.addStat(StatsStorage.StatisticType.LOCAL_KILLS, 1); + user.adjustStatistic("KILLS", 1); + user.adjustStatistic("LOCAL_KILLS", 1); ArenaUtils.addScore(user, ArenaUtils.ScoreAction.KILL_PLAYER, 0); - Arena arena = ArenaRegistry.getArena(attacker); - if(Role.isRole(Role.ANY_DETECTIVE, victim) && arena.lastAliveDetective()) { + Arena arena = plugin.getArenaRegistry().getArena(attacker); + if(Role.isRole(Role.ANY_DETECTIVE, userVictim) && arena.lastAliveDetective()) { //if already true, no effect is done :) arena.setDetectiveDead(true); - if(Role.isRole(Role.FAKE_DETECTIVE, victim)) { + if(Role.isRole(Role.FAKE_DETECTIVE, userVictim)) { arena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, null); } ArenaUtils.dropBowAndAnnounce(arena, victim); } } + @EventHandler public void onArrowDamage(EntityDamageByEntityEvent e) { if(!(e.getDamager() instanceof Arrow)) { @@ -315,14 +283,16 @@ public void onArrowDamage(EntityDamageByEntityEvent e) { return; } Player attacker = (Player) ((Arrow) e.getDamager()).getShooter(); - if(ArenaRegistry.isInArena(attacker)) { + User userAttacker = plugin.getUserManager().getUser(attacker); + if(plugin.getArenaRegistry().isInArena(attacker)) { e.setCancelled(true); e.getDamager().remove(); } - if(!(e.getEntity() instanceof Player)) { + if(e.getEntityType() != EntityType.PLAYER) { return; } Player victim = (Player) e.getEntity(); + User userVictim = plugin.getUserManager().getUser(victim); if(!ArenaUtils.areInSameArena(attacker, victim)) { return; } @@ -332,47 +302,48 @@ public void onArrowDamage(EntityDamageByEntityEvent e) { return; } //dont kill murderer on bow damage if attacker is murderer - if(Role.isRole(Role.MURDERER, attacker) && Role.isRole(Role.MURDERER, victim)) { + if(Role.isRole(Role.MURDERER, userAttacker) && Role.isRole(Role.MURDERER, userVictim)) { e.setCancelled(true); return; } - Arena arena = ArenaRegistry.getArena(attacker); + Arena arena = plugin.getArenaRegistry().getArena(attacker); //we need to set it before the victim die, because of hero character - if(Role.isRole(Role.MURDERER, victim)) { + if(Role.isRole(Role.MURDERER, userVictim)) { arena.setCharacter(Arena.CharacterType.HERO, attacker); } XSound.ENTITY_PLAYER_DEATH.play(victim.getLocation(), 50, 1); victim.damage(100.0); - User user = plugin.getUserManager().getUser(attacker); - user.addStat(StatsStorage.StatisticType.KILLS, 1); - if(Role.isRole(Role.MURDERER, attacker)) { - user.addStat(StatsStorage.StatisticType.LOCAL_KILLS, 1); - ArenaUtils.addScore(user, ArenaUtils.ScoreAction.KILL_PLAYER, 0); + userAttacker.adjustStatistic("KILLS", 1); + if(Role.isRole(Role.MURDERER, userAttacker)) { + userAttacker.adjustStatistic("LOCAL_KILLS", 1); + arena.adjustContributorValue(Role.DETECTIVE, userAttacker, plugin.getRandom().nextInt(2)); + ArenaUtils.addScore(userAttacker, ArenaUtils.ScoreAction.KILL_PLAYER, 0); } - VersionUtils.sendTitles(victim, chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Titles.Died", victim), null, 5, 40, 50); + VersionUtils.sendTitles(victim, new MessageBuilder("IN_GAME_DEATH_SCREEN").asKey().build(), null, 5, 40, 50); - if(Role.isRole(Role.MURDERER, victim)) { - ArenaUtils.addScore(user, ArenaUtils.ScoreAction.KILL_MURDERER, 0); - } else if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.ENABLE_KILL_DETECTIVE_IF_INNOCENT_KILLED) && (Role.isRole(Role.ANY_DETECTIVE, victim) || Role.isRole(Role.INNOCENT, victim))) { - if(Role.isRole(Role.MURDERER, attacker)) { - VersionUtils.sendTitles(victim, null, chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Subtitles.Murderer-Killed-You", victim), 5, 40, 5); + if(Role.isRole(Role.MURDERER, userVictim)) { + ArenaUtils.addScore(userAttacker, ArenaUtils.ScoreAction.KILL_MURDERER, 0); + arena.adjustContributorValue(Role.MURDERER, userAttacker, plugin.getRandom().nextInt(2)); + } else if(plugin.getConfigPreferences().getOption("BOW_KILL_DETECTIVE") && (Role.isRole(Role.ANY_DETECTIVE, userVictim) || Role.isRole(Role.INNOCENT, userVictim))) { + if(Role.isRole(Role.MURDERER, userAttacker)) { + VersionUtils.sendTitles(victim, null, new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_MURDERER_KILLED_YOU").asKey().build(), 5, 40, 5); } else { - VersionUtils.sendTitles(victim, null, chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Subtitles.Player-Killed-You", victim), 5, 40, 5); + VersionUtils.sendTitles(victim, null, new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_INNOCENT_KILLED_YOU").asKey().build(), 5, 40, 5); } //if else, murderer killed, so don't kill him :) - if(Role.isRole(Role.ANY_DETECTIVE, attacker) || Role.isRole(Role.INNOCENT, attacker)) { - VersionUtils.sendTitles(attacker, chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Titles.Died", attacker), - chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Subtitles.Killed-Innocent", attacker), 5, 40, 5); + if(Role.isRole(Role.ANY_DETECTIVE, userAttacker) || Role.isRole(Role.INNOCENT, userAttacker)) { + VersionUtils.sendSubTitle(attacker, new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_INNOCENT_KILLED_WRONGLY").asKey().build(), 5, 40, 5); + attacker.damage(100.0); - ArenaUtils.addScore(user, ArenaUtils.ScoreAction.INNOCENT_KILL, 0); - plugin.getRewardsHandler().performReward(attacker, Reward.RewardType.DETECTIVE_KILL); - if(Role.isRole(Role.ANY_DETECTIVE, attacker) && arena.lastAliveDetective()) { + ArenaUtils.addScore(userAttacker, ArenaUtils.ScoreAction.INNOCENT_KILL, 0); + plugin.getRewardsHandler().performReward(attacker, plugin.getRewardsHandler().getRewardType("KILL_DETECTIVE")); + if(Role.isRole(Role.ANY_DETECTIVE, userAttacker) && arena.lastAliveDetective()) { arena.setDetectiveDead(true); - if(Role.isRole(Role.FAKE_DETECTIVE, attacker)) { + if(Role.isRole(Role.FAKE_DETECTIVE, userAttacker)) { arena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, null); } ArenaUtils.dropBowAndAnnounce(arena, victim); @@ -384,10 +355,11 @@ public void onArrowDamage(EntityDamageByEntityEvent e) { @EventHandler(priority = EventPriority.HIGH) public void onPlayerDie(PlayerDeathEvent e) { Player player = e.getEntity(); - Arena arena = ArenaRegistry.getArena(player); + Arena arena = plugin.getArenaRegistry().getArena(player); if(arena == null) { return; } + User user = plugin.getUserManager().getUser(player); ComplementAccessor.getComplement().setDeathMessage(e, ""); e.getDrops().clear(); e.setDroppedExp(0); @@ -399,58 +371,55 @@ public void onPlayerDie(PlayerDeathEvent e) { player.getInventory().clear(); player.setFlying(false); player.setAllowFlight(false); - plugin.getUserManager().getUser(player).setStat(StatsStorage.StatisticType.LOCAL_GOLD, 0); + user.setStatistic("LOCAL_GOLD", 0); return; } - if(Role.isRole(Role.MURDERER, player, arena) && arena.lastAliveMurderer()) { + if(Role.isRole(Role.MURDERER, user, arena) && arena.lastAliveMurderer()) { ArenaUtils.onMurdererDeath(arena); } - if(Role.isRole(Role.ANY_DETECTIVE, player) && arena.lastAliveDetective()) { + if(Role.isRole(Role.ANY_DETECTIVE, user) && arena.lastAliveDetective()) { arena.setDetectiveDead(true); - if(Role.isRole(Role.FAKE_DETECTIVE, player)) { + if(Role.isRole(Role.FAKE_DETECTIVE, user)) { arena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, null); } ArenaUtils.dropBowAndAnnounce(arena, player); } - User user = plugin.getUserManager().getUser(player); - user.addStat(StatsStorage.StatisticType.DEATHS, 1); + user.adjustStatistic("DEATHS", 1); user.setSpectator(true); VersionUtils.setCollidable(player, false); player.setGameMode(GameMode.SURVIVAL); - user.setStat(StatsStorage.StatisticType.LOCAL_GOLD, 0); + user.setStatistic("LOCAL_GOLD", 0); ArenaUtils.hidePlayer(player, arena); player.setAllowFlight(true); player.setFlying(true); player.getInventory().clear(); - chatManager.broadcastAction(arena, player, ChatManager.ActionType.DEATH); + if(plugin.getConfigPreferences().getOption("HIDE_DEATH")) { + new MessageBuilder(MessageBuilder.ActionType.DEATH).player(player).arena(arena).sendArena(); + } + if(arena.getArenaState() != ArenaState.ENDING && arena.getArenaState() != ArenaState.RESTARTING) { arena.addDeathPlayer(player); } //we must call it ticks later due to instant respawn bug Bukkit.getScheduler().runTaskLater(plugin, () -> { player.spigot().respawn(); - for(SpecialItem item : plugin.getSpecialItemManager().getSpecialItems()) { - if(item.getDisplayStage() != SpecialItem.DisplayStage.SPECTATOR) { - continue; - } - player.getInventory().setItem(item.getSlot(), item.getItemStack()); - } + plugin.getSpecialItemManager().addSpecialItemsOfStage(player, SpecialItem.DisplayStage.SPECTATOR); }, 5); } @EventHandler(priority = EventPriority.HIGHEST) - public void onRespawn(PlayerRespawnEvent e) { - Player player = e.getPlayer(); - Arena arena = ArenaRegistry.getArena(player); + public void onRespawn(PlayerRespawnEvent event) { + Player player = event.getPlayer(); + Arena arena = plugin.getArenaRegistry().getArena(player); if(arena == null) { return; } if(arena.getArenaState() == ArenaState.STARTING || arena.getArenaState() == ArenaState.WAITING_FOR_PLAYERS) { - e.setRespawnLocation(arena.getLobbyLocation()); + event.setRespawnLocation(arena.getLobbyLocation()); return; } if(arena.getArenaState() == ArenaState.ENDING || arena.getArenaState() == ArenaState.RESTARTING) { - e.setRespawnLocation(arena.getEndLocation()); + event.setRespawnLocation(arena.getEndLocation()); return; } if(arena.getPlayers().contains(player)) { @@ -458,9 +427,9 @@ public void onRespawn(PlayerRespawnEvent e) { org.bukkit.Location firstSpawn = arena.getPlayerSpawnPoints().get(0); if(player.getLocation().getWorld().equals(firstSpawn.getWorld())) { - e.setRespawnLocation(player.getLocation()); + event.setRespawnLocation(player.getLocation()); } else { - e.setRespawnLocation(firstSpawn); + event.setRespawnLocation(firstSpawn); } player.setAllowFlight(true); player.setFlying(true); @@ -469,72 +438,65 @@ public void onRespawn(PlayerRespawnEvent e) { VersionUtils.setCollidable(player, false); player.setGameMode(GameMode.SURVIVAL); player.removePotionEffect(PotionEffectType.NIGHT_VISION); - user.setStat(StatsStorage.StatisticType.LOCAL_GOLD, 0); - plugin.getRewardsHandler().performReward(player, Reward.RewardType.DEATH); + user.setStatistic("LOCAL_GOLD", 0); + plugin.getRewardsHandler().performReward(player, plugin.getRewardsHandler().getRewardType("PLAYER_DEATH")); } } - @EventHandler - public void onItemMove(InventoryClickEvent e) { - if(e.getWhoClicked() instanceof Player && ArenaRegistry.isInArena((Player) e.getWhoClicked())) { - if(e.getView().getType() == InventoryType.CRAFTING || e.getView().getType() == InventoryType.PLAYER) { - e.setResult(Event.Result.DENY); - } - } - } @EventHandler - public void playerCommandExecution(PlayerCommandPreprocessEvent e) { - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.ENABLE_SHORT_COMMANDS)) { - if(e.getMessage().equalsIgnoreCase("/start")) { - e.getPlayer().performCommand("mma forcestart"); - e.setCancelled(true); - return; - } - - if(e.getMessage().equalsIgnoreCase("/leave")) { - e.getPlayer().performCommand("mm leave"); - e.setCancelled(true); - } - } - } - - @EventHandler - public void locatorDistanceUpdate(PlayerMoveEvent e) { - Player player = e.getPlayer(); - Arena arena = ArenaRegistry.getArena(player); + public void locatorDistanceUpdate(PlayerMoveEvent event) { + Player player = event.getPlayer(); + Arena arena = plugin.getArenaRegistry().getArena(player); if(arena == null) { return; } + User user = plugin.getUserManager().getUser(player); //skip spectators - if(plugin.getUserManager().getUser(player).isSpectator()) { + if(user.isSpectator()) { return; } if(arena.getArenaState() == ArenaState.IN_GAME) { - if(Role.isRole(Role.INNOCENT, player, arena)) { + if(Role.isRole(Role.INNOCENT, user, arena)) { if(player.getInventory().getItem(ItemPosition.BOW_LOCATOR.getOtherRolesItemPosition()) != null) { ItemStack bowLocator = new ItemStack(Material.COMPASS, 1); ItemMeta bowMeta = bowLocator.getItemMeta(); - ComplementAccessor.getComplement().setDisplayName(bowMeta, chatManager.colorMessage("In-Game.Bow-Locator-Item-Name", player) + " §7| §a" + (int) Math.round(player.getLocation().distance(player.getCompassTarget()))); + ComplementAccessor.getComplement().setDisplayName(bowMeta, new MessageBuilder("IN_GAME_MESSAGES_ARENA_LOCATOR_BOW").asKey().player(player).arena(arena).build() + " §7| §a" + (int) Math.round(player.getLocation().distance(player.getCompassTarget()))); bowLocator.setItemMeta(bowMeta); - ItemPosition.setItem(player, ItemPosition.BOW_LOCATOR, bowLocator); + ItemPosition.setItem(user, ItemPosition.BOW_LOCATOR, bowLocator); return; } } - if(arena.isMurdererLocatorReceived() && Role.isRole(Role.MURDERER, player, arena) && arena.isMurderAlive(player)) { + if(arena.isMurdererLocatorReceived() && Role.isRole(Role.MURDERER, user, arena) && arena.isMurderAlive(player)) { ItemStack innocentLocator = new ItemStack(Material.COMPASS, 1); ItemMeta innocentMeta = innocentLocator.getItemMeta(); for(Player p : arena.getPlayersLeft()) { - Arena playerArena = ArenaRegistry.getArena(p); + Arena playerArena = plugin.getArenaRegistry().getArena(p); + User playerUser = plugin.getUserManager().getUser(p); - if(Role.isRole(Role.INNOCENT, p, playerArena) || Role.isRole(Role.ANY_DETECTIVE, p, playerArena)) { - ComplementAccessor.getComplement().setDisplayName(innocentMeta, chatManager.colorMessage("In-Game.Innocent-Locator-Item-Name", player) + " §7| §a" + (int) Math.round(player.getLocation().distance(p.getLocation()))); + if(Role.isRole(Role.INNOCENT, playerUser, playerArena) || Role.isRole(Role.ANY_DETECTIVE, playerUser, playerArena)) { + ComplementAccessor.getComplement().setDisplayName(innocentMeta, new MessageBuilder("IN_GAME_MESSAGES_ARENA_LOCATOR_INNOCENT").asKey().player(player).arena(arena).build() + " §7| §a" + (int) Math.round(player.getLocation().distance(p.getLocation()))); innocentLocator.setItemMeta(innocentMeta); - ItemPosition.setItem(player, ItemPosition.INNOCENTS_LOCATOR, innocentLocator); + ItemPosition.setItem(user, ItemPosition.INNOCENTS_LOCATOR, innocentLocator); } } } } } + @EventHandler + public void onDrop(PlayerDropItemEvent event) { + if(plugin.getArenaRegistry().getArena(event.getPlayer()) != null && plugin.getArenaRegistry().getArena(event.getPlayer()).getArenaState() == ArenaState.IN_GAME) { + event.setCancelled(true); + } + } + + @EventHandler + public void onItemMove(InventoryClickEvent event) { + if(event.getWhoClicked() instanceof Player && plugin.getArenaRegistry().isInArena((Player) event.getWhoClicked())) { + if(event.getView().getType() == InventoryType.CRAFTING || event.getView().getType() == InventoryType.PLAYER) { + event.setResult(Event.Result.DENY); + } + } + } } diff --git a/src/main/java/plugily/projects/murdermystery/arena/ArenaManager.java b/src/main/java/plugily/projects/murdermystery/arena/ArenaManager.java index 53761010..a27d8d02 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/ArenaManager.java +++ b/src/main/java/plugily/projects/murdermystery/arena/ArenaManager.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,38 +18,17 @@ package plugily.projects.murdermystery.arena; -import me.clip.placeholderapi.PlaceholderAPI; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Material; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; - -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.misc.MiscUtils; -import plugily.projects.commonsbox.minecraft.serialization.InventorySerializer; -import plugily.projects.murdermystery.ConfigPreferences; +import org.jetbrains.annotations.NotNull; +import plugily.projects.minigamesbox.classic.arena.ArenaState; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.PluginArenaManager; +import plugily.projects.minigamesbox.classic.handlers.language.TitleBuilder; +import plugily.projects.minigamesbox.classic.user.User; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.api.events.game.MMGameJoinAttemptEvent; -import plugily.projects.murdermystery.api.events.game.MMGameLeaveAttemptEvent; -import plugily.projects.murdermystery.api.events.game.MMGameStopEvent; +import plugily.projects.murdermystery.arena.managers.MapRestorerManager; import plugily.projects.murdermystery.arena.role.Role; import plugily.projects.murdermystery.arena.special.SpecialBlock; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.PermissionsManager; -import plugily.projects.murdermystery.handlers.items.SpecialItem; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.handlers.party.GameParty; -import plugily.projects.murdermystery.handlers.rewards.Reward; -import plugily.projects.murdermystery.user.User; -import plugily.projects.murdermystery.utils.Debugger; import plugily.projects.murdermystery.utils.ItemPosition; import java.util.ArrayList; @@ -58,489 +37,135 @@ /** * @author Plajer - *

- * Created at 13.05.2018 + *

Created at 13.05.2018 */ -public class ArenaManager { +public class ArenaManager extends PluginArenaManager { - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private static final ChatManager chatManager = plugin.getChatManager(); + private final Main plugin; - private ArenaManager() { + public ArenaManager(Main plugin) { + super(plugin); + this.plugin = plugin; } - /** - * Attempts player to join arena. - * Calls MMGameJoinAttemptEvent. - * Can be cancelled only via above-mentioned event - * - * @param player player to join - * @see MMGameJoinAttemptEvent - */ - public static void joinAttempt(Player player, Arena arena) { - Debugger.debug("[{0}] Initial join attempt for {1}", arena.getId(), player.getName()); - long start = System.currentTimeMillis(); - MMGameJoinAttemptEvent gameJoinAttemptEvent = new MMGameJoinAttemptEvent(player, arena); - Bukkit.getPluginManager().callEvent(gameJoinAttemptEvent); - - if(!arena.isReady()) { - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Arena-Not-Configured")); - return; - } - if(gameJoinAttemptEvent.isCancelled()) { - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Join-Cancelled-Via-API")); + @Override + public void joinAttempt(@NotNull Player player, @NotNull PluginArena arena) { + Arena pluginArena = (Arena) plugin.getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { return; } - if(ArenaRegistry.isInArena(player)) { - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Already-Playing")); - return; - } - - //check if player is in party and send party members to the game - if(plugin.getPartyHandler().isPlayerInParty(player)) { - Debugger.debug("{0} is in a party", player.getName()); - GameParty party = plugin.getPartyHandler().getParty(player); - if(party.getLeader().equals(player)) { - Debugger.debug("{0} is partyleader", player.getName()); - if(arena.getMaximumPlayers() - arena.getPlayers().size() >= party.getPlayers().size()) { - for(Player partyPlayer : party.getPlayers()) { - if(player.equals(partyPlayer)) { - continue; - } - Arena partyArena = ArenaRegistry.getArena(partyPlayer); - if(partyArena != null) { - if(partyArena.getArenaState() == ArenaState.IN_GAME) { - continue; - } - Debugger.debug("[Partyleader: {0}] Found party member {1} on other arena", player.getName(), partyPlayer.getName()); - leaveAttempt(partyPlayer, partyArena); - } - partyPlayer.sendMessage(chatManager.getPrefix() + chatManager.formatMessage(arena, chatManager.colorMessage("In-Game.Join-As-Party-Member"), partyPlayer)); - Debugger.debug("Let party member {0} join the arena of {1}", partyPlayer.getName(), player.getName()); - joinAttempt(partyPlayer, arena); - } - } else { - Debugger.debug("[Partyleader: {0}] The arena got not enough space for the party", player.getName()); - player.sendMessage(chatManager.getPrefix() + chatManager.formatMessage(arena, chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Not-Enough-Space-For-Party"), player)); - return; - } - } - } - - if(!(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED) - || player.hasPermission(PermissionsManager.getJoinPerm().replace("", "*")) - || player.hasPermission(PermissionsManager.getJoinPerm().replace("", arena.getId())))) { - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Join-No-Permission").replace("%permission%", - PermissionsManager.getJoinPerm().replace("", arena.getId()))); - return; - } - if(arena.getArenaState() == ArenaState.RESTARTING) { - return; - } - if(arena.getArenaState() == ArenaState.STARTING && arena.getPlayers().size() >= arena.getMaximumPlayers()) { - if(!player.hasPermission(PermissionsManager.getJoinFullGames())) { - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Full-Game-No-Permission")); - return; - } - boolean foundSlot = false; - for(Player loopPlayer : arena.getPlayers()) { - if(loopPlayer.hasPermission(PermissionsManager.getJoinFullGames())) { - continue; - } - leaveAttempt(loopPlayer, arena); - loopPlayer.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Lobby-Messages.You-Were-Kicked-For-Premium-Slot")); - chatManager.broadcast(arena, chatManager.formatMessage(arena, chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Kicked-For-Premium-Slot"), loopPlayer)); - foundSlot = true; - break; - } - if(!foundSlot) { - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.No-Slots-For-Premium")); - return; - } - } - - Debugger.debug("[{0}] Checked join attempt for {1} initialized", arena.getId(), player.getName()); - - User user = plugin.getUserManager().getUser(player); - user.lastBoard = player.getScoreboard(); - - //reset scoreboard - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - - arena.getScoreboardManager().createScoreboard(user); - - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.INVENTORY_MANAGER_ENABLED)) { - InventorySerializer.saveInventoryToFile(plugin, player); - } - - int murderIncrease = player.getEffectivePermissions().stream().filter(permAttach -> permAttach.getPermission().startsWith("murdermystery.role.murderer.")) - .mapToInt(pai -> Integer.parseInt(pai.getPermission().substring(28 /* remove the permission node to obtain the number*/))).max().orElse(0); - int detectiveIncrease = player.getEffectivePermissions().stream().filter(permAttach -> permAttach.getPermission().startsWith("murdermystery.role.detective.")) - .mapToInt(pai -> Integer.parseInt(pai.getPermission().substring(29 /* remove the permission node to obtain the number*/))).max().orElse(0); - user.addStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, murderIncrease); - user.addStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, detectiveIncrease); - - arena.addPlayer(player); - player.setLevel(0); - player.setExp(1); - player.setHealth(VersionUtils.getMaxHealth(player)); - player.setFoodLevel(20); - if((arena.getArenaState() == ArenaState.IN_GAME || arena.getArenaState() == ArenaState.ENDING)) { - arena.teleportToStartLocation(player); - player.sendMessage(chatManager.colorMessage("In-Game.You-Are-Spectator")); - player.getInventory().clear(); - - for(SpecialItem item : plugin.getSpecialItemManager().getSpecialItems()) { - if(item.getDisplayStage() != SpecialItem.DisplayStage.SPECTATOR) { - continue; - } - player.getInventory().setItem(item.getSlot(), item.getItemStack()); - } - - player.getActivePotionEffects().forEach(potionEffect -> player.removePotionEffect(potionEffect.getType())); - player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0)); - ArenaUtils.hidePlayer(player, arena); - - user.setSpectator(true); - - arena.addSpectatorPlayer(player); - VersionUtils.setCollidable(player, false); - player.setGameMode(GameMode.SURVIVAL); - player.setAllowFlight(true); - player.setFlying(true); - - for(Player spectator : arena.getPlayers()) { - if(!plugin.getUserManager().getUser(spectator).isSpectator()) { - VersionUtils.hidePlayer(plugin, /*not spectator*/ spectator, /*joined spectator*/ player); - } - VersionUtils.showPlayer(plugin, player, spectator); - } - ArenaUtils.hidePlayersOutsideTheGame(player, arena); - Debugger.debug("[{0}] Join attempt as spectator finished for {1} took {2}ms", arena.getId(), player.getName(), System.currentTimeMillis() - start); - return; - } - arena.teleportToLobby(player); - player.getInventory().setArmorContents(new ItemStack[]{new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR)}); - player.setFlying(false); - player.setAllowFlight(false); - player.getInventory().clear(); - arena.doBarAction(Arena.BarAction.ADD, player); - if(!user.isSpectator()) { - chatManager.broadcastAction(arena, player, ChatManager.ActionType.JOIN); - } - if(arena.getArenaState() == ArenaState.STARTING || arena.getArenaState() == ArenaState.WAITING_FOR_PLAYERS) { - for(SpecialItem item : plugin.getSpecialItemManager().getSpecialItems()) { - if(item.getDisplayStage() != SpecialItem.DisplayStage.LOBBY) { - continue; - } - player.getInventory().setItem(item.getSlot(), item.getItemStack()); - } - } - player.updateInventory(); - for(Player arenaPlayer : arena.getPlayers()) { - ArenaUtils.showPlayer(arenaPlayer, arena); - } - arena.showPlayers(); + super.joinAttempt(player, arena); ArenaUtils.updateNameTagsVisibility(player); - plugin.getSignManager().updateSigns(); - Debugger.debug("[{0}] Join attempt as player for {1} took {2}ms", arena.getId(), player.getName(), System.currentTimeMillis() - start); } - /** - * Attempts player to leave arena. - * Calls MMGameLeaveAttemptEvent event. - * - * @param player player to join - * @see MMGameLeaveAttemptEvent - */ - public static void leaveAttempt(Player player, Arena arena) { - Debugger.debug("[{0}] Initial leave attempt for {1}", arena.getId(), player.getName()); - long start = System.currentTimeMillis(); - - Bukkit.getPluginManager().callEvent(new MMGameLeaveAttemptEvent(player, arena)); - User user = plugin.getUserManager().getUser(player); - - int localScore = user.getStat(StatsStorage.StatisticType.LOCAL_SCORE); - if(localScore > user.getStat(StatsStorage.StatisticType.HIGHEST_SCORE)) { - user.setStat(StatsStorage.StatisticType.HIGHEST_SCORE, localScore); - } - - //todo change later - int murderDecrease = player.getEffectivePermissions().stream().filter(permAttach -> permAttach.getPermission().startsWith("murdermystery.role.murderer.")) - .mapToInt(pai -> Integer.parseInt(pai.getPermission().substring(28 /* remove the permission node to obtain the number*/))).max().orElse(0); - int detectiveDecrease = player.getEffectivePermissions().stream().filter(permAttach -> permAttach.getPermission().startsWith("murdermystery.role.detective.")) - .mapToInt(pai -> Integer.parseInt(pai.getPermission().substring(29 /* remove the permission node to obtain the number*/))).max().orElse(0); - user.addStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, -murderDecrease); - if(user.getStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER) <= 0) { - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, 1); + @Override + public void leaveAttempt(@NotNull Player player, @NotNull PluginArena arena) { + Arena pluginArena = (Arena) plugin.getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return; } - user.addStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, -detectiveDecrease); - if(user.getStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE) <= 0) { - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, 1); + super.leaveAttempt(player, arena); + if(pluginArena.isDeathPlayer(player)) { + pluginArena.removeDeathPlayer(player); } + User user = plugin.getUserManager().getUser(player); - if(arena.getArenaState() == ArenaState.IN_GAME) { - if(Role.isRole(Role.FAKE_DETECTIVE, player, arena) || Role.isRole(Role.INNOCENT, player, arena)) { - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, ThreadLocalRandom.current().nextInt(4) + 1); - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, ThreadLocalRandom.current().nextInt(4) + 1); - } + int localScore = user.getStatistic("LOCAL_SCORE"); + if(localScore > user.getStatistic("HIGHEST_SCORE")) { + user.setStatistic("HIGHEST_SCORE", localScore); } - user.removeScoreboard(arena); - - boolean playerHasMurdererRole = Role.isRole(Role.MURDERER, player, arena); + boolean playerHasMurdererRole = Role.isRole(Role.MURDERER, user, arena); if(playerHasMurdererRole) { - arena.removeFromMurdererList(player); + pluginArena.removeFromMurdererList(player); } + if(arena.getArenaState() == ArenaState.IN_GAME && !user.isSpectator()) { List playersLeft = arena.getPlayersLeft(); - //-1 cause we didn't remove player yet + // -1 cause we didn't remove player yet if(playersLeft.size() - 1 > 1) { if(playerHasMurdererRole) { - if(arena.getMurdererList().isEmpty()) { + if(pluginArena.getMurdererList().isEmpty()) { List players = new ArrayList<>(); for(Player gamePlayer : playersLeft) { - if(gamePlayer == player || Role.isRole(Role.ANY_DETECTIVE, gamePlayer, arena) || Role.isRole(Role.MURDERER, gamePlayer, arena)) { + User userGamePlayer = plugin.getUserManager().getUser(gamePlayer); + if(gamePlayer == player || Role.isRole(Role.ANY_DETECTIVE, userGamePlayer, arena) || Role.isRole(Role.MURDERER, userGamePlayer, arena)) { continue; } players.add(gamePlayer); } Player newMurderer = players.get(players.size() == 1 ? 0 : ThreadLocalRandom.current().nextInt(players.size())); - if (newMurderer != null) { - Debugger.debug("A murderer left the game. New murderer: {0}", newMurderer.getName()); - arena.setCharacter(Arena.CharacterType.MURDERER, newMurderer); - arena.addToMurdererList(newMurderer); - } - - String title = chatManager.colorMessage("In-Game.Messages.Previous-Role-Left-Title", player).replace("%role%", - chatManager.colorMessage("Scoreboard.Roles.Murderer", player)); - String subtitle = chatManager.colorMessage("In-Game.Messages.Previous-Role-Left-Subtitle", player).replace("%role%", - chatManager.colorMessage("Scoreboard.Roles.Murderer", player)); - - for(Player gamePlayer : arena.getPlayers()) { - VersionUtils.sendTitles(gamePlayer, title, subtitle, 5, 40, 5); + if(newMurderer != null) { + plugin.getDebugger().debug("A murderer left the game. New murderer: {0}", newMurderer.getName()); + pluginArena.setCharacter(Arena.CharacterType.MURDERER, newMurderer); + pluginArena.addToMurdererList(newMurderer); } - if (newMurderer != null) { - VersionUtils.sendTitles(newMurderer, chatManager.colorMessage("In-Game.Messages.Role-Set.Murderer-Title", player), - chatManager.colorMessage("In-Game.Messages.Role-Set.Murderer-Subtitle", player), 5, 40, 5); - ItemPosition.setItem(newMurderer, ItemPosition.MURDERER_SWORD, plugin.getConfigPreferences().getMurdererSword()); + new TitleBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_CHANGE").asKey().player(player).arena(pluginArena).sendArena(); + if(newMurderer != null) { + new TitleBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_MURDERER").asKey().player(player).arena(pluginArena).sendArena(); + ItemPosition.setItem(plugin.getUserManager().getUser(newMurderer), ItemPosition.MURDERER_SWORD, plugin.getSwordSkinManager().getRandomSwordSkin(player)); } - - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, 1); } else { - Debugger.debug("No new murderer added as there are some"); + plugin.getDebugger().debug("No new murderer added as there are some"); } - } else if(Role.isRole(Role.ANY_DETECTIVE, player, arena) && arena.lastAliveDetective()) { - arena.setDetectiveDead(true); - if(Role.isRole(Role.FAKE_DETECTIVE, player, arena)) { - arena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, null); - } else { - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, 1); + } else if(Role.isRole(Role.ANY_DETECTIVE, user, arena) + && pluginArena.lastAliveDetective()) { + pluginArena.setDetectiveDead(true); + if(Role.isRole(Role.FAKE_DETECTIVE, user, arena)) { + pluginArena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, null); } - ArenaUtils.dropBowAndAnnounce(arena, player); + ArenaUtils.dropBowAndAnnounce(pluginArena, player); } - plugin.getCorpseHandler().spawnCorpse(player, arena); + plugin.getCorpseHandler().spawnCorpse(player, pluginArena); } else { stopGame(false, arena); } } - //the default fly speed - player.setFlySpeed(0.1f); - player.getInventory().clear(); - player.getInventory().setArmorContents(null); - arena.removePlayer(player); - - if(!user.isSpectator() && !arena.isSpectatorPlayer(player)) { - chatManager.broadcastAction(arena, player, ChatManager.ActionType.LEAVE); - } - - VersionUtils.setGlowing(player, false); - user.setSpectator(false); - - arena.removeDeathPlayer(player); - arena.removeSpectatorPlayer(player); - - VersionUtils.setCollidable(player, true); - user.removeScoreboard(arena); - arena.doBarAction(Arena.BarAction.REMOVE, player); - player.setHealth(VersionUtils.getMaxHealth(player)); - player.setFoodLevel(20); - player.setLevel(0); - player.setExp(0); - player.setFlying(false); - player.setAllowFlight(false); - player.getActivePotionEffects().forEach(effect -> player.removePotionEffect(effect.getType())); - player.setWalkSpeed(0.2f); - player.setFireTicks(0); - if(arena.getArenaState() != ArenaState.WAITING_FOR_PLAYERS && arena.getArenaState() != ArenaState.STARTING && arena.getPlayers().isEmpty()) { - arena.setArenaState(ArenaState.ENDING); - arena.setTimer(0); - } - - player.setGameMode(GameMode.SURVIVAL); - for(Player players : plugin.getServer().getOnlinePlayers()) { - if(!ArenaRegistry.isInArena(players)) { - VersionUtils.showPlayer(plugin, players, player); - } - VersionUtils.showPlayer(plugin, player, players); - } - arena.teleportToEndLocation(player); - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED) - && plugin.getConfigPreferences().getOption(ConfigPreferences.Option.INVENTORY_MANAGER_ENABLED)) { - InventorySerializer.loadInventory(plugin, player); - } - plugin.getUserManager().saveAllStatistic(user); - plugin.getSignManager().updateSigns(); - Debugger.debug("[{0}] Game leave finished for {1} took{2}ms ", arena.getId(), player.getName(), System.currentTimeMillis() - start); } - /** - * Stops current arena. Calls MMGameStopEvent event - * - * @param quickStop should arena be stopped immediately? (use only in important cases) - * @see MMGameStopEvent - */ - public static void stopGame(boolean quickStop, Arena arena) { - Debugger.debug("[{0}] Stop game event initialized with quickStop {1}", arena.getId(), quickStop); - long start = System.currentTimeMillis(); - - Bukkit.getPluginManager().callEvent(new MMGameStopEvent(arena)); - arena.setArenaState(ArenaState.ENDING); - if(quickStop) { - arena.setTimer(2); - chatManager.broadcast(arena, chatManager.colorRawMessage("&cThe game has been force stopped by command")); - } else { - arena.setTimer(10); + @Override + public void stopGame(boolean quickStop, @NotNull PluginArena arena) { + Arena pluginArena = (Arena) plugin.getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return; } - - for(SpecialBlock specialBlock : arena.getSpecialBlocks()) { + for(SpecialBlock specialBlock : pluginArena.getSpecialBlocks()) { if(specialBlock.getArmorStandHologram() != null) { specialBlock.getArmorStandHologram().delete(); } } - - arena.removeBowHolo(); - - List summaryMessages = LanguageManager.getLanguageList("In-Game.Messages.Game-End-Messages.Summary-Message"); - arena.getScoreboardManager().stopAllScoreboards(); - - boolean murderWon = arena.getPlayersLeft().size() == arena.aliveMurderer(); - - for(final Player player : arena.getPlayers()) { - User user = plugin.getUserManager().getUser(player); - - if(!quickStop && Role.isAnyRole(player, arena)) { - boolean hasDeathRole = Role.isRole(Role.DEATH, player, arena); - - if(!hasDeathRole && !Role.isRole(Role.SPECTATOR, player, arena)) { - if(Role.isRole(Role.FAKE_DETECTIVE, player, arena) || Role.isRole(Role.INNOCENT, player, arena)) { - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, ThreadLocalRandom.current().nextInt(4) + 1); - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, ThreadLocalRandom.current().nextInt(4) + 1); - } - - boolean hasMurdererRole = Role.isRole(Role.MURDERER, player, arena); - - if((murderWon && hasMurdererRole) || !hasMurdererRole) { - user.addStat(StatsStorage.StatisticType.WINS, 1); - plugin.getRewardsHandler().performReward(player, Reward.RewardType.WIN); - } else { - user.addStat(StatsStorage.StatisticType.LOSES, 1); - plugin.getRewardsHandler().performReward(player, Reward.RewardType.LOSE); - } - } else if(hasDeathRole) { - user.addStat(StatsStorage.StatisticType.LOSES, 1); - plugin.getRewardsHandler().performReward(player, Reward.RewardType.LOSE); - } - } - //the default walk & fly speed - player.setFlySpeed(0.1f); - player.setWalkSpeed(0.2f); - - player.getInventory().clear(); - for(SpecialItem item : plugin.getSpecialItemManager().getSpecialItems()) { - if(item.getDisplayStage() != SpecialItem.DisplayStage.SPECTATOR) { - continue; - } - player.getInventory().setItem(item.getSlot(), item.getItemStack()); - } + ((MapRestorerManager) pluginArena.getMapRestorerManager()).removeBowHolo(); + boolean murderWon = arena.getPlayersLeft().size() == pluginArena.aliveMurderer(); + for(Player player : arena.getPlayers()) { if(!quickStop) { - for(String msg : summaryMessages) { - MiscUtils.sendCenteredMessage(player, formatSummaryPlaceholders(msg, arena, player)); - } - } - user.removeScoreboard(arena); - if(!quickStop && !user.isSpectator() && !user.isPermanentSpectator() && plugin.getConfig().getBoolean("Firework-When-Game-Ends", true)) { - new BukkitRunnable() { - int i = 0; - - @Override - public void run() { - if(i >= 4 || !arena.getPlayers().contains(player)) { - cancel(); + User user = plugin.getUserManager().getUser(player); + if(!quickStop && Role.isAnyRole(user, arena)) { + boolean hasDeathRole = Role.isRole(Role.DEATH, user, arena); + int multiplicator = 1; + if(!hasDeathRole) { + multiplicator = arena.getMaximumPlayers(); + } + pluginArena.adjustContributorValue(Role.MURDERER, user, plugin.getRandom().nextInt(10 * multiplicator)); + pluginArena.adjustContributorValue(Role.DETECTIVE, user, plugin.getRandom().nextInt(10 * multiplicator)); + if(!hasDeathRole && !Role.isRole(Role.SPECTATOR, user, arena)) { + boolean hasMurdererRole = Role.isRole(Role.MURDERER, user, arena); + if(murderWon || !hasMurdererRole) { + user.adjustStatistic("WINS", 1); + plugin.getRewardsHandler().performReward(player, plugin.getRewardsHandler().getRewardType("WIN")); + } else { + user.adjustStatistic("LOSES", 1); + plugin.getRewardsHandler().performReward(player, plugin.getRewardsHandler().getRewardType("LOSE")); } - MiscUtils.spawnRandomFirework(player.getLocation()); - i++; + } else if(hasDeathRole) { + user.adjustStatistic("LOSES", 1); + plugin.getRewardsHandler().performReward(player, plugin.getRewardsHandler().getRewardType("LOSE")); } - }.runTaskTimer(plugin, 30, 30); - } - } - Debugger.debug("[{0}] Stop game event finished took{1}ms ", arena.getId(), System.currentTimeMillis() - start); - } - - private static String formatSummaryPlaceholders(String msg, Arena arena, Player player) { - String formatted = msg; - - StringBuilder murders = new StringBuilder(), detectives = new StringBuilder(); - int murdererKills = 0; - for(Player p : arena.getMurdererList()) { - User user = plugin.getUserManager().getUser(p); - int localKills = user.getStat(StatsStorage.StatisticType.LOCAL_KILLS); - - murders.append(p.getName()); - - if(arena.getMurdererList().size() > 1) { - murders.append(" (").append(localKills).append("), "); + } } - - murdererKills += localKills; } - if(arena.getMurdererList().size() > 1) { - murders.deleteCharAt(murders.length() - 2); - } - for(Player p : arena.getDetectiveList()) { - detectives.append(p.getName()).append(", "); - } - - int index = detectives.length() - 2; - if (index > 0 && index < detectives.length()) { - detectives.deleteCharAt(index); - } - - int aliveMurderer = arena.aliveMurderer(); - - if(arena.getPlayersLeft().size() == aliveMurderer) { - formatted = StringUtils.replace(formatted, "%winner%", chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Winners.Murderer")); - } else { - formatted = StringUtils.replace(formatted, "%winner%", chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Winners.Players")); - } - - formatted = StringUtils.replace(formatted, "%detective%", (arena.isDetectiveDead() ? ChatColor.STRIKETHROUGH : "") + detectives.toString()); - - formatted = StringUtils.replace(formatted, "%murderer%", (aliveMurderer == 1 ? "" : ChatColor.STRIKETHROUGH) + murders.toString()); - - formatted = StringUtils.replace(formatted, "%murderer_kills%", Integer.toString(murdererKills)); - - Player hero = arena.getCharacter(Arena.CharacterType.HERO); - formatted = StringUtils.replace(formatted, "%hero%", hero != null ? hero.getName() : chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Winners.Nobody")); - - if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) { - formatted = PlaceholderAPI.setPlaceholders(player, formatted); - } - - return formatted; + super.stopGame(quickStop, arena); } - } diff --git a/src/main/java/plugily/projects/murdermystery/arena/ArenaRegistry.java b/src/main/java/plugily/projects/murdermystery/arena/ArenaRegistry.java index 254ca3b8..47e0e097 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/ArenaRegistry.java +++ b/src/main/java/plugily/projects/murdermystery/arena/ArenaRegistry.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,191 +19,110 @@ package plugily.projects.murdermystery.arena; import org.bukkit.Location; +import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.PluginArenaRegistry; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.utils.serialization.LocationSerializer; import plugily.projects.murdermystery.Main; import plugily.projects.murdermystery.arena.special.SpecialBlock; -import plugily.projects.murdermystery.utils.Debugger; import java.util.ArrayList; import java.util.List; -import java.util.Random; /** * Created by Tom on 27/07/2014. */ -public class ArenaRegistry { - - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private static final List arenas = new ArrayList<>(); - private static int bungeeArena = -999; - - /** - * Checks if player is in any arena - * - * @param player player to check - * @return [b]true[/b] when player is in arena, [b]false[/b] if otherwise - */ - public static boolean isInArena(Player player) { - return getArena(player) != null; - } - - /** - * Returns arena where the player is - * - * @param p target player - * @return Arena or null if not playing - * @see #isInArena(Player) to check if player is playing - */ - public static Arena getArena(Player p) { - if(p == null) { - return null; - } - for(Arena arena : arenas) { - for(Player player : arena.getPlayers()) { - if(player.getUniqueId().equals(p.getUniqueId())) { - return arena; - } - } - } - return null; - } +public class ArenaRegistry extends PluginArenaRegistry { - /** - * Returns arena based by ID - * - * @param id name of arena - * @return Arena or null if not found - */ - public static Arena getArena(String id) { - for(Arena loopArena : arenas) { - if(loopArena.getId().equalsIgnoreCase(id)) { - return loopArena; - } - } - return null; - } + private final Main plugin; - public static int getArenaPlayersOnline() { - int players = 0; - for(Arena arena : arenas) { - players += arena.getPlayers().size(); - } - return players; + public ArenaRegistry(Main plugin) { + super(plugin); + this.plugin = plugin; } - public static void registerArena(Arena arena) { - Debugger.debug("Registering new game instance {0}", arena.getId()); - arenas.add(arena); - } - public static void unregisterArena(Arena arena) { - Debugger.debug("Unegistering game instance {0}", arena.getId()); - arenas.remove(arena); + @Override + public PluginArena getNewArena(String id) { + return new Arena(id); } - public static void registerArenas() { - Debugger.debug("Initial arenas registration"); - long start = System.currentTimeMillis(); - - if(!arenas.isEmpty()) { - for(Arena arena : new ArrayList<>(arenas)) { - arena.cleanUpArena(); - unregisterArena(arena); - } - } + @Override + public boolean additionalValidatorChecks(ConfigurationSection section, PluginArena arena, String id) { + boolean checks = super.additionalValidatorChecks(section, arena, id); + if(!checks) return false; - org.bukkit.configuration.file.FileConfiguration config = ConfigUtils.getConfig(plugin, "arenas"); - org.bukkit.configuration.ConfigurationSection section = config.getConfigurationSection("instances"); - if(section == null) { - Debugger.sendConsoleMsg(plugin.getChatManager().colorMessage("Validator.No-Instances-Created")); - return; + if(!section.getBoolean(id + ".isdone")) { + plugin.getDebugger().sendConsoleMsg(new MessageBuilder("VALIDATOR_INVALID_ARENA_CONFIGURATION").asKey().value("NOT VALIDATED").arena(arena).build()); + return false; } - for(String id : section.getKeys(false)) { - if(id.equalsIgnoreCase("default")) { - continue; - } - - Arena arena = new Arena(id); - - List playerSpawnPoints = new ArrayList<>(); - for(String loc : section.getStringList(id + ".playerspawnpoints")) { - org.bukkit.Location serialized = LocationSerializer.getLocation(loc); + List playerSpawnPoints = new ArrayList<>(); + for(String loc : section.getStringList(id + ".playerspawnpoints")) { + org.bukkit.Location serialized = LocationSerializer.getLocation(loc); - // Ignore the arena if world is not exist at least in spawn points - if(serialized == null || serialized.getWorld() == null) { - section.set(id + ".isdone", false); - } else { - playerSpawnPoints.add(serialized); - } - } - - arena.setPlayerSpawnPoints(playerSpawnPoints); - arena.setMinimumPlayers(section.getInt(id + ".minimumplayers", 2)); - arena.setMaximumPlayers(section.getInt(id + ".maximumplayers", 4)); - arena.setMapName(section.getString(id + ".mapname", "none")); - arena.setSpawnGoldTime(section.getInt(id + ".spawngoldtime", 5)); - arena.setHideChances(section.getBoolean(id + ".hidechances")); - arena.setMurderers(section.getInt(id + ".playerpermurderer", 5)); - arena.setDetectives(section.getInt(id + ".playerperdetective", 7)); - arena.setGoldVisuals(section.getBoolean(id + ".goldvisuals")); - - Location endLoc = LocationSerializer.getLocation(section.getString(id + ".Endlocation", "world,364.0,63.0,-72.0,0.0,0.0")); - Location lobbyLoc = LocationSerializer.getLocation(section.getString(id + ".lobbylocation", "world,364.0,63.0,-72.0,0.0,0.0")); - if(lobbyLoc == null || lobbyLoc.getWorld() == null || endLoc == null || endLoc.getWorld() == null) { + // Ignore the arena if world is not exist at least in spawn points + if(serialized == null || serialized.getWorld() == null) { section.set(id + ".isdone", false); } else { - arena.setLobbyLocation(lobbyLoc); - arena.setEndLocation(endLoc); - } - - if(!section.getBoolean(id + ".isdone")) { - Debugger.sendConsoleMsg(plugin.getChatManager().colorMessage("Validator.Invalid-Arena-Configuration").replace("%arena%", id).replace("%error%", "NOT VALIDATED")); - arena.setReady(false); - registerArena(arena); - continue; - } - - List goldSpawnPoints = new ArrayList<>(); - for(String loc : section.getStringList(id + ".goldspawnpoints")) { - goldSpawnPoints.add(LocationSerializer.getLocation(loc)); + playerSpawnPoints.add(serialized); } - arena.setGoldSpawnPoints(goldSpawnPoints); + } - List specialBlocks = new ArrayList<>(); - for(String loc : section.getStringList(id + ".mystery-cauldrons")) { - specialBlocks.add(new SpecialBlock(LocationSerializer.getLocation(loc), SpecialBlock.SpecialBlockType.MYSTERY_CAULDRON)); - } - for(String loc : section.getStringList(id + ".confessionals")) { - specialBlocks.add(new SpecialBlock(LocationSerializer.getLocation(loc), SpecialBlock.SpecialBlockType.PRAISE_DEVELOPER)); - } + ((Arena) arena).setSpawnGoldTime(section.getInt(id + ".spawngoldtime", 5)); + ((Arena) arena).setHideChances(section.getBoolean(id + ".hidechances")); + arena.setArenaOption("MURDERER_DIVIDER",section.getInt(id + ".playerpermurderer", 5)); + arena.setArenaOption("DETECTIVE_DIVIDER",section.getInt(id + ".playerperdetective", 7)); + ((Arena) arena).setGoldVisuals(section.getBoolean(id + ".goldvisuals")); + ((Arena) arena).setPlayerSpawnPoints(playerSpawnPoints); - specialBlocks.forEach(arena::loadSpecialBlock); + List goldSpawnPoints = new ArrayList<>(); + for(String loc : section.getStringList(id + ".goldspawnpoints")) { + goldSpawnPoints.add(LocationSerializer.getLocation(loc)); + } + ((Arena) arena).setGoldSpawnPoints(goldSpawnPoints); - registerArena(arena); - arena.start(); - Debugger.sendConsoleMsg(plugin.getChatManager().colorMessage("Validator.Instance-Started").replace("%arena%", id)); + List specialBlocks = new ArrayList<>(); + for(String loc : section.getStringList(id + ".mystery-cauldrons")) { + specialBlocks.add(new SpecialBlock(LocationSerializer.getLocation(loc), SpecialBlock.SpecialBlockType.MYSTERY_CAULDRON)); } - ConfigUtils.saveConfig(plugin, config, "arenas"); - Debugger.debug("Arenas registration completed, took {0}ms", System.currentTimeMillis() - start); + for(String loc : section.getStringList(id + ".confessionals")) { + specialBlocks.add(new SpecialBlock(LocationSerializer.getLocation(loc), SpecialBlock.SpecialBlockType.PRAISE_DEVELOPER)); + } + + specialBlocks.forEach(((Arena) arena)::loadSpecialBlock); + return true; } - public static List getArenas() { - return arenas; + @Override + public @Nullable Arena getArena(Player player) { + PluginArena pluginArena = super.getArena(player); + if(pluginArena instanceof Arena) { + return (Arena) pluginArena; + } + return null; } - public static void shuffleBungeeArena() { - bungeeArena = new Random().nextInt(arenas.size()); + @Override + public @Nullable Arena getArena(String id) { + PluginArena pluginArena = super.getArena(id); + if(pluginArena instanceof Arena) { + return (Arena) pluginArena; + } + return null; } - public static int getBungeeArena() { - if(bungeeArena == -999) { - bungeeArena = new Random().nextInt(arenas.size()); + public @NotNull List getPluginArenas() { + List arenas = new ArrayList<>(); + for(PluginArena pluginArena : super.getArenas()) { + if(pluginArena instanceof Arena) { + arenas.add((Arena) pluginArena); + } } - return bungeeArena; + return arenas; } } diff --git a/src/main/java/plugily/projects/murdermystery/arena/ArenaState.java b/src/main/java/plugily/projects/murdermystery/arena/ArenaState.java deleted file mode 100644 index 103fe03b..00000000 --- a/src/main/java/plugily/projects/murdermystery/arena/ArenaState.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.arena; - -import org.bukkit.plugin.java.JavaPlugin; - -import plugily.projects.murdermystery.Main; - -/** - * @author TomTheDeveloper - *

- * Contains all GameStates. - */ -public enum ArenaState { - WAITING_FOR_PLAYERS("Waiting"), STARTING("Starting"), IN_GAME("In-Game"), ENDING("Ending"), RESTARTING("Restarting"); - - private final String formattedName; - private final String placeholder; - - ArenaState(String formattedName) { - this.formattedName = formattedName; - this.placeholder = JavaPlugin.getPlugin(Main.class).getChatManager().colorMessage("Placeholders.Game-States." + formattedName); - } - - public String getFormattedName() { - return formattedName; - } - - public String getPlaceholder() { - return placeholder; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/arena/ArenaUtils.java b/src/main/java/plugily/projects/murdermystery/arena/ArenaUtils.java index 8d51e13e..29708eac 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/ArenaUtils.java +++ b/src/main/java/plugily/projects/murdermystery/arena/ArenaUtils.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,119 +18,48 @@ package plugily.projects.murdermystery.arena; -import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.plugin.java.JavaPlugin; - -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.compat.xseries.XSound; -import plugily.projects.commonsbox.minecraft.hologram.ArmorStandHologram; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; +import plugily.projects.minigamesbox.classic.arena.ArenaState; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.PluginArenaUtils; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.handlers.language.TitleBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.hologram.ArmorStandHologram; +import plugily.projects.minigamesbox.classic.utils.misc.complement.ComplementAccessor; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XSound; import plugily.projects.murdermystery.arena.role.Role; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.user.User; import plugily.projects.murdermystery.utils.ItemPosition; -import plugily.projects.murdermystery.utils.Utils; /** * @author Plajer - *

- * Created at 13.03.2018 + *

Created at 13.03.2018 */ -public class ArenaUtils { +public class ArenaUtils extends PluginArenaUtils { - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private static final ChatManager chatManager = plugin.getChatManager(); + private ArenaUtils() { + super(); + } public static void onMurdererDeath(Arena arena) { for(Player player : arena.getPlayers()) { - VersionUtils.sendTitles(player, chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Titles.Win", player), - chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Subtitles.Murderer-Stopped", player), 5, 40, 5); - if(Role.isRole(Role.MURDERER, player, arena)) { - VersionUtils.sendTitles(player, chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Titles.Lose", player), null, 5, 40, 5); - } - User loopUser = plugin.getUserManager().getUser(player); - if(Role.isRole(Role.INNOCENT, player, arena)) { + VersionUtils.sendSubTitle(player, getPlugin().getLanguageManager().getLanguageMessage("In-Game.Messages.Game-End.Placeholders.Murderer.Stopped"), 5, 40, 5); + User loopUser = getPlugin().getUserManager().getUser(player); + if(Role.isRole(Role.INNOCENT, loopUser, arena)) { addScore(loopUser, ScoreAction.SURVIVE_GAME, 0); - } else if(Role.isRole(Role.ANY_DETECTIVE, player, arena)) { + } else if(Role.isRole(Role.ANY_DETECTIVE, loopUser, arena)) { addScore(loopUser, ScoreAction.WIN_GAME, 0); addScore(loopUser, ScoreAction.DETECTIVE_WIN_GAME, 0); } } - for(Player murderer : arena.getMurdererList()) { - VersionUtils.sendTitles(murderer, chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Titles.Lose", murderer), - chatManager.colorMessage("In-Game.Messages.Game-End-Messages.Subtitles.Murderer-Stopped", murderer), 5, 40, 5); - } //we must call it ticks later due to instant respawn bug - Bukkit.getScheduler().runTaskLater(plugin, () -> ArenaManager.stopGame(false, arena), 10); - } - - public static void addScore(User user, ScoreAction action, int amount) { - String s = plugin.getConfig().getString("AddScore-Sound", ""); - if(!s.isEmpty()) { - Sound sound = XSound.ENTITY_EXPERIENCE_ORB_PICKUP.parseSound(); - - try { - sound = Sound.valueOf(s.toUpperCase()); - } catch(IllegalArgumentException e) { - } - - XSound.matchXSound(sound).play(user.getPlayer().getLocation(), 1F, 2F); - } - - String msg = chatManager.colorMessage("In-Game.Messages.Bonus-Score"); - - if(action == ScoreAction.GOLD_PICKUP && amount > 1) { - int score = action.points * amount; - - msg = StringUtils.replace(msg, "%score%", Integer.toString(score)); - msg = StringUtils.replace(msg, "%action%", action.action); - - user.setStat(StatsStorage.StatisticType.LOCAL_SCORE, user.getStat(StatsStorage.StatisticType.LOCAL_SCORE) + score); - user.getPlayer().sendMessage(msg); - return; - } - - if(action == ScoreAction.DETECTIVE_WIN_GAME) { - int innocents = 0; - Arena arena = user.getArena(); - - for(Player p : arena.getPlayersLeft()) { - if(Role.isRole(Role.INNOCENT, p, arena)) { - innocents++; - } - } - - int overallInnocents = 100 * innocents; - - user.setStat(StatsStorage.StatisticType.LOCAL_SCORE, user.getStat(StatsStorage.StatisticType.LOCAL_SCORE) + overallInnocents); - - msg = StringUtils.replace(msg, "%score%", Integer.toString(overallInnocents)); - msg = StringUtils.replace(msg, "%action%", action.action.replace("%amount%", Integer.toString(innocents))); - - user.getPlayer().sendMessage(msg); - return; - } - - msg = StringUtils.replace(msg, "%score%", Integer.toString(action.points)); - - if(action.points < 0) { - msg = StringUtils.replace(msg, "+", ""); - } - - msg = StringUtils.replace(msg, "%action%", action.action); - - user.setStat(StatsStorage.StatisticType.LOCAL_SCORE, user.getStat(StatsStorage.StatisticType.LOCAL_SCORE) + action.points); - user.getPlayer().sendMessage(msg); + Bukkit.getScheduler().runTask(getPlugin(), () -> getPlugin().getArenaManager().stopGame(false, arena)); } public static void updateInnocentLocator(Arena arena) { @@ -139,25 +68,32 @@ public static void updateInnocentLocator(Arena arena) { if(!arena.isMurdererLocatorReceived()) { ItemStack innocentLocator = new ItemStack(Material.COMPASS, 1); ItemMeta innocentMeta = innocentLocator.getItemMeta(); - ComplementAccessor.getComplement().setDisplayName(innocentMeta, chatManager.colorMessage("In-Game.Innocent-Locator-Item-Name")); + ComplementAccessor.getComplement() + .setDisplayName( + innocentMeta, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_LOCATOR_INNOCENT").asKey().build()); innocentLocator.setItemMeta(innocentMeta); for(Player p : list) { if(arena.isMurderAlive(p)) { - ItemPosition.setItem(p, ItemPosition.INNOCENTS_LOCATOR, innocentLocator); + ItemPosition.setItem(getPlugin().getUserManager().getUser(p), ItemPosition.INNOCENTS_LOCATOR, innocentLocator); } } arena.setMurdererLocatorReceived(true); for(Player p : list) { - if(Role.isRole(Role.MURDERER, p, arena)) { + if(Role.isRole(Role.MURDERER, getPlugin().getUserManager().getUser(p), arena)) { continue; } - VersionUtils.sendTitles(p, chatManager.colorMessage("In-Game.Watch-Out-Title", p), chatManager.colorMessage("In-Game.Watch-Out-Subtitle", p), 5, 40, 5); + new TitleBuilder("IN_GAME_MESSAGES_ARENA_LOCATOR_WATCH_OUT") + .asKey() + .player(p) + .arena(arena) + .sendPlayer(); } } for(Player p : list) { - if(Role.isRole(Role.MURDERER, p, arena)) { + if(Role.isRole(Role.MURDERER, getPlugin().getUserManager().getUser(p), arena)) { continue; } for(Player murder : arena.getMurdererList()) { @@ -169,111 +105,143 @@ public static void updateInnocentLocator(Arena arena) { } } - private static void addBowLocator(Arena arena, Location loc) { - ItemStack bowLocator = new ItemStack(Material.COMPASS, 1); - ItemMeta bowMeta = bowLocator.getItemMeta(); - ComplementAccessor.getComplement().setDisplayName(bowMeta, chatManager.colorMessage("In-Game.Bow-Locator-Item-Name")); - bowLocator.setItemMeta(bowMeta); - for(Player p : arena.getPlayersLeft()) { - if(Role.isRole(Role.INNOCENT, p, arena)) { - ItemPosition.setItem(p, ItemPosition.BOW_LOCATOR, bowLocator); - p.setCompassTarget(loc); - } - } - } - public static void dropBowAndAnnounce(Arena arena, Player victim) { if(arena.getBowHologram() != null) { return; } - java.util.List list = arena.getPlayersLeft(); - if(list.size() > 1) { - for(Player p : arena.getPlayers()) { - VersionUtils.sendTitles(p, chatManager.colorMessage("In-Game.Messages.Bow-Messages.Bow-Dropped-Title", p), null, 5, 40, 5); - } - for(Player p : list) { - VersionUtils.sendTitles(p, null, chatManager.colorMessage("In-Game.Messages.Bow-Messages.Bow-Dropped-Subtitle", p), 5, 40, 5); - } - } + new TitleBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_BOW_DROPPED").asKey().arena(arena).sendArena(); - ArmorStandHologram hologram = new ArmorStandHologram(victim.getLocation()) - .appendItem(new ItemStack(Material.BOW, 1)); + ArmorStandHologram hologram = + new ArmorStandHologram(victim.getLocation()).appendItem(new ItemStack(Material.BOW, 1)); arena.setBowHologram(hologram); addBowLocator(arena, hologram.getLocation()); } - public static boolean areInSameArena(Player one, Player two) { - Arena a1 = ArenaRegistry.getArena(one); - return a1 != null && a1.equals(ArenaRegistry.getArena(two)); - } - - public static void hidePlayer(Player p, Arena arena) { - for(Player player : arena.getPlayers()) { - if(plugin.getUserManager().getUser(player).isSpectator()) { - VersionUtils.showPlayer(plugin, player, p); - } else { - VersionUtils.hidePlayer(plugin, player, p); - } - } - } - - public static void showPlayer(Player p, Arena arena) { - for(Player player : arena.getPlayers()) { - VersionUtils.showPlayer(plugin, player, p); - } - } - - public static void hidePlayersOutsideTheGame(Player player, Arena arena) { - for(Player players : plugin.getServer().getOnlinePlayers()) { - if(arena.getPlayers().contains(players)) { - continue; + private static void addBowLocator(Arena arena, Location loc) { + ItemStack bowLocator = new ItemStack(Material.COMPASS, 1); + ItemMeta bowMeta = bowLocator.getItemMeta(); + ComplementAccessor.getComplement() + .setDisplayName( + bowMeta, new MessageBuilder("IN_GAME_MESSAGES_ARENA_LOCATOR_BOW").asKey().build()); + bowLocator.setItemMeta(bowMeta); + for(Player p : arena.getPlayersLeft()) { + User user = getPlugin().getUserManager().getUser(p); + if(Role.isRole(Role.INNOCENT, user, arena)) { + ItemPosition.setItem(user, ItemPosition.BOW_LOCATOR, bowLocator); + p.setCompassTarget(loc); } - VersionUtils.hidePlayer(plugin, player, players); - VersionUtils.hidePlayer(plugin, players, player); } } public static void updateNameTagsVisibility(final Player p) { - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.NAMETAGS_HIDDEN)) { + if(!getPlugin().getConfigPreferences().getOption("HIDE_NAMETAGS")) { return; } - for(Player players : plugin.getServer().getOnlinePlayers()) { - Arena arena = ArenaRegistry.getArena(players); + for(Player players : getPlugin().getServer().getOnlinePlayers()) { + PluginArena arena = getPlugin().getArenaRegistry().getArena(players); if(arena == null) { continue; } - VersionUtils.updateNameTagsVisibility(p, players, "MMHide", arena.getArenaState() != ArenaState.IN_GAME); + VersionUtils.updateNameTagsVisibility( + p, players, "MMHide", arena.getArenaState() != ArenaState.IN_GAME); } } - public static void arenaForceStart(Player player) { - if(!Utils.hasPermission(player, "murdermystery.admin.forcestart")) { - return; - } - if(!Utils.checkIsInGameInstance(player)) { + public static void addScore(User user, ScoreAction action, int amount) { + XSound.matchXSound(XSound.ENTITY_EXPERIENCE_ORB_PICKUP.parseSound()) + .play(user.getPlayer().getLocation(), 1F, 2F); + + if(action == ScoreAction.GOLD_PICKUP && amount > 1) { + int score = action.points * amount; + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_BONUS") + .asKey() + .player(user.getPlayer()) + .arena(user.getArena()) + .integer(score) + .value(action.action) + .sendPlayer(); + user.adjustStatistic("LOCAL_SCORE", score); return; } - Arena arena = ArenaRegistry.getArena(player); - if(arena.getPlayers().size() < 2) { - chatManager.broadcast(arena, chatManager.formatMessage(arena, chatManager.colorMessage("In-Game.Messages.Lobby-Messages.Waiting-For-Players"), arena.getMinimumPlayers())); + + if(action == ScoreAction.DETECTIVE_WIN_GAME) { + int innocents = 0; + Arena arena = (Arena) user.getArena(); + + for(Player p : arena.getPlayersLeft()) { + if(Role.isRole(Role.INNOCENT, getPlugin().getUserManager().getUser(p), arena)) { + innocents++; + } + } + + int overallInnocents = 100 * innocents; + + user.adjustStatistic("LOCAL_SCORE", overallInnocents); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_BONUS") + .asKey() + .player(user.getPlayer()) + .arena(user.getArena()) + .integer(overallInnocents) + .value(new MessageBuilder(action.action).integer(innocents).build()) + .sendPlayer(); return; } - if(arena.getArenaState() == ArenaState.WAITING_FOR_PLAYERS || arena.getArenaState() == ArenaState.STARTING) { - arena.setArenaState(ArenaState.STARTING); - arena.setForceStart(true); - arena.setTimer(0); - for(Player arenaPlayers : arena.getPlayers()) { - arenaPlayers.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Admin-Messages.Set-Starting-In-To-0")); - } + String msg = + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_BONUS") + .asKey() + .player(user.getPlayer()) + .arena(user.getArena()) + .integer(action.points) + .value(action.action) + .build(); + + if(action.points < 0) { + msg = msg.replace("+", ""); } + + user.adjustStatistic("LOCAL_SCORE", action.points); + user.getPlayer().sendMessage(msg); } public enum ScoreAction { - KILL_PLAYER(100, chatManager.colorMessage("In-Game.Messages.Score-Actions.Kill-Player")), KILL_MURDERER(200, chatManager.colorMessage("In-Game.Messages.Score-Actions.Kill-Murderer")), - GOLD_PICKUP(15, chatManager.colorMessage("In-Game.Messages.Score-Actions.Gold-Pickup")), SURVIVE_TIME(150, chatManager.colorMessage("In-Game.Messages.Score-Actions.Survive")), - SURVIVE_GAME(200, chatManager.colorMessage("In-Game.Messages.Score-Actions.Survive-Till-End")), WIN_GAME(100, chatManager.colorMessage("In-Game.Messages.Score-Actions.Win-Game")), - DETECTIVE_WIN_GAME(0, chatManager.colorMessage("In-Game.Messages.Score-Actions.Detective-Reward")), INNOCENT_KILL(-100, chatManager.colorMessage("In-Game.Messages.Score-Actions.Innocent-Kill")); + KILL_PLAYER( + 100, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_KILL_PLAYER") + .asKey() + .build()), + KILL_MURDERER( + 200, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_KILL_MURDERER") + .asKey() + .build()), + GOLD_PICKUP( + 15, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_PICKUP_GOLD") + .asKey() + .build()), + SURVIVE_TIME( + 150, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_SURVIVING_TIME") + .asKey() + .build()), + SURVIVE_GAME( + 200, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_SURVIVING_END") + .asKey() + .build()), + WIN_GAME( + 100, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_WIN").asKey().build()), + DETECTIVE_WIN_GAME( + 0, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_DETECTIVE") + .asKey() + .build()), + INNOCENT_KILL( + -100, + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_KILL_INNOCENT") + .asKey() + .build()); int points; String action; @@ -291,5 +259,4 @@ public String getAction() { return action; } } - } diff --git a/src/main/java/plugily/projects/murdermystery/arena/corpse/Corpse.java b/src/main/java/plugily/projects/murdermystery/arena/corpse/Corpse.java index f6c75514..91364110 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/corpse/Corpse.java +++ b/src/main/java/plugily/projects/murdermystery/arena/corpse/Corpse.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ import org.golde.bukkit.corpsereborn.nms.Corpses; -import plugily.projects.commonsbox.minecraft.hologram.ArmorStandHologram; +import plugily.projects.minigamesbox.classic.utils.hologram.ArmorStandHologram; /** * @author Plajer diff --git a/src/main/java/plugily/projects/murdermystery/arena/corpse/Stand.java b/src/main/java/plugily/projects/murdermystery/arena/corpse/Stand.java index 875a4a27..155a7319 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/corpse/Stand.java +++ b/src/main/java/plugily/projects/murdermystery/arena/corpse/Stand.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ import org.bukkit.entity.ArmorStand; -import plugily.projects.commonsbox.minecraft.hologram.ArmorStandHologram; +import plugily.projects.minigamesbox.classic.utils.hologram.ArmorStandHologram; /** * @author Plajer diff --git a/src/main/java/plugily/projects/murdermystery/arena/managers/MapRestorerManager.java b/src/main/java/plugily/projects/murdermystery/arena/managers/MapRestorerManager.java new file mode 100644 index 00000000..7e7d1ee8 --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/arena/managers/MapRestorerManager.java @@ -0,0 +1,98 @@ +/* + * MurderMystery - Find the murderer, kill him and survive! + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package plugily.projects.murdermystery.arena.managers; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Item; +import org.golde.bukkit.corpsereborn.CorpseAPI.CorpseAPI; +import plugily.projects.minigamesbox.classic.arena.managers.PluginMapRestorerManager; +import plugily.projects.murdermystery.HookManager; +import plugily.projects.murdermystery.arena.Arena; +import plugily.projects.murdermystery.arena.corpse.Corpse; +import plugily.projects.murdermystery.arena.corpse.Stand; + +import java.util.Objects; + +public class MapRestorerManager extends PluginMapRestorerManager { + + public final Arena arena; + + public MapRestorerManager(Arena arena) { + super(arena); + this.arena = arena; + } + + @Override + public void fullyRestoreArena() { + cleanUpArena(); + super.fullyRestoreArena(); + } + + + public void cleanUpArena() { + removeBowHolo(); + arena.setMurdererLocatorReceived(false); + arena.getDetectiveContributions().clear(); + arena.getMurdererContributions().clear(); + arena.getGameCharacters().clear(); + arena.getMurdererList().clear(); + arena.getDetectiveList().clear(); + arena.getDeaths().clear(); + arena.setDetectiveDead(false); + clearCorpses(); + clearGold(); + } + + public void removeBowHolo() { + if(arena.getBowHologram() != null && !arena.getBowHologram().isDeleted()) { + arena.getBowHologram().delete(); + } + arena.setBowHologram(null); + } + + public void clearGold() { + arena.getGoldSpawned().stream().filter(Objects::nonNull).forEach(Item::remove); + arena.getGoldSpawned().clear(); + } + + public void clearCorpses() { + if(!arena.getPlugin().getHookManager().isFeatureEnabled(HookManager.HookFeature.CORPSES)) { + for(Stand stand : arena.getStands()) { + if(!stand.getHologram().isDeleted()) { + stand.getHologram().delete(); + } + if(stand.getStand() != null) { + stand.getStand().remove(); + } + } + arena.getStands().clear(); + return; + } + for(Corpse corpse : arena.getCorpses()) { + if(!corpse.getHologram().isDeleted()) { + corpse.getHologram().delete(); + } + if(corpse.getCorpseData() != null) { + corpse.getCorpseData().destroyCorpseFromEveryone(); + CorpseAPI.removeCorpse(corpse.getCorpseData()); + } + } + arena.getCorpses().clear(); + } +} diff --git a/src/main/java/plugily/projects/murdermystery/arena/managers/ScoreboardManager.java b/src/main/java/plugily/projects/murdermystery/arena/managers/ScoreboardManager.java index 3ad9d9de..52208f4b 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/managers/ScoreboardManager.java +++ b/src/main/java/plugily/projects/murdermystery/arena/managers/ScoreboardManager.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,178 +18,58 @@ package plugily.projects.murdermystery.arena.managers; -import me.clip.placeholderapi.PlaceholderAPI; -import me.tigerhix.lib.scoreboard.ScoreboardLib; -import me.tigerhix.lib.scoreboard.common.EntryBuilder; -import me.tigerhix.lib.scoreboard.type.Entry; -import me.tigerhix.lib.scoreboard.type.Scoreboard; -import me.tigerhix.lib.scoreboard.type.ScoreboardHandler; -import org.apache.commons.lang.StringUtils; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import plugily.projects.commonsbox.string.StringFormatUtils; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaState; +import plugily.projects.minigamesbox.classic.arena.ArenaState; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.managers.PluginScoreboardManager; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.scoreboard.common.EntryBuilder; +import plugily.projects.minigamesbox.classic.utils.scoreboard.type.Entry; import plugily.projects.murdermystery.arena.role.Role; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.user.User; -import java.util.ArrayList; import java.util.List; /** - * @author Plajer - *

- * Created at 24.03.2019 + * @author Tigerpanzer_02 + *

Created at 19.12.2021 */ -public class ScoreboardManager { +public class ScoreboardManager extends PluginScoreboardManager { - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private final List scoreboards = new ArrayList<>(); - private final Arena arena; + private final PluginArena arena; - public ScoreboardManager(Arena arena) { + public ScoreboardManager(PluginArena arena) { + super(arena); this.arena = arena; } - /** - * Creates arena scoreboard for target user - * - * @param user user that represents game player - * @see User - */ - public void createScoreboard(User user) { - Player player = user.getPlayer(); - final String boardTitle = plugin.getChatManager().colorMessage("Scoreboard.Title"); - Scoreboard scoreboard = ScoreboardLib.createScoreboard(player).setHandler(new ScoreboardHandler() { - @Override - public String getTitle(Player player) { - return boardTitle; - } - - @Override - public List getEntries(Player player) { - return formatScoreboard(user); - } - }); - scoreboard.activate(); - scoreboards.add(scoreboard); - } - - /** - * Removes scoreboard of user - * - * @param user user that represents game player - * @see User - */ - public void removeScoreboard(User user) { - for(Scoreboard board : scoreboards) { - if(board.getHolder().equals(user.getPlayer())) { - scoreboards.remove(board); - board.deactivate(); - return; - } - } - } - - /** - * Forces all scoreboards to deactivate. - */ - public void stopAllScoreboards() { - scoreboards.forEach(Scoreboard::deactivate); - scoreboards.clear(); - } - - private List formatScoreboard(User user) { + @Override + public List formatScoreboard(User user) { EntryBuilder builder = new EntryBuilder(); List lines; - if(arena.getArenaState() == ArenaState.IN_GAME) { - lines = LanguageManager.getLanguageList("Scoreboard.Content.Playing"); - if(Role.isRole(Role.MURDERER, user.getPlayer())) { - lines = LanguageManager.getLanguageList("Scoreboard.Content.Playing-Murderer"); - } + if(user.getArena().getArenaState() == ArenaState.FULL_GAME) { + lines = + user.getArena() + .getPlugin() + .getLanguageManager() + .getLanguageList("Scoreboard.Content.Starting"); + } else if(user.getArena().getArenaState() == ArenaState.IN_GAME) { + lines = + user.getArena() + .getPlugin() + .getLanguageManager() + .getLanguageList( + "Scoreboard.Content." + user.getArena().getArenaState().getFormattedName() + (Role.isRole(Role.MURDERER, user) ? "-Murderer" : "")); } else { - //apply fix - if(arena.getArenaState() == ArenaState.ENDING) { - lines = LanguageManager.getLanguageList("Scoreboard.Content.Playing"); - if(Role.isRole(Role.MURDERER, user.getPlayer())) { - lines = LanguageManager.getLanguageList("Scoreboard.Content.Playing-Murderer"); - } - } else { - lines = LanguageManager.getLanguageList("Scoreboard.Content." + arena.getArenaState().getFormattedName()); - } + lines = + user.getArena() + .getPlugin() + .getLanguageManager() + .getLanguageList( + "Scoreboard.Content." + user.getArena().getArenaState().getFormattedName()); } for(String line : lines) { - builder.next(formatScoreboardLine(line, user)); + builder.next(new MessageBuilder(line).player(user.getPlayer()).arena(arena).build()); } return builder.build(); } - - private String formatScoreboardLine(String line, User user) { - String formattedLine = line; - - int timer = arena.getTimer(); - - formattedLine = StringUtils.replace(formattedLine, "%TIME%", Integer.toString(timer + 1)); - formattedLine = StringUtils.replace(formattedLine, "%FORMATTED_TIME%", StringFormatUtils.formatIntoMMSS(timer + 1)); - formattedLine = StringUtils.replace(formattedLine, "%MAPNAME%", arena.getMapName()); - - boolean havePlayer = false; - int innocents = 0; - - Player player = user.getPlayer(); - - for(Player p : arena.getPlayersLeft()) { - if (p == player) { - havePlayer = true; - } - - if(!Role.isRole(Role.MURDERER, p)) { - innocents++; - } - } - - ChatManager chatManager = plugin.getChatManager(); - - if(!havePlayer) { - formattedLine = StringUtils.replace(formattedLine, "%ROLE%", chatManager.colorMessage("Scoreboard.Roles.Dead")); - } else { - if(Role.isRole(Role.MURDERER, player)) { - formattedLine = StringUtils.replace(formattedLine, "%ROLE%", chatManager.colorMessage("Scoreboard.Roles.Murderer")); - } else if(Role.isRole(Role.ANY_DETECTIVE, player)) { - formattedLine = StringUtils.replace(formattedLine, "%ROLE%", chatManager.colorMessage("Scoreboard.Roles.Detective")); - } else { - formattedLine = StringUtils.replace(formattedLine, "%ROLE%", chatManager.colorMessage("Scoreboard.Roles.Innocent")); - } - } - formattedLine = StringUtils.replace(formattedLine, "%INNOCENTS%", Integer.toString(innocents)); - formattedLine = StringUtils.replace(formattedLine, "%PLAYERS%", Integer.toString(arena.getPlayers().size())); - formattedLine = StringUtils.replace(formattedLine, "%MAX_PLAYERS%", Integer.toString(arena.getMaximumPlayers())); - formattedLine = StringUtils.replace(formattedLine, "%MIN_PLAYERS%", Integer.toString(arena.getMinimumPlayers())); - - if (arena.isDetectiveDead()) { - if(!arena.isCharacterSet(Arena.CharacterType.FAKE_DETECTIVE)) { - formattedLine = StringUtils.replace(formattedLine, "%DETECTIVE_STATUS%", chatManager.colorMessage("Scoreboard.Detective-Died-No-Bow")); - } else { - formattedLine = StringUtils.replace(formattedLine, "%DETECTIVE_STATUS%", chatManager.colorMessage("Scoreboard.Detective-Died-Bow")); - } - } else { - formattedLine = StringUtils.replace(formattedLine, "%DETECTIVE_STATUS%", chatManager.colorMessage("Scoreboard.Detective-Status-Normal")); - } - - //should be for murderer only - formattedLine = StringUtils.replace(formattedLine, "%KILLS%", Integer.toString(user.getStat(StatsStorage.StatisticType.LOCAL_KILLS))); - formattedLine = StringUtils.replace(formattedLine, "%SCORE%", Integer.toString(user.getStat(StatsStorage.StatisticType.LOCAL_SCORE))); - - if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) { - formattedLine = PlaceholderAPI.setPlaceholders(player, formattedLine); - } - - return chatManager.colorRawMessage(formattedLine); - } - } diff --git a/src/main/java/plugily/projects/murdermystery/arena/options/ArenaOption.java b/src/main/java/plugily/projects/murdermystery/arena/options/ArenaOption.java deleted file mode 100644 index 17e5283a..00000000 --- a/src/main/java/plugily/projects/murdermystery/arena/options/ArenaOption.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.arena.options; - -/** - * @author Plajer - *

- * Created at 24.03.2019 - */ -public enum ArenaOption { - /** - * Current arena timer, ex. 30 seconds before game starts. - */ - TIMER(0), - /** - * Minimum players in arena needed to start. - */ - MINIMUM_PLAYERS(2), - /** - * Maximum players arena can hold, users with full games permission can bypass this! - */ - MAXIMUM_PLAYERS(10); - - private final int defaultValue; - - ArenaOption(int defaultValue) { - this.defaultValue = defaultValue; - } - - public int getDefaultValue() { - return defaultValue; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/arena/role/Role.java b/src/main/java/plugily/projects/murdermystery/arena/role/Role.java index dcc603ed..6cc7284b 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/role/Role.java +++ b/src/main/java/plugily/projects/murdermystery/arena/role/Role.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,10 +19,9 @@ package plugily.projects.murdermystery.arena.role; import org.bukkit.entity.Player; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.user.User; import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; - -import java.util.Arrays; /** * @author Plajer @@ -65,40 +64,44 @@ public enum Role { * Checks whether player is playing specified role or not * * @param role role to check - * @param player player to check + * @param user player to check * @return true if is playing it, false otherwise */ - public static boolean isRole(Role role, Player player) { - return isRole(role, player, ArenaRegistry.getArena(player)); + public static boolean isRole(Role role, User user) { + return isRole(role, user, user.getArena()); } /** * Checks whether player is playing specified role or not * * @param role role to check - * @param player player to check + * @param user player to check * @param arena the arena where to check * @return true if is playing it, false otherwise */ - public static boolean isRole(Role role, Player player, Arena arena) { - if (arena == null) + public static boolean isRole(Role role, User user, PluginArena arena) { + if(arena == null) return false; - + Arena pluginArena = (Arena) arena.getPlugin().getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return false; + } + Player player = user.getPlayer(); switch(role) { case DETECTIVE: - return arena.isCharacterSet(Arena.CharacterType.DETECTIVE) && arena.getDetectiveList().contains(player); + return pluginArena.isCharacterSet(Arena.CharacterType.DETECTIVE) && pluginArena.getDetectiveList().contains(player); case FAKE_DETECTIVE: - return player.equals(arena.getCharacter(Arena.CharacterType.FAKE_DETECTIVE)); + return player.equals(pluginArena.getCharacter(Arena.CharacterType.FAKE_DETECTIVE)); case MURDERER: - return arena.isCharacterSet(Arena.CharacterType.MURDERER) && arena.getMurdererList().contains(player); + return pluginArena.isCharacterSet(Arena.CharacterType.MURDERER) && pluginArena.getMurdererList().contains(player); case ANY_DETECTIVE: - return isRole(Role.DETECTIVE, player) || isRole(Role.FAKE_DETECTIVE, player); + return isRole(Role.DETECTIVE, user) || isRole(Role.FAKE_DETECTIVE, user); case INNOCENT: - return !isRole(Role.MURDERER, player) && !isRole(Role.ANY_DETECTIVE, player); + return !isRole(Role.MURDERER, user) && !isRole(Role.ANY_DETECTIVE, user); case DEATH: - return arena.isDeathPlayer(player); + return pluginArena.isDeathPlayer(player); case SPECTATOR: - return arena.isSpectatorPlayer(player); + return pluginArena.isSpectatorPlayer(player); default: return false; } @@ -107,21 +110,23 @@ public static boolean isRole(Role role, Player player, Arena arena) { /** * Checks whether player is playing a role or not * - * @param player player to check + * @param user player to check * @return true if is playing one role, false otherwise */ - public static boolean isAnyRole(Player player) { - return isAnyRole(player, ArenaRegistry.getArena(player)); + public static boolean isAnyRole(User user) { + return isAnyRole(user, user.getArena()); } + private static final Role[] roles = Role.values(); + /** * Checks whether player is playing a role or not * - * @param player player to check - * @param arena the player's arena + * @param user player to check + * @param arena the player's arena * @return true if is playing one role, false otherwise */ - public static boolean isAnyRole(Player player, Arena arena) { - return arena != null && Arrays.stream(Role.values()).anyMatch(role -> isRole(role, player, arena)); + public static boolean isAnyRole(User user, PluginArena arena) { + return arena != null && java.util.Arrays.stream(roles).anyMatch(role -> isRole(role, user, arena)); } } diff --git a/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlock.java b/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlock.java index fe932463..c18f7edf 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlock.java +++ b/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlock.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ import org.bukkit.Location; -import plugily.projects.commonsbox.minecraft.hologram.ArmorStandHologram; +import plugily.projects.minigamesbox.classic.utils.hologram.ArmorStandHologram; /** * @author Plajer diff --git a/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlockEvents.java b/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlockEvents.java index 7cf9f850..bb52ded3 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlockEvents.java +++ b/src/main/java/plugily/projects/murdermystery/arena/special/SpecialBlockEvents.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,25 +26,22 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.inventory.ItemStack; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.item.ItemUtils; -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; +import plugily.projects.minigamesbox.classic.arena.ArenaState; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.helper.ItemBuilder; +import plugily.projects.minigamesbox.classic.utils.helper.ItemUtils; +import plugily.projects.minigamesbox.classic.utils.misc.complement.ComplementAccessor; +import plugily.projects.minigamesbox.classic.utils.version.ServerVersion; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; import plugily.projects.murdermystery.arena.special.mysterypotion.MysteryPotion; import plugily.projects.murdermystery.arena.special.mysterypotion.MysteryPotionRegistry; import plugily.projects.murdermystery.arena.special.pray.PrayerRegistry; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.user.User; import plugily.projects.murdermystery.utils.ItemPosition; -import plugily.projects.murdermystery.utils.Utils; + /** * @author Plajer @@ -54,44 +51,42 @@ public class SpecialBlockEvents implements Listener { private final Main plugin; - private final ChatManager chatManager; public SpecialBlockEvents(Main plugin) { this.plugin = plugin; - chatManager = plugin.getChatManager(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler - public void onSpecialBlockClick(PlayerInteractEvent e) { - if (e.getClickedBlock() == null) + public void onSpecialBlockClick(PlayerInteractEvent event) { + if(event.getClickedBlock() == null) return; - if(ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_11_R1) && e.getHand() == org.bukkit.inventory.EquipmentSlot.OFF_HAND) { + if(ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_11_R1) && event.getHand() == org.bukkit.inventory.EquipmentSlot.OFF_HAND) { return; } - Arena arena = ArenaRegistry.getArena(e.getPlayer()); + Arena arena = plugin.getArenaRegistry().getArena(event.getPlayer()); if(arena == null) { return; } - if(arena.getArenaState() != ArenaState.IN_GAME || plugin.getUserManager().getUser(e.getPlayer()).isSpectator()) { + if(arena.getArenaState() != ArenaState.IN_GAME || plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { return; } for(SpecialBlock specialBlock : arena.getSpecialBlocks()) { - if(e.getClickedBlock().getType() == XMaterial.LEVER.parseMaterial() && Utils.getNearbyBlocks(specialBlock.getLocation(), 3).contains(e.getClickedBlock())) { - onPrayLeverClick(e); + if(event.getClickedBlock().getType() == XMaterial.LEVER.parseMaterial() && plugin.getBukkitHelper().getNearbyBlocks(specialBlock.getLocation(), 3).contains(event.getClickedBlock())) { + onPrayLeverClick(event); return; } - if(specialBlock.getLocation().getBlock().equals(e.getClickedBlock())) { + if(specialBlock.getLocation().getBlock().equals(event.getClickedBlock())) { switch(specialBlock.getSpecialBlockType()) { case MYSTERY_CAULDRON: - onCauldronClick(e); + onCauldronClick(event); return; case PRAISE_DEVELOPER: - onPrayerClick(e); + onPrayerClick(event); return; case HORSE_PURCHASE: case RAPID_TELEPORTATION: @@ -103,82 +98,86 @@ public void onSpecialBlockClick(PlayerInteractEvent e) { } } - private void onCauldronClick(PlayerInteractEvent e) { - if(e.getClickedBlock().getType() != Material.CAULDRON) { + private void onCauldronClick(PlayerInteractEvent event) { + if(event.getClickedBlock().getType() != Material.CAULDRON) { return; } - if(e.getPlayer().getInventory().getItem(/* same for all roles */ ItemPosition.POTION.getOtherRolesItemPosition()) != null) { - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Special-Blocks.Cauldron-Drink-Potion", e.getPlayer())); + if(event.getPlayer().getInventory().getItem(/* same for all roles */ ItemPosition.POTION.getOtherRolesItemPosition()) != null) { + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_CAULDRON_POTION").asKey().player(event.getPlayer()).sendPlayer(); return; } - User user = plugin.getUserManager().getUser(e.getPlayer()); + User user = plugin.getUserManager().getUser(event.getPlayer()); - int localGold = user.getStat(StatsStorage.StatisticType.LOCAL_GOLD); + int localGold = user.getStatistic("LOCAL_GOLD"); if(localGold < 1) { - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Special-Blocks.Not-Enough-Gold", e.getPlayer()).replace("%amount%", "1")); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_NOT_ENOUGH_GOLD").asKey().player(event.getPlayer()).integer(1).sendPlayer(); return; } - VersionUtils.sendParticles("FIREWORKS_SPARK", e.getPlayer(), e.getClickedBlock().getLocation(), 10); - Item item = e.getClickedBlock().getWorld().dropItemNaturally(e.getClickedBlock().getLocation().clone().add(0, 1, 0), new ItemStack(Material.POTION, 1)); + org.bukkit.Location blockLoc = event.getClickedBlock().getLocation(); + + VersionUtils.sendParticles("FIREWORKS_SPARK", event.getPlayer(), blockLoc, 10); + Item item = blockLoc.getWorld().dropItemNaturally(blockLoc.clone().add(0, 1, 0), new ItemStack(Material.POTION, 1)); item.setPickupDelay(10000); Bukkit.getScheduler().runTaskLater(plugin, item::remove, 20); - user.setStat(StatsStorage.StatisticType.LOCAL_GOLD, localGold - 1); - ItemPosition.addItem(e.getPlayer(), ItemPosition.GOLD_INGOTS, new ItemStack(Material.GOLD_INGOT, -1)); - ItemPosition.setItem(e.getPlayer(), ItemPosition.POTION, new ItemBuilder(XMaterial.POTION.parseItem()).name(MysteryPotionRegistry.getRandomPotion().getName()).build()); + user.adjustStatistic("LOCAL_GOLD", 1); + ItemPosition.addItem(user, ItemPosition.GOLD_INGOTS, new ItemStack(Material.GOLD_INGOT, -1)); + ItemPosition.setItem(user, ItemPosition.POTION, new ItemBuilder(XMaterial.POTION.parseItem()).name(MysteryPotionRegistry.getRandomPotion().getName()).build()); } - private void onPrayerClick(PlayerInteractEvent e) { - if(e.getClickedBlock().getType() != XMaterial.ENCHANTING_TABLE.parseMaterial()) { + private void onPrayerClick(PlayerInteractEvent event) { + if(event.getClickedBlock().getType() != XMaterial.ENCHANTING_TABLE.parseMaterial()) { return; } - e.setCancelled(true); + event.setCancelled(true); - User user = plugin.getUserManager().getUser(e.getPlayer()); - int localGold = user.getStat(StatsStorage.StatisticType.LOCAL_GOLD); + User user = plugin.getUserManager().getUser(event.getPlayer()); + int localGold = user.getStatistic("LOCAL_GOLD"); if(localGold < 1) { - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Special-Blocks.Not-Enough-Gold", e.getPlayer()).replace("%amount%", "1")); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_NOT_ENOUGH_GOLD").asKey().player(event.getPlayer()).integer(1).sendPlayer(); return; } - - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Special-Blocks.Prayed-Message", e.getPlayer())); - user.setStat(StatsStorage.StatisticType.LOCAL_PRAISES, user.getStat(StatsStorage.StatisticType.LOCAL_PRAISES) + 1); - VersionUtils.sendParticles("FIREWORKS_SPARK", e.getPlayer(), e.getClickedBlock().getLocation(), 10); - user.setStat(StatsStorage.StatisticType.LOCAL_GOLD, localGold - 1); - ItemPosition.addItem(e.getPlayer(), ItemPosition.GOLD_INGOTS, new ItemStack(Material.GOLD_INGOT, -1)); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_CHAT").asKey().player(event.getPlayer()).sendPlayer(); + user.adjustStatistic("LOCAL_PRAISES", 1); + VersionUtils.sendParticles("FIREWORKS_SPARK", event.getPlayer(), event.getClickedBlock().getLocation(), 10); + user.adjustStatistic("LOCAL_GOLD", 1); + ItemPosition.addItem(user, ItemPosition.GOLD_INGOTS, new ItemStack(Material.GOLD_INGOT, -1)); } - private void onPrayLeverClick(PlayerInteractEvent e) { - User user = plugin.getUserManager().getUser(e.getPlayer()); - if(user.getStat(StatsStorage.StatisticType.LOCAL_PRAISES) < 1) { - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Messages.Special-Blocks.No-Money-No-Pray", e.getPlayer())); + private void onPrayLeverClick(PlayerInteractEvent event) { + User user = plugin.getUserManager().getUser(event.getPlayer()); + if(user.getStatistic("LOCAL_PRAISES") < 1) { + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PAY").asKey().player(event.getPlayer()).sendPlayer(); return; } PrayerRegistry.applyRandomPrayer(user); - user.setStat(StatsStorage.StatisticType.LOCAL_PRAISES, 0); + user.setStatistic("LOCAL_PRAISES", 0); } @EventHandler - public void onMysteryPotionDrink(PlayerItemConsumeEvent e) { - ItemStack item = e.getItem(); + public void onMysteryPotionDrink(PlayerItemConsumeEvent event) { + ItemStack item = event.getItem(); if(item.getType() != XMaterial.POTION.parseMaterial() || !ItemUtils.isItemStackNamed(item)) { return; } - Arena arena = ArenaRegistry.getArena(e.getPlayer()); - if(arena == null) { + + if(plugin.getArenaRegistry().getArena(event.getPlayer()) == null) { return; } + + String itemDisplayName = ComplementAccessor.getComplement().getDisplayName(item.getItemMeta()); + User user = plugin.getUserManager().getUser(event.getPlayer()); for(MysteryPotion potion : MysteryPotionRegistry.getMysteryPotions()) { - if(ComplementAccessor.getComplement().getDisplayName(item.getItemMeta()).equals(potion.getName())) { - e.setCancelled(true); - e.getPlayer().sendMessage(potion.getSubtitle()); - VersionUtils.sendTitles(e.getPlayer(), "", potion.getSubtitle(), 5, 40, 5); - ItemPosition.setItem(e.getPlayer(), ItemPosition.POTION, null); - e.getPlayer().addPotionEffect(potion.getPotionEffect()); + if(itemDisplayName.equals(potion.getName())) { + event.setCancelled(true); + event.getPlayer().sendMessage(potion.getSubtitle()); + VersionUtils.sendTitles(event.getPlayer(), "", potion.getSubtitle(), 5, 40, 5); + ItemPosition.setItem(user, ItemPosition.POTION, null); + event.getPlayer().addPotionEffect(potion.getPotionEffect()); return; } } diff --git a/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotion.java b/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotion.java index e53d6bed..d46173b3 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotion.java +++ b/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotion.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotionRegistry.java b/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotionRegistry.java index 2ab7a5d8..16afe1e2 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotionRegistry.java +++ b/src/main/java/plugily/projects/murdermystery/arena/special/mysterypotion/MysteryPotionRegistry.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,7 +22,8 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.utils.configuration.ConfigUtils; import plugily.projects.murdermystery.Main; import java.util.ArrayList; @@ -39,7 +40,7 @@ public class MysteryPotionRegistry { private static final List mysteryPotions = new ArrayList<>(); public static void init(Main plugin) { - FileConfiguration config = ConfigUtils.getConfig(plugin, "specialblocks"); + FileConfiguration config = ConfigUtils.getConfig(plugin, "special_blocks"); org.bukkit.configuration.ConfigurationSection section = config.getConfigurationSection("Special-Blocks.Cauldron-Potions"); if(section == null) { return; @@ -48,16 +49,16 @@ public static void init(Main plugin) { for(String key : section.getKeys(false)) { PotionEffectType effectType = PotionEffectType.getByName(section.getString(key + ".Type", "").toUpperCase()); - if (effectType == null) { - effectType = PotionEffectType.HEAL; + if(effectType == null) { + continue; } //amplifiers are counted from 0 so -1 PotionEffect effect = new PotionEffect(effectType, section.getInt(key + ".Duration") * 20, section.getInt(key + ".Amplifier") - 1, false, false); - mysteryPotions.add(new MysteryPotion(plugin.getChatManager().colorRawMessage(section.getString(key + ".Name")), - plugin.getChatManager().colorRawMessage(section.getString(key + ".Subtitle")), effect)); + mysteryPotions.add(new MysteryPotion(new MessageBuilder(section.getString(key + ".Name")).build(), + new MessageBuilder(section.getString(key + ".Subtitle")).build(), effect)); } } diff --git a/src/main/java/plugily/projects/murdermystery/arena/special/pray/Prayer.java b/src/main/java/plugily/projects/murdermystery/arena/special/pray/Prayer.java index 95f10374..ee8318f6 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/special/pray/Prayer.java +++ b/src/main/java/plugily/projects/murdermystery/arena/special/pray/Prayer.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/main/java/plugily/projects/murdermystery/arena/special/pray/PrayerRegistry.java b/src/main/java/plugily/projects/murdermystery/arena/special/pray/PrayerRegistry.java index f8e4645f..d2665193 100644 --- a/src/main/java/plugily/projects/murdermystery/arena/special/pray/PrayerRegistry.java +++ b/src/main/java/plugily/projects/murdermystery/arena/special/pray/PrayerRegistry.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -25,16 +25,13 @@ import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; -import plugily.projects.commonsbox.minecraft.misc.MiscUtils; +import plugily.projects.minigamesbox.classic.arena.ArenaState; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.misc.MiscUtils; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; import plugily.projects.murdermystery.arena.role.Role; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.user.User; import plugily.projects.murdermystery.utils.ItemPosition; import java.util.ArrayList; @@ -49,7 +46,6 @@ public class PrayerRegistry { private static Main plugin; - private static ChatManager chatManager; private static final List prayers = new ArrayList<>(); private static final List ban = new ArrayList<>(), rush = new ArrayList<>(); @@ -58,18 +54,17 @@ private PrayerRegistry() { public static void init(Main plugin) { PrayerRegistry.plugin = plugin; - chatManager = plugin.getChatManager(); //good prayers - prayers.add(new Prayer(Prayer.PrayerType.DETECTIVE_REVELATION, true, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Gifts.Detective-Revelation"))); - prayers.add(new Prayer(Prayer.PrayerType.GOLD_RUSH, true, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Gifts.Gold-Rush"))); - prayers.add(new Prayer(Prayer.PrayerType.SINGLE_COMPENSATION, true, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Gifts.Single-Compensation"))); - prayers.add(new Prayer(Prayer.PrayerType.BOW_TIME, true, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Gifts.Bow-Time"))); + prayers.add(new Prayer(Prayer.PrayerType.DETECTIVE_REVELATION, true, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_DETECTIVE_REVELATION").asKey().build())); + prayers.add(new Prayer(Prayer.PrayerType.GOLD_RUSH, true, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_GOLD_RUSH").asKey().build())); + prayers.add(new Prayer(Prayer.PrayerType.SINGLE_COMPENSATION, true, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_SINGLE_COMPENSATION").asKey().build())); + prayers.add(new Prayer(Prayer.PrayerType.BOW_TIME, true, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_BOW").asKey().build())); //bad prayers - prayers.add(new Prayer(Prayer.PrayerType.SLOWNESS_CURSE, false, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Curses.Slowness-Curse"))); - prayers.add(new Prayer(Prayer.PrayerType.BLINDNESS_CURSE, false, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Curses.Blindness-Curse"))); - prayers.add(new Prayer(Prayer.PrayerType.GOLD_BAN, false, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Curses.Gold-Ban"))); - prayers.add(new Prayer(Prayer.PrayerType.INCOMING_DEATH, false, chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Curses.Incoming-Death"))); + prayers.add(new Prayer(Prayer.PrayerType.SLOWNESS_CURSE, false, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_SLOWNESS").asKey().build())); + prayers.add(new Prayer(Prayer.PrayerType.BLINDNESS_CURSE, false, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_BLINDNESS").asKey().build())); + prayers.add(new Prayer(Prayer.PrayerType.GOLD_BAN, false, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_GOLD").asKey().build())); + prayers.add(new Prayer(Prayer.PrayerType.INCOMING_DEATH, false, new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_DEATH").asKey().build())); } public static Prayer getRandomPray() { @@ -83,16 +78,16 @@ public static List getPrayers() { public static void applyRandomPrayer(User user) { Prayer prayer = getRandomPray(); - user.setStat(StatsStorage.StatisticType.LOCAL_CURRENT_PRAY, prayer.getPrayerType().ordinal()); + user.setStatistic("LOCAL_CURRENT_PRAY", prayer.getPrayerType().ordinal()); Player player = user.getPlayer(); - Arena arena = ArenaRegistry.getArena(player); - List prayMessage = LanguageManager.getLanguageList("In-Game.Messages.Special-Blocks.Praises.Message"); + Arena arena = plugin.getArenaRegistry().getArena(player); + List prayMessage = plugin.getLanguageManager().getLanguageList("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Heard"); - String feeling = chatManager.colorMessage("In-Game.Messages.Special-Blocks.Praises.Feelings." + (prayer.isGoodPray() ? "Blessed" : "Cursed"), player); + String feeling = plugin.getLanguageManager().getLanguageMessage("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Feeling." + (prayer.isGoodPray() ? "Blessed" : "Cursed")); int praySize = prayMessage.size(); - for (int a = 0; a < praySize; a++) { + for(int a = 0; a < praySize; a++) { prayMessage.set(a, prayMessage.get(a).replace("%feeling%", feeling).replace("%praise%", prayer.getPrayerDescription())); } @@ -101,21 +96,25 @@ public static void applyRandomPrayer(User user) { player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Integer.MAX_VALUE, 0, false, false)); break; case BOW_TIME: - if(!Role.isRole(Role.ANY_DETECTIVE, player, arena)) { - ItemPosition.addItem(player, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); + if(!Role.isRole(Role.ANY_DETECTIVE, user, arena)) { + ItemPosition.addItem(user, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); } - ItemPosition.setItem(player, ItemPosition.ARROWS, new ItemStack(Material.ARROW, plugin.getConfig().getInt("Detective-Prayer-Arrows", 2))); + ItemPosition.setItem(user, ItemPosition.ARROWS, new ItemStack(Material.ARROW, plugin.getConfig().getInt("Bow.Amount.Arrows.Prayer", 2))); break; case DETECTIVE_REVELATION: - Player characterType = arena.getCharacter(Arena.CharacterType.DETECTIVE); + Player characterType = null; - if (characterType == null) { - characterType = arena.getCharacter(Arena.CharacterType.FAKE_DETECTIVE); + if(arena != null) { + characterType = arena.getCharacter(Arena.CharacterType.DETECTIVE); + + if(characterType == null) { + characterType = arena.getCharacter(Arena.CharacterType.FAKE_DETECTIVE); + } } String charName = characterType == null ? "????" : characterType.getName(); - for (int a = 0; a < praySize; a++) { + for(int a = 0; a < praySize; a++) { prayMessage.set(a, prayMessage.get(a).replace("%detective%", charName)); } @@ -139,8 +138,8 @@ public void run() { }.runTaskTimer(plugin, 20, 20); break; case SINGLE_COMPENSATION: - ItemPosition.addItem(player, ItemPosition.GOLD_INGOTS, new ItemStack(Material.GOLD_INGOT, 5)); - user.setStat(StatsStorage.StatisticType.LOCAL_GOLD, user.getStat(StatsStorage.StatisticType.LOCAL_GOLD) + 5); + ItemPosition.addItem(user, ItemPosition.GOLD_INGOTS, new ItemStack(Material.GOLD_INGOT, 5)); + user.adjustStatistic("LOCAL_GOLD", 5); break; case SLOWNESS_CURSE: player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, Integer.MAX_VALUE, 0, false, false)); diff --git a/src/main/java/plugily/projects/murdermystery/arena/states/InGameState.java b/src/main/java/plugily/projects/murdermystery/arena/states/InGameState.java new file mode 100644 index 00000000..f85d3b8c --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/arena/states/InGameState.java @@ -0,0 +1,161 @@ +/* + * MurderMystery - Find the murderer, kill him and survive! + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package plugily.projects.murdermystery.arena.states; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.states.PluginInGameState; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.handlers.language.TitleBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XSound; +import plugily.projects.murdermystery.arena.Arena; +import plugily.projects.murdermystery.arena.ArenaUtils; +import plugily.projects.murdermystery.arena.role.Role; +import plugily.projects.murdermystery.utils.ItemPosition; + +/** + * @author Plajer + *

Created at 03.06.2019 + */ +public class InGameState extends PluginInGameState { + + @Override + public void handleCall(PluginArena arena) { + super.handleCall(arena); + Arena pluginArena = (Arena) getPlugin().getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return; + } + + // winner checks + if(pluginArena.getTimer() <= 0) { + getPlugin().getArenaManager().stopGame(false, pluginArena); + } + if(pluginArena.getPlayersLeft().size() == pluginArena.aliveMurderer()) { + getPlugin().getArenaManager().stopGame(false, pluginArena); + } + + distributeMurdererSword(pluginArena); + //every 30 secs survive reward + givePlayerSurviveReward(pluginArena); + addInnocentLocator(pluginArena); + if(pluginArena.getPlayersLeft().size() == pluginArena.aliveMurderer() + 1) { + addMurdererSpeed(pluginArena); + } + spawnGold(pluginArena); + } + + private void addMurdererSpeed(Arena pluginArena) { + int multiplier = getPlugin().getConfig().getInt("Murderer.Speed", 3); + if(multiplier > 1 && multiplier <= 10) { + for(Player player : pluginArena.getMurdererList()) { + if(pluginArena.isMurderAlive(player)) { + // no potion because it adds particles which can be identified + player.setWalkSpeed(0.1f * multiplier); + } + } + } + } + + private void distributeMurdererSword(Arena pluginArena) { + int inGameLength = getPlugin().getConfig().getInt("Time-Manager.In-Game", 270); + if(pluginArena.getTimer() <= (inGameLength - 10) && pluginArena.getTimer() > (inGameLength - 15)) { + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_SWORD_SOON").asKey().integer(pluginArena.getTimer() - (inGameLength - 15)).arena(pluginArena).sendArena(); + for(Player p : pluginArena.getPlayers()) { + XSound.UI_BUTTON_CLICK.play(p.getLocation(), 1, 1); + } + + if(pluginArena.getTimer() == (inGameLength - 14)) { + if(pluginArena.getMurdererList().isEmpty()) getPlugin().getArenaManager().stopGame(false, pluginArena); + + for(Player p : pluginArena.getMurdererList()) { + User murderer = getPlugin().getUserManager().getUser(p); + + if(murderer.isSpectator() || !p.isOnline()) + continue; + + p.getInventory().setHeldItemSlot(0); + ItemPosition.setItem(murderer, ItemPosition.MURDERER_SWORD, pluginArena.getPlugin().getSwordSkinManager().getRandomSwordSkin(p)); + } + } + } + } + + private void spawnGold(Arena pluginArena) { + //don't spawn it every time + if(pluginArena.getSpawnGoldTimer() == pluginArena.getSpawnGoldTime()) { + spawnSomeGold(pluginArena); + pluginArena.setSpawnGoldTimer(0); + } else { + pluginArena.setSpawnGoldTimer(pluginArena.getSpawnGoldTimer() + 1); + } + } + + private void givePlayerSurviveReward(Arena pluginArena) { + if(pluginArena.getTimer() % 30 == 0) { + new TitleBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_TIME_LEFT").arena(pluginArena).sendArena(); + for(Player p : pluginArena.getPlayersLeft()) { + User user = getPlugin().getUserManager().getUser(p); + if(Role.isRole(Role.INNOCENT, user, pluginArena)) { + ArenaUtils.addScore(user, ArenaUtils.ScoreAction.SURVIVE_TIME, 0); + } + } + } + } + + private void addInnocentLocator(Arena pluginArena) { + if(pluginArena.getTimer() <= 30 || pluginArena.getPlayersLeft().size() == pluginArena.aliveMurderer() + 1) { + if(getPlugin().getConfigPreferences().getOption("MURDERER_LOCATOR")) { + ArenaUtils.updateInnocentLocator(pluginArena); + } + } + } + + private void spawnSomeGold(Arena arena) { + int spawnPointsSize = arena.getGoldSpawnPoints().size(); + + if(spawnPointsSize == 0) { + return; + } + //may users want to disable it and want much gold on their map xD + if(!getPlugin().getConfigPreferences().getOption("GOLD_LIMITER")) { + //do not exceed amount of gold per spawn + if(arena.getGoldSpawned().size() >= spawnPointsSize) { + return; + } + } + if(getPlugin().getConfigPreferences().getOption("GOLD_SPAWNER_MODE_ALL")) { + for(Location location : arena.getGoldSpawnPoints()) { + dropGold(arena, location); + } + } else { + Location loc = arena.getGoldSpawnPoints().get(getPlugin().getRandom().nextInt(spawnPointsSize)); + dropGold(arena, loc); + } + } + + private void dropGold(Arena arena, Location location) { + arena.getGoldSpawned().add(location.getWorld().dropItem(location, new ItemStack(Material.GOLD_INGOT, 1))); + getPlugin().getPowerupRegistry().spawnPowerup(location, arena); + } +} diff --git a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStartEvent.java b/src/main/java/plugily/projects/murdermystery/arena/states/RestartingState.java similarity index 53% rename from src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStartEvent.java rename to src/main/java/plugily/projects/murdermystery/arena/states/RestartingState.java index b1b895d6..0fa4b635 100644 --- a/src/main/java/plugily/projects/murdermystery/api/events/game/MMGameStartEvent.java +++ b/src/main/java/plugily/projects/murdermystery/arena/states/RestartingState.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,33 +16,30 @@ * along with this program. If not, see . */ -package plugily.projects.murdermystery.api.events.game; +package plugily.projects.murdermystery.arena.states; -import org.bukkit.event.HandlerList; -import plugily.projects.murdermystery.api.events.MurderMysteryEvent; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.states.PluginRestartingState; import plugily.projects.murdermystery.arena.Arena; /** * @author Plajer - * @since 0.0.1-alpha *

- * Called when arena has started. + * Created at 03.06.2019 */ -public class MMGameStartEvent extends MurderMysteryEvent { - - private static final HandlerList HANDLERS = new HandlerList(); - - public MMGameStartEvent(Arena arena) { - super(arena); - } - - public static HandlerList getHandlerList() { - return HANDLERS; - } +public class RestartingState extends PluginRestartingState { @Override - public HandlerList getHandlers() { - return HANDLERS; + public void handleCall(PluginArena arena) { + super.handleCall(arena); + Arena pluginArena = (Arena) getPlugin().getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return; + } + if(arena.getTimer() <= 0) { + if(pluginArena.isGoldVisuals()) { + pluginArena.startGoldVisuals(); + } + } } - } diff --git a/src/main/java/plugily/projects/murdermystery/arena/states/StartingState.java b/src/main/java/plugily/projects/murdermystery/arena/states/StartingState.java new file mode 100644 index 00000000..8832ea27 --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/arena/states/StartingState.java @@ -0,0 +1,144 @@ +/* + * MurderMystery - Find the murderer, kill him and survive! + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package plugily.projects.murdermystery.arena.states; + +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.states.PluginStartingState; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.handlers.language.TitleBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; +import plugily.projects.murdermystery.arena.Arena; +import plugily.projects.murdermystery.arena.ArenaUtils; +import plugily.projects.murdermystery.arena.role.Role; +import plugily.projects.murdermystery.arena.special.pray.PrayerRegistry; +import plugily.projects.murdermystery.utils.ItemPosition; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author Plajer + *

Created at 03.06.2019 + */ +public class StartingState extends PluginStartingState { + + int maxmurderer = 1; + int maxdetectives = 1; + + @Override + public void handleCall(PluginArena arena) { + super.handleCall(arena); + Arena pluginArena = (Arena) getPlugin().getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return; + } + + if(!pluginArena.isHideChances()) { + for(Player player : arena.getPlayers()) { + String message = new MessageBuilder("IN_GAME_MESSAGES_ARENA_ROLE_CHANCES_ACTION_BAR").asKey().player(player).arena(pluginArena).build(); + VersionUtils.sendActionBar(player, message); + } + } + + if(arena.getTimer() == 0 || arena.isForceStart()) { + int size = pluginArena.getPlayerSpawnPoints().size(); + for(Player player : arena.getPlayers()) { + VersionUtils.teleport(player, pluginArena.getPlayerSpawnPoints().get(getPlugin().getRandom().nextInt(size))); + User user = arena.getPlugin().getUserManager().getUser(player); + user.resetNonePersistentStatistics(); + PrayerRegistry.getRush().remove(player); + PrayerRegistry.getBan().remove(player); + ArenaUtils.updateNameTagsVisibility(player); + player.setGameMode(GameMode.ADVENTURE); + } + + Set playersToSet = new HashSet<>(arena.getPlayers()); + + getMaxRolesToSet(pluginArena); + + addRole(pluginArena, Role.MURDERER, playersToSet); + addRole(pluginArena, Role.DETECTIVE, playersToSet); + + for(Player player : playersToSet) { + new TitleBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_INNOCENT").asKey().player(player).arena(pluginArena).sendPlayer(); + } + + arena.getPlugin().getDebugger().debug("After: Arena: {0} | Detectives = {1}, Murders = {2}, Players = {3} | Players: Detectives = {4}, Murders = {5}", arena.getId(), maxdetectives, maxmurderer, arena.getPlayers().size(), pluginArena.getDetectiveList(), pluginArena.getMurdererList()); + + // Load and append special blocks hologram + pluginArena.getSpecialBlocks().forEach(pluginArena::loadSpecialBlock); + } + } + + private void addRole(Arena arena, Role role, Set playersToSet) { + String roleName = role.toString(); + + List chancesRanking = getPlugin().getUserManager().getUsers(arena).stream().filter(user -> playersToSet.contains(user.getPlayer())).sorted(Comparator.comparingInt(user -> arena.getContributorValue(role, user))).collect(Collectors.toList()); + Collections.reverse(chancesRanking); + List chancesPlayer = new ArrayList<>(); + for(User user : chancesRanking) { + chancesPlayer.add(user.getPlayer()); + } + getPlugin().getDebugger().debug("Arena {0} | Role add {1} | List {2}", arena.getId(), roleName, chancesPlayer); + + int amount = role == Role.MURDERER ? maxmurderer : maxdetectives; + for(int i = 0; i < amount; i++) { + User user = chancesRanking.get(i); + Player userPlayer = user.getPlayer(); + arena.setCharacter(role, userPlayer); + arena.resetContributorValue(role, user); + playersToSet.remove(userPlayer); + new TitleBuilder("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_" + roleName).asKey().arena(arena).player(user.getPlayer()).sendPlayer(); + if(role == Role.MURDERER) { + arena.getMurdererList().add(userPlayer); + } else if(role == Role.DETECTIVE) { + arena.getDetectiveList().add(userPlayer); + userPlayer.getInventory().setHeldItemSlot(0); + ItemPosition.setItem(user, ItemPosition.BOW, new ItemStack(Material.BOW, 1)); + ItemPosition.setItem(user, ItemPosition.INFINITE_ARROWS, new ItemStack(Material.ARROW, getPlugin().getConfig().getInt("Bow.Amount.Arrows.Detective", 3))); + } + } + } + + private void getMaxRolesToSet(Arena arena) { + int playersSize = arena.getPlayers().size(); + arena.getPlugin().getDebugger().debug("Before: Arena: {0} | Detectives = {1}, Murders = {2}, Players = {3} | Configured: Detectives = {4}, Murders = {5}", arena.getId(), maxdetectives, maxmurderer, playersSize, arena.getArenaOption("DETECTIVE_DIVIDER"), arena.getArenaOption("MURDERER_DIVIDER")); + if(arena.getArenaOption("MURDERER_DIVIDER") > 1 && playersSize > arena.getArenaOption("MURDERER_DIVIDER")) { + maxmurderer = (playersSize / arena.getArenaOption("MURDERER_DIVIDER")); + } + if(arena.getArenaOption("DETECTIVE_DIVIDER") > 1 && playersSize > arena.getArenaOption("DETECTIVE_DIVIDER")) { + maxdetectives = (playersSize / arena.getArenaOption("DETECTIVE_DIVIDER")); + } + if(playersSize - (maxmurderer + maxdetectives) < 1) { + arena.getPlugin().getDebugger().debug("{0} Murderers and detectives amount was reduced because there are not enough players", arena.getId()); + // Make sure to have one innocent! + if(maxdetectives > 1) { + maxdetectives--; + } else if(maxmurderer > 1) { + maxmurderer--; + } + } + arena.getPlugin().getDebugger().debug("After: Arena: {0} | Detectives = {1}, Murders = {2}, Players = {3} | Configured: Detectives = {4}, Murders = {5}", arena.getId(), maxdetectives, maxmurderer, playersSize, arena.getArenaOption("DETECTIVE_DIVIDER"), arena.getArenaOption("MURDERER_DIVIDER")); + } +} diff --git a/src/main/java/plugily/projects/murdermystery/arena/states/WaitingState.java b/src/main/java/plugily/projects/murdermystery/arena/states/WaitingState.java new file mode 100644 index 00000000..b5715a9f --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/arena/states/WaitingState.java @@ -0,0 +1,24 @@ +package plugily.projects.murdermystery.arena.states; + +import org.bukkit.configuration.file.FileConfiguration; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.arena.states.PluginWaitingState; +import plugily.projects.minigamesbox.classic.utils.configuration.ConfigUtils; +import plugily.projects.murdermystery.arena.Arena; + +public class WaitingState extends PluginWaitingState { + + @Override + public void handleCall(PluginArena arena) { + super.handleCall(arena); + Arena pluginArena = (Arena) getPlugin().getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return; + } + if(arena.getTimer() <= 0) { + FileConfiguration config = + ConfigUtils.getConfig(getPlugin(), "arenas"); + pluginArena.setGoldVisuals(config.getBoolean(pluginArena.getId() + ".goldvisuals")); + } + } +} diff --git a/src/main/java/plugily/projects/murdermystery/boot/AdditionalValueInitializer.java b/src/main/java/plugily/projects/murdermystery/boot/AdditionalValueInitializer.java new file mode 100644 index 00000000..ea19b8eb --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/boot/AdditionalValueInitializer.java @@ -0,0 +1,109 @@ +package plugily.projects.murdermystery.boot; + +import plugily.projects.minigamesbox.classic.api.StatisticType; +import plugily.projects.minigamesbox.classic.api.StatsStorage; +import plugily.projects.minigamesbox.classic.arena.options.ArenaOption; +import plugily.projects.minigamesbox.classic.arena.options.ArenaOptionManager; +import plugily.projects.minigamesbox.classic.handlers.items.SpecialItemManager; +import plugily.projects.minigamesbox.classic.handlers.permissions.PermissionCategory; +import plugily.projects.minigamesbox.classic.handlers.permissions.PermissionsManager; +import plugily.projects.minigamesbox.classic.handlers.reward.RewardType; +import plugily.projects.minigamesbox.classic.handlers.reward.RewardsFactory; +import plugily.projects.minigamesbox.classic.preferences.ConfigOption; +import plugily.projects.minigamesbox.classic.preferences.ConfigPreferences; +import plugily.projects.murdermystery.Main; + +/** + * @author Tigerpanzer_02 + *

+ * Created at 15.10.2022 + */ +public class AdditionalValueInitializer { + + private final Main plugin; + + public AdditionalValueInitializer(Main plugin) { + this.plugin = plugin; + registerConfigOptions(); + registerStatistics(); + registerPermission(); + registerRewards(); + registerSpecialItems(); + registerArenaOptions(); + } + + private void registerConfigOptions() { + getConfigPreferences().registerOption("CORPSES_INTEGRATION_OVERWRITE", new ConfigOption("Corpses.Integration-Overwrite", true)); + getConfigPreferences().registerOption("BOW_KILL_DETECTIVE", new ConfigOption("Bow.Kill-Detective", true)); + getConfigPreferences().registerOption("HIDE_DEATH", new ConfigOption("Hide.Death", false)); + getConfigPreferences().registerOption("HIDE_NAMETAGS", new ConfigOption("Hide.Nametags", false)); + getConfigPreferences().registerOption("GOLD_SPAWNER_MODE_ALL", new ConfigOption("Gold.Spawner-Mode", false)); + getConfigPreferences().registerOption("GOLD_LIMITER", new ConfigOption("Gold.Limiter", false)); + getConfigPreferences().registerOption("MURDERER_LOCATOR", new ConfigOption("Murderer.Locator", true)); + } + + private void registerStatistics() { + getStatsStorage().registerStatistic("KILLS", new StatisticType("kills", true, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("DEATHS", new StatisticType("deaths", true, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("HIGHEST_SCORE", new StatisticType("highest_score", true, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("CONTRIBUTION_DETECTIVE", new StatisticType("contribution_detective", true, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("CONTRIBUTION_MURDERER", new StatisticType("contribution_murderer", true, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("PASS_MURDERER", new StatisticType("pass_murderer", true, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("PASS_DETECTIVE", new StatisticType("pass_detective", true, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("LOCAL_PRAISES", new StatisticType("local_praises", false, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("LOCAL_SCORE", new StatisticType("local_score", false, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("LOCAL_PRAY", new StatisticType("local_pray", false, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("LOCAL_GOLD", new StatisticType("local_gold", false, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("LOCAL_KILLS", new StatisticType("local_kills", false, "int(11) NOT NULL DEFAULT '0'")); + getStatsStorage().registerStatistic("LOCAL_CURRENT_PRAY", new StatisticType("local_current_pray", false, "int(11) NOT NULL DEFAULT '0'")); + } + + private void registerPermission() { + getPermissionsManager().registerPermissionCategory("CHANCES_BOOSTER", new PermissionCategory("Chances-Boost", null)); + getPermissionsManager().registerPermissionCategory("MURDERER_BOOSTER", new PermissionCategory("Murderer-Boost", null)); + getPermissionsManager().registerPermissionCategory("DETECTIVE_BOOSTER", new PermissionCategory("Detective-Boost", null)); + } + + private void registerRewards() { + getRewardsHandler().registerRewardType("KILL_DETECTIVE", new RewardType("detective-kill")); + getRewardsHandler().registerRewardType("KILL_MURDERER", new RewardType("murderer-kill")); + getRewardsHandler().registerRewardType("WIN", new RewardType("win")); + getRewardsHandler().registerRewardType("LOSE", new RewardType("lose")); + getRewardsHandler().registerRewardType("PLAYER_DEATH", new RewardType("player-death")); + getRewardsHandler().registerRewardType("GOLD_PICKUP", new RewardType("gold-pickup")); + } + + private void registerSpecialItems() { + getSpecialItemManager().registerSpecialItem("ROLE_PASS", "Role-Pass"); + } + + private void registerArenaOptions() { + getArenaOptionManager().registerArenaOption("DETECTIVE_DIVIDER", new ArenaOption("null", 1)); + getArenaOptionManager().registerArenaOption("MURDERER_DIVIDER", new ArenaOption("null", 1)); + } + + private ConfigPreferences getConfigPreferences() { + return plugin.getConfigPreferences(); + } + + private StatsStorage getStatsStorage() { + return plugin.getStatsStorage(); + } + + private PermissionsManager getPermissionsManager() { + return plugin.getPermissionsManager(); + } + + private RewardsFactory getRewardsHandler() { + return plugin.getRewardsHandler(); + } + + private SpecialItemManager getSpecialItemManager() { + return plugin.getSpecialItemManager(); + } + + private ArenaOptionManager getArenaOptionManager() { + return plugin.getArenaOptionManager(); + } + +} diff --git a/src/main/java/plugily/projects/murdermystery/boot/MessageInitializer.java b/src/main/java/plugily/projects/murdermystery/boot/MessageInitializer.java new file mode 100644 index 00000000..5034c80c --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/boot/MessageInitializer.java @@ -0,0 +1,106 @@ + +package plugily.projects.murdermystery.boot; + + +import plugily.projects.minigamesbox.classic.handlers.language.Message; +import plugily.projects.minigamesbox.classic.handlers.language.MessageManager; +import plugily.projects.minigamesbox.classic.utils.services.locale.Locale; +import plugily.projects.minigamesbox.classic.utils.services.locale.LocaleRegistry; +import plugily.projects.murdermystery.Main; + +import java.util.Arrays; + +/** + * @author Tigerpanzer_02 + *

+ * Created at 15.10.2022 + */ +public class MessageInitializer { + private final Main plugin; + + public MessageInitializer(Main plugin) { + this.plugin = plugin; + } + + public void registerMessages() { + getMessageManager().registerMessage("", new Message("", "")); + getMessageManager().registerMessage("SCOREBOARD_ROLES_DETECTIVE", new Message("Scoreboard.Roles.Detective", "")); + getMessageManager().registerMessage("SCOREBOARD_ROLES_MURDERER", new Message("Scoreboard.Roles.Murderer", "")); + getMessageManager().registerMessage("SCOREBOARD_ROLES_INNOCENT", new Message("Scoreboard.Roles.Innocent", "")); + getMessageManager().registerMessage("SCOREBOARD_ROLES_DEAD", new Message("Scoreboard.Roles.Dead", "")); + getMessageManager().registerMessage("SCOREBOARD_DETECTIVE_ALIVE", new Message("Scoreboard.Detective.Alive", "")); + getMessageManager().registerMessage("SCOREBOARD_DETECTIVE_BOW_DROPPED", new Message("Scoreboard.Detective.Bow.Dropped", "")); + getMessageManager().registerMessage("SCOREBOARD_DETECTIVE_BOW_PICKED", new Message("Scoreboard.Detective.Bow.Picked", "")); + + getMessageManager().registerMessage("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_MURDERER_STOPPED", new Message("In-Game.Messages.Game-End.Placeholders.Murderer.Stopped", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_MURDERER_KILLED_YOU", new Message("In-Game.Messages.Game-End.Placeholders.Murderer.Killed.You", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_MURDERER_KILLED_ALL", new Message("In-Game.Messages.Game-End.Placeholders.Murderer.Killed.All", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_INNOCENT_KILLED_YOU", new Message("In-Game.Messages.Game-End.Placeholders.Innocent.Killed.You", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_INNOCENT_KILLED_WRONGLY", new Message("In-Game.Messages.Game-End.Placeholders.Innocent.Killed.All", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_NOBODY", new Message("In-Game.Messages.Game-End.Placeholders.Nobody", "")); + + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_ROLE_CHANCES_ACTION_BAR", new Message("In-Game.Messages.Arena.Chances.Action-Bar", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_COOLDOWN", new Message("In-Game.Messages.Arena.Cooldown", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_LOCATOR_BOW", new Message("In-Game.Messages.Arena.Locator.Bow", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_LOCATOR_INNOCENT", new Message("In-Game.Messages.Arena.Locator.Innocent", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_LOCATOR_WATCH_OUT", new Message("In-Game.Messages.Arena.Locator.Watch-Out", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_NAME", new Message("In-Game.Messages.Arena.Pass.Name", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_ROLE_MURDERER_NAME", new Message("In-Game.Messages.Arena.Pass.Role.Murderer.Name", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_ROLE_MURDERER_LORE", new Message("In-Game.Messages.Arena.Pass.Role.Murderer.Lore", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_ROLE_DETECTIVE_NAME", new Message("In-Game.Messages.Arena.Pass.Role.Detective.Name", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_ROLE_DETECTIVE_LORE", new Message("In-Game.Messages.Arena.Pass.Role.Detective.Lore", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_FAIL", new Message("In-Game.Messages.Arena.Pass.Fail", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_SUCCESS", new Message("In-Game.Messages.Arena.Pass.Success", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PASS_CHANGE", new Message("In-Game.Messages.Arena.Pass.Change", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_TIME_LEFT", new Message("In-Game.Messages.Arena.Playing.Time-Left", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_CHANGE", new Message("In-Game.Messages.Arena.Playing.Role.Change", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_MURDERER", new Message("In-Game.Messages.Arena.Playing.Role.Murderer", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_DETECTIVE", new Message("In-Game.Messages.Arena.Playing.Role.Detective", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_ROLE_INNOCENT", new Message("In-Game.Messages.Arena.Playing.Role.Innocent", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_BONUS", new Message("In-Game.Messages.Arena.Playing.Score.Bonus", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_GOLD", new Message("In-Game.Messages.Arena.Playing.Score.Gold", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_KILL_PLAYER", new Message("In-Game.Messages.Arena.Playing.Score.Action.Kill.Player", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_KILL_MURDERER", new Message("In-Game.Messages.Arena.Playing.Score.Action.Kill.Murderer", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_KILL_INNOCENT", new Message("In-Game.Messages.Arena.Playing.Score.Action.Kill.Innocent", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_PICKUP_GOLD", new Message("In-Game.Messages.Arena.Playing.Score.Action.Pickup.Gold", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_SURVIVING_TIME", new Message("In-Game.Messages.Arena.Playing.Score.Action.Surviving.Time", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_SURVIVING_END", new Message("In-Game.Messages.Arena.Playing.Score.Action.Surviving.End", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_WIN", new Message("In-Game.Messages.Arena.Playing.Score.Action.Win", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SCORE_ACTION_DETECTIVE", new Message("In-Game.Messages.Arena.Playing.Score.Action.Detective", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SWORD_SOON", new Message("In-Game.Messages.Arena.Playing.Sword.Soon", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_CAULDRON_POTION", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Cauldron.Potion", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_CAULDRON_HOLOGRAM", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Cauldron.Hologram", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_NOT_ENOUGH_GOLD", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Not-Enough-Gold", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_HOLOGRAM", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Hologram", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_CHAT", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Chat", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PAY", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Pay", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_HEARD", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Heard", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_FEELING_BLESSED", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Feeling.Blessed", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_FEELING_CURSED", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Feeling.Cursed", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_DETECTIVE_REVELATION", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Gifts.Detective-Revelation", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_GOLD_RUSH", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Gifts.Gold-Rush", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_SINGLE_COMPENSATION", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Gifts.Single-Compensation", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_GIFTS_BOW", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Gifts.Bow", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_SLOWNESS", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Curses.Slowness", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_BLINDNESS", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Curses.Blindness", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_GOLD", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Curses.Gold", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_SPECIAL_BLOCKS_PRAY_PRAISE_CURSES_DEATH", new Message("In-Game.Messages.Arena.Playing.Special-Blocks.Pray.Praise.Curses.Death", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_BOW_DROPPED", new Message("In-Game.Messages.Arena.Playing.Bow.Dropped", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_BOW_PICKUP", new Message("In-Game.Messages.Arena.Playing.Bow.Pickup", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_BOW_SHOT_GOLD", new Message("In-Game.Messages.Arena.Playing.Bow.Shot.Gold", "")); + getMessageManager().registerMessage("IN_GAME_MESSAGES_ARENA_PLAYING_BOW_SHOT_TITLE", new Message("In-Game.Messages.Arena.Playing.Bow.Shot.Title", "")); + getMessageManager().registerMessage("LEADERBOARD_STATISTICS_CONTRIBUTION_DETECTIVE", new Message("Leaderboard.Statistics.Detective-Contribution", "")); + getMessageManager().registerMessage("LEADERBOARD_STATISTICS_CONTRIBUTION_MURDERER", new Message("Leaderboard.Statistics.Murderer-Contribution", "")); + + getMessageManager().registerMessage("LEADERBOARD_STATISTICS_PASS_DETECTIVE", new Message("Leaderboard.Statistics.Detective-Pass", "")); + getMessageManager().registerMessage("LEADERBOARD_STATISTICS_PASS_MURDERER", new Message("Leaderboard.Statistics.Murderer-Pass", "")); + getMessageManager().registerMessage("LEADERBOARD_STATISTICS_KILLS", new Message("Leaderboard.Statistics.Kills", "")); + getMessageManager().registerMessage("LEADERBOARD_STATISTICS_DEATHS", new Message("Leaderboard.Statistics.Deaths", "")); + getMessageManager().registerMessage("LEADERBOARD_STATISTICS_HIGHEST_SCORE", new Message("Leaderboard.Statistics.Highest-Score", "")); + } + + private MessageManager getMessageManager() { + return plugin.getMessageManager(); + } + +} diff --git a/src/main/java/plugily/projects/murdermystery/boot/PlaceholderInitializer.java b/src/main/java/plugily/projects/murdermystery/boot/PlaceholderInitializer.java new file mode 100644 index 00000000..256272f1 --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/boot/PlaceholderInitializer.java @@ -0,0 +1,264 @@ + +package plugily.projects.murdermystery.boot; + +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.number.NumberUtils; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.handlers.placeholder.Placeholder; +import plugily.projects.minigamesbox.classic.handlers.placeholder.PlaceholderManager; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.user.UserManager; +import plugily.projects.murdermystery.Main; +import plugily.projects.murdermystery.arena.Arena; +import plugily.projects.murdermystery.arena.ArenaRegistry; +import plugily.projects.murdermystery.arena.role.Role; + +/** + * @author Tigerpanzer_02 + *

+ * Created at 15.10.2022 + */ +public class PlaceholderInitializer { + + private final Main plugin; + + public PlaceholderInitializer(Main plugin) { + this.plugin = plugin; + registerPlaceholders(); + } + + private void registerPlaceholders() { + getPlaceholderManager().registerPlaceholder(new Placeholder("detective_list", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + + StringBuilder detectives = new StringBuilder(); + for(Player p : pluginArena.getDetectiveList()) { + detectives.append(p.getName()).append(", "); + } + + int index = detectives.length() - 2; + if(index > 0 && index < detectives.length()) { + detectives.deleteCharAt(index); + } + + return (pluginArena.isDetectiveDead() ? ChatColor.STRIKETHROUGH : "") + + detectives.toString(); + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("murderer_list", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + + StringBuilder murders = new StringBuilder(); + for(Player p : pluginArena.getMurdererList()) { + User user = getUserManager().getUser(p); + int localKills = user.getStatistic("LOCAL_KILLS"); + murders.append(p.getName()); + if(pluginArena.getMurdererList().size() > 1) { + murders.append(" (").append(localKills).append("), "); + } + } + if(pluginArena.getMurdererList().size() > 1) { + murders.deleteCharAt(murders.length() - 2); + } + + return (pluginArena.aliveMurderer() == 1 ? "" : ChatColor.STRIKETHROUGH) + + murders.toString(); + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("murderer_kills", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + int murdererKills = 0; + for(Player p : pluginArena.getMurdererList()) { + User user = getUserManager().getUser(p); + int localKills = user.getStatistic("LOCAL_KILLS"); + murdererKills += localKills; + } + return Integer.toString(murdererKills); + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("hero", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + Player hero = pluginArena.getCharacter(Arena.CharacterType.HERO); + return hero != null ? hero.getName() : new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_NOBODY").asKey().build(); + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("murderer_chance", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + + User user = getUserManager().getUser(player); + return NumberUtils.round(((double) pluginArena.getContributorValue(Role.MURDERER, user) / (double) pluginArena.getTotalRoleChances(Role.MURDERER)) * 100.0, 2) + "%"; + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("detective_chance", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + + User user = getUserManager().getUser(player); + return NumberUtils.round(((double) pluginArena.getContributorValue(Role.DETECTIVE, user) / (double) pluginArena.getTotalRoleChances(Role.DETECTIVE)) * 100.0, 2) + "%"; + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("detective_status", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + + if(pluginArena.isDetectiveDead()) { + if(!pluginArena.isCharacterSet(Arena.CharacterType.FAKE_DETECTIVE)) { + return new MessageBuilder("SCOREBOARD_DETECTIVE_BOW_DROPPED").asKey().build(); + } else { + return new MessageBuilder("SCOREBOARD_DETECTIVE_BOW_PICKED").asKey().build(); + } + } else { + return new MessageBuilder("SCOREBOARD_DETECTIVE_ALIVE").asKey().build(); + } + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("innocent_size", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + int innocents = 0; + for(Player p : arena.getPlayersLeft()) { + if(!Role.isRole(Role.MURDERER, getUserManager().getUser(p))) { + innocents++; + } + } + return Integer.toString(innocents); + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("player_role", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + User user = getUserManager().getUser(player); + String role; + if(pluginArena.isDeathPlayer(player)) { + role = new MessageBuilder("SCOREBOARD_ROLES_DEAD").asKey().build(); + } else if(Role.isRole(Role.MURDERER, user, arena)) { + role = new MessageBuilder("SCOREBOARD_ROLES_MURDERER").asKey().build(); + } else if(Role.isRole(Role.ANY_DETECTIVE, user, arena)) { + role = new MessageBuilder("SCOREBOARD_ROLES_DETECTIVE").asKey().build(); + } else { + role = new MessageBuilder("SCOREBOARD_ROLES_INNOCENT").asKey().build(); + } + return role; + } + }); + + getPlaceholderManager().registerPlaceholder(new Placeholder("summary_player", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + return getSummary(player, arena); + } + + @Nullable + private String getSummary(Player player, PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + String summaryEnding; + + if(pluginArena.getMurdererList().containsAll(pluginArena.getPlayersLeft()) + && pluginArena.getMurdererList().contains(player)) { + summaryEnding = new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_WIN").asKey().arena(pluginArena).build(); + } else if(!pluginArena.getMurdererList().containsAll(pluginArena.getPlayersLeft()) + && !pluginArena.getMurdererList().contains(player)) { + summaryEnding = new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_WIN").asKey().arena(pluginArena).build(); + } else { + summaryEnding = new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_LOSE").asKey().arena(pluginArena).build(); + } + return summaryEnding; + } + }); + getPlaceholderManager().registerPlaceholder(new Placeholder("summary", Placeholder.PlaceholderType.ARENA, Placeholder.PlaceholderExecutor.ALL) { + @Override + public String getValue(Player player, PluginArena arena) { + return getSummary(arena); + } + + @Override + public String getValue(PluginArena arena) { + return getSummary(arena); + } + + @Nullable + private String getSummary(PluginArena arena) { + Arena pluginArena = getArenaRegistry().getArena(arena.getId()); + if(pluginArena == null) { + return null; + } + String summaryEnding; + + if(pluginArena.getMurdererList().containsAll(pluginArena.getPlayersLeft())) { + summaryEnding = new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_MURDERER_KILLED_ALL").asKey().arena(pluginArena).build(); + } else { + summaryEnding = new MessageBuilder("IN_GAME_MESSAGES_GAME_END_PLACEHOLDERS_MURDERER_STOPPED").asKey().arena(pluginArena).build(); + } + return summaryEnding; + } + }); + } + + private PlaceholderManager getPlaceholderManager() { + return plugin.getPlaceholderManager(); + } + + private ArenaRegistry getArenaRegistry() { + return plugin.getArenaRegistry(); + } + + private UserManager getUserManager() { + return plugin.getUserManager(); + } + +} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/ArgumentsRegistry.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/ArgumentsRegistry.java index 6768b0a8..d5bc6d12 100644 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/ArgumentsRegistry.java +++ b/src/main/java/plugily/projects/murdermystery/commands/arguments/ArgumentsRegistry.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,226 +18,27 @@ package plugily.projects.murdermystery.commands.arguments; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.ComponentBuilder; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.string.StringMatcher; +import plugily.projects.minigamesbox.classic.commands.arguments.PluginArgumentsRegistry; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.admin.ListArenasArgument; import plugily.projects.murdermystery.commands.arguments.admin.RolePassArgument; -import plugily.projects.murdermystery.commands.arguments.admin.TeleportArgument; -import plugily.projects.murdermystery.commands.arguments.admin.arena.DeleteArgument; -import plugily.projects.murdermystery.commands.arguments.admin.arena.ForceStartArgument; -import plugily.projects.murdermystery.commands.arguments.admin.arena.ReloadArgument; import plugily.projects.murdermystery.commands.arguments.admin.arena.SpecialBlockRemoverArgument; -import plugily.projects.murdermystery.commands.arguments.admin.arena.StopArgument; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.commands.arguments.game.ArenaSelectorArgument; -import plugily.projects.murdermystery.commands.arguments.game.CreateArgument; -import plugily.projects.murdermystery.commands.arguments.game.JoinArguments; -import plugily.projects.murdermystery.commands.arguments.game.LeaderboardArgument; -import plugily.projects.murdermystery.commands.arguments.game.LeaveArgument; import plugily.projects.murdermystery.commands.arguments.game.RoleSelectorArgument; -import plugily.projects.murdermystery.commands.arguments.game.StatsArgument; -import plugily.projects.murdermystery.commands.completion.TabCompletion; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; -import plugily.projects.murdermystery.utils.Utils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; /** * @author Plajer *

* Created at 11.01.2019 */ -public class ArgumentsRegistry implements CommandExecutor { - - private final Map> mappedArguments = new HashMap<>(); - private final Main plugin; - private final ChatManager chatManager; - private final TabCompletion tabCompletion; +public class ArgumentsRegistry extends PluginArgumentsRegistry { public ArgumentsRegistry(Main plugin) { - this.plugin = plugin; - chatManager = plugin.getChatManager(); - tabCompletion = new TabCompletion(this); - - Optional.ofNullable(plugin.getCommand("murdermystery")).ifPresent(mm -> { - mm.setExecutor(this); - mm.setTabCompleter(tabCompletion); - }); - Optional.ofNullable(plugin.getCommand("murdermysteryadmin")).ifPresent(mma -> { - mma.setExecutor(this); - mma.setTabCompleter(tabCompletion); - }); - + super(plugin); //register basic arugments - new ArenaSelectorArgument(this, chatManager); - new CreateArgument(this, chatManager); - new JoinArguments(this, chatManager); - new LeaderboardArgument(this, chatManager); - new LeaveArgument(this, chatManager); - new StatsArgument(this, chatManager); new RoleSelectorArgument(this); //register admin related arguments - new DeleteArgument(this, chatManager); - new ForceStartArgument(this); - new ListArenasArgument(this, chatManager); new SpecialBlockRemoverArgument(this); - new ReloadArgument(this, chatManager); - new StopArgument(this); - new TeleportArgument(this); - new RolePassArgument(this, chatManager); - } - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - for(Map.Entry> entry : mappedArguments.entrySet()) { - if(cmd.getName().equalsIgnoreCase(entry.getKey())) { - if(cmd.getName().equalsIgnoreCase("murdermystery")) { - if(args.length == 0 || args[0].equalsIgnoreCase("help")) { - sendHelpCommand(sender); - return true; - } - if(args.length > 1 && args[1].equalsIgnoreCase("edit")) { - if(!checkSenderIsExecutorType(sender, CommandArgument.ExecutorType.PLAYER) - || !Utils.hasPermission(sender, "murdermystery.admin.create")) { - return true; - } - Arena arena = ArenaRegistry.getArena(args[0]); - if(arena == null) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.No-Arena-Like-That")); - return true; - } - - new SetupInventory(arena, (Player) sender).openInventory(); - return true; - } - } - if(cmd.getName().equalsIgnoreCase("murdermysteryadmin") && (args.length == 0 || args[0].equalsIgnoreCase("help"))) { - if(!sender.hasPermission("murdermystery.admin")) { - return true; - } - sendAdminHelpCommand(sender); - return true; - } - for(CommandArgument argument : entry.getValue()) { - if(argument.getArgumentName().equalsIgnoreCase(args[0])) { - //does it make sense that it is a list? - for(String perm : argument.getPermissions()) { - if(perm.isEmpty() || Utils.hasPermission(sender, perm)) { - break; - } - //user has no permission to execute command - return true; - } - if(checkSenderIsExecutorType(sender, argument.getValidExecutors())) { - argument.execute(sender, args); - } - //return true even if sender is not good executor or hasn't got permission - return true; - } - } - - //sending did you mean help - List matches = StringMatcher.match(args[0], mappedArguments.get(cmd.getName().toLowerCase()).stream().map(CommandArgument::getArgumentName).collect(Collectors.toList())); - if(!matches.isEmpty()) { - sender.sendMessage(chatManager.colorMessage("Commands.Did-You-Mean").replace("%command%", label + " " + matches.get(0).getMatch())); - return true; - } - } - } - return false; - } - - private boolean checkSenderIsExecutorType(CommandSender sender, CommandArgument.ExecutorType type) { - switch(type) { - case BOTH: - return sender instanceof ConsoleCommandSender || sender instanceof Player; - case CONSOLE: - return sender instanceof ConsoleCommandSender; - case PLAYER: - if(sender instanceof Player) { - return true; - } - sender.sendMessage(chatManager.colorMessage("Commands.Only-By-Player")); - return false; - default: - return false; - } - } - - private void sendHelpCommand(CommandSender sender) { - sender.sendMessage(chatManager.colorMessage("Commands.Main-Command.Header")); - sender.sendMessage(chatManager.colorMessage("Commands.Main-Command.Description")); - if(sender.hasPermission("murdermystery.admin")) { - sender.sendMessage(chatManager.colorMessage("Commands.Main-Command.Admin-Bonus-Description")); - } - sender.sendMessage(chatManager.colorMessage("Commands.Main-Command.Footer")); - } - - private void sendAdminHelpCommand(CommandSender sender) { - sender.sendMessage(ChatColor.GREEN + " " + ChatColor.BOLD + "Murder Mystery " + ChatColor.GRAY + plugin.getDescription().getVersion()); - sender.sendMessage(ChatColor.RED + " []" + ChatColor.GRAY + " = optional " + ChatColor.GOLD + "<>" + ChatColor.GRAY + " = required"); - if(sender instanceof Player) { - sender.sendMessage(ChatColor.GRAY + "Hover command to see more, click command to suggest it."); - } - List data = mappedArguments.get("murdermysteryadmin").stream().filter(arg -> arg instanceof LabeledCommandArgument) - .map(arg -> ((LabeledCommandArgument) arg).getLabelData()).collect(Collectors.toList()); - data.add(new LabelData("/mm &6&f edit", "/mm edit", - "&7Edit existing arena\n&6Permission: &7murdermystery.admin.edit")); - data.addAll(mappedArguments.get("murdermystery").stream().filter(arg -> arg instanceof LabeledCommandArgument) - .map(arg -> ((LabeledCommandArgument) arg).getLabelData()).collect(Collectors.toList())); - for(LabelData labelData : data) { - TextComponent component = new TextComponent(labelData.getText()); - component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, labelData.getCommand())); - component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(labelData.getDescription()).create())); - VersionUtils.sendTextComponent(sender, component); - } - } - - /** - * Maps new argument to the main command - * - * @param mainCommand mother command ex. /mm - * @param argument argument to map ex. leave (for /mm leave) - */ - public void mapArgument(String mainCommand, CommandArgument argument) { - List args = mappedArguments.getOrDefault(mainCommand, new ArrayList<>()); - args.add(argument); - mappedArguments.put(mainCommand, args); - } - - public Map> getMappedArguments() { - return mappedArguments; - } - - public TabCompletion getTabCompletion() { - return tabCompletion; - } - - public Main getPlugin() { - return plugin; + new RolePassArgument(this); } } diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/ListArenasArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/ListArenasArgument.java deleted file mode 100644 index 4c902ce4..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/ListArenasArgument.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.admin; - -import org.bukkit.command.CommandSender; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class ListArenasArgument { - - public ListArenasArgument(ArgumentsRegistry registry, ChatManager chatManager) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("list", "murdermystery.admin.list", CommandArgument.ExecutorType.BOTH, - new LabelData("/mma list", "/mma list", "&7Shows list with all loaded arenas\n&6Permission: &7murdermystery.admin.list")) { - @Override - public void execute(CommandSender sender, String[] args) { - sender.sendMessage(chatManager.colorMessage("Commands.Admin-Commands.List-Command.Header")); - int i = 0; - for(Arena arena : ArenaRegistry.getArenas()) { - sender.sendMessage(chatManager.colorMessage("Commands.Admin-Commands.List-Command.Format").replace("%arena%", arena.getId()) - .replace("%status%", arena.getArenaState().getFormattedName()).replace("%players%", Integer.toString(arena.getPlayers().size())) - .replace("%maxplayers%", Integer.toString(arena.getMaximumPlayers()))); - i++; - } - if(i == 0) { - sender.sendMessage(chatManager.colorMessage("Commands.Admin-Commands.List-Command.No-Arenas")); - } - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/RolePassArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/RolePassArgument.java index 8909596b..7757d51d 100644 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/RolePassArgument.java +++ b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/RolePassArgument.java @@ -1,18 +1,35 @@ +/* + * MurderMystery - Find the murderer, kill him and survive! + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + package plugily.projects.murdermystery.commands.arguments.admin; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import plugily.projects.commonsbox.number.NumberUtils; -import plugily.projects.murdermystery.api.StatsStorage; +import plugily.projects.minigamesbox.classic.commands.arguments.data.CommandArgument; +import plugily.projects.minigamesbox.classic.commands.arguments.data.LabelData; +import plugily.projects.minigamesbox.classic.commands.arguments.data.LabeledCommandArgument; +import plugily.projects.minigamesbox.number.NumberUtils; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.user.User; import plugily.projects.murdermystery.arena.role.Role; import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.user.User; /** * @author Tigerpanzer_02 @@ -21,19 +38,19 @@ */ public class RolePassArgument { - public RolePassArgument(ArgumentsRegistry registry, ChatManager chatManager) { + public RolePassArgument(ArgumentsRegistry registry) { registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("rolepass", "murdermystery.admin.rolepass", CommandArgument.ExecutorType.BOTH, new LabelData("/mma rolepass [player]", "/mma rolepass [player] ", "&7Add or remove rolepass\n&6Permission: &7murdermystery.admin.rolepass")) { @Override public void execute(CommandSender sender, String[] args) { if(args.length < 4) { - sender.sendMessage(chatManager.getPrefix() + ChatColor.RED + "Command: /mma rolepass [player]"); + sender.sendMessage(ChatColor.RED + "Command: /mma rolepass [player]"); return; } //add/remove String addOrRemove = args[1]; if(!addOrRemove.equalsIgnoreCase("add") && !addOrRemove.equalsIgnoreCase("remove") && !addOrRemove.equalsIgnoreCase("set")) { - sender.sendMessage(chatManager.getPrefix() + ChatColor.RED + "Command: /mma rolepass [player]"); + sender.sendMessage(ChatColor.RED + "Command: /mma rolepass [player]"); return; } String roleArg = args[2]; @@ -41,55 +58,55 @@ public void execute(CommandSender sender, String[] args) { try { role = Role.valueOf(roleArg.toUpperCase()); } catch(IllegalArgumentException exception) { - sender.sendMessage(chatManager.getPrefix() + ChatColor.RED + "Command: /mma rolepass [player]"); + sender.sendMessage(ChatColor.RED + "Command: /mma rolepass [player]"); return; } if(role != Role.MURDERER && role != Role.DETECTIVE) { - sender.sendMessage(chatManager.getPrefix() + ChatColor.RED + "Command: /mma rolepass [player]"); + sender.sendMessage(ChatColor.RED + "Command: /mma rolepass [player]"); return; } java.util.Optional opt = NumberUtils.parseInt(args[3]); if(!opt.isPresent()) { - sender.sendMessage(chatManager.getPrefix() + ChatColor.RED + "Command: /mma rolepass [player]"); + sender.sendMessage(ChatColor.RED + "Command: /mma rolepass [player]"); return; } int amount = opt.orElse(0); //player Player player = args.length == 5 ? Bukkit.getPlayerExact(args[4]) : (Player) sender; if(player == null) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Admin-Commands.Player-Not-Found")); + new MessageBuilder("COMMANDS_PLAYER_NOT_FOUND").asKey().send(sender); return; } User user = registry.getPlugin().getUserManager().getUser(player); switch(addOrRemove.toLowerCase()) { case "add": if(role == Role.MURDERER) { - user.addStat(StatsStorage.StatisticType.MURDERER_PASS, amount); + user.adjustStatistic("PASS_MURDERER", amount); } else { - user.addStat(StatsStorage.StatisticType.DETECTIVE_PASS, amount); + user.adjustStatistic("PASS_DETECTIVE", amount); } break; case "remove": if(role == Role.MURDERER) { - user.addStat(StatsStorage.StatisticType.MURDERER_PASS, -amount); + user.adjustStatistic("PASS_MURDERER", -amount); } else { - user.addStat(StatsStorage.StatisticType.DETECTIVE_PASS, -amount); + user.adjustStatistic("PASS_DETECTIVE", -amount); } break; case "set": if(role == Role.MURDERER) { - user.setStat(StatsStorage.StatisticType.MURDERER_PASS, amount); + user.setStatistic("PASS_MURDERER", amount); } else { - user.setStat(StatsStorage.StatisticType.DETECTIVE_PASS, amount); + user.setStatistic("PASS_DETECTIVE", amount); } break; default: break; } if(role == Role.MURDERER) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Role-Pass.Change").replace("%amount%", Integer.toString(user.getStat(StatsStorage.StatisticType.MURDERER_PASS))).replace("%role%", Role.MURDERER.name())); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_CHANGE").asKey().player(player).integer(user.getStatistic("PASS_MURDERER")).value(Role.MURDERER.name()).sendPlayer(); } else { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("In-Game.Role-Pass.Change").replace("%amount%", Integer.toString(user.getStat(StatsStorage.StatisticType.MURDERER_PASS))).replace("%role%", Role.DETECTIVE.name())); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_CHANGE").asKey().player(player).integer(user.getStatistic("PASS_DETECTIVE")).value(Role.DETECTIVE.name()).sendPlayer(); } } }); diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/SpectateArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/SpectateArgument.java deleted file mode 100644 index f5a1491b..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/SpectateArgument.java +++ /dev/null @@ -1,30 +0,0 @@ -package plugily.projects.murdermystery.commands.arguments.admin; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.user.User; - -/** - * @author Tigerpanzer_02 - *

- * Created at 30.06.2020 - */ - -public class SpectateArgument { - - public SpectateArgument(ArgumentsRegistry registry) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("spectate", "murdermystery.admin.spectate", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mma spectate", "/mma spectate", "&7Enable/Disable permanent spectator mode\n&6Permission: &7murdermystery.admin.spectate")) { - @Override - public void execute(CommandSender sender, String[] args) { - User user = registry.getPlugin().getUserManager().getUser((Player) sender); - user.setPermanentSpectator(!user.isPermanentSpectator()); - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/TeleportArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/TeleportArgument.java deleted file mode 100644 index 3f204e49..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/TeleportArgument.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2021 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.admin; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; - -import java.util.Arrays; - -/** - * @author Tigerpanzer_02 - *

- * Created at 14.03.2021 - */ -public class TeleportArgument { - - public TeleportArgument(ArgumentsRegistry registry) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("tp", "murdermystery.admin.teleport", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mma tp &6 ", "/mma tp ", - "&7Teleport you to provided arena location\n&7Valid locations:\n&7• LOBBY - lobby location\n&7• START - starting location\n" - + "&7• END - ending location\n&6Permission: &7murdermystery.admin.teleport")) { - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length == 1) { - sender.sendMessage(registry.getPlugin().getChatManager().getPrefix() + registry.getPlugin().getChatManager().colorMessage("Commands.Type-Arena-Name")); - return; - } - if(args.length == 2) { - sender.sendMessage(registry.getPlugin().getChatManager().getPrefix() + ChatColor.RED + "Please type location type: " + Arrays.toString(LocationType.values()).replace("[", "").replace("]", "")); - return; - } - LocationType locType; - try { - locType = LocationType.valueOf(args[2].toUpperCase()); - } catch(IllegalArgumentException e) { - sender.sendMessage(registry.getPlugin().getChatManager().getPrefix() + ChatColor.RED + "Please type location type: " + Arrays.toString(LocationType.values()).replace("[", "").replace("]", "")); - return; - } - for(Arena arena : ArenaRegistry.getArenas()) { - if(arena.getId().equalsIgnoreCase(args[1])) { - teleport((Player) sender, arena, locType); - break; - } - } - } - }); - } - - private void teleport(Player player, Arena arena, LocationType locationType) { - switch(locationType) { - case LOBBY: - org.bukkit.Location lobby = arena.getLobbyLocation(); - if(lobby == null) { - player.sendMessage(ChatColor.RED + "Lobby location isn't set for this arena!"); - return; - } - player.teleport(lobby); - player.sendMessage(ChatColor.GRAY + "Teleported to LOBBY location from arena " + arena.getId()); - break; - case START: - if(arena.getLobbyLocation() == null) { - player.sendMessage(ChatColor.RED + "Start location isn't set for this arena!"); - return; - } - player.teleport(arena.getPlayerSpawnPoints().get(0)); - player.sendMessage(ChatColor.GRAY + "Teleported to START location from arena " + arena.getId()); - break; - case END: - if(arena.getLobbyLocation() == null) { - player.sendMessage(ChatColor.RED + "End location isn't set for this arena!"); - return; - } - arena.teleportToEndLocation(player); - player.sendMessage(ChatColor.GRAY + "Teleported to END location from arena " + arena.getId()); - break; - default: - break; //o.o - } - } - - public enum LocationType { - LOBBY, END, START - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/DeleteArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/DeleteArgument.java deleted file mode 100644 index fd47dcd2..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/DeleteArgument.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.admin.arena; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; - -import java.util.HashSet; -import java.util.Set; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class DeleteArgument { - - private final Set confirmations = new HashSet<>(); - - public DeleteArgument(ArgumentsRegistry registry, ChatManager chatManager) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("delete", "murdermystery.admin.delete", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mma delete &6", "/mma delete ", - "&7Deletes specified arena\n&6Permission: &7murdermystery.admin.delete")) { - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length == 1) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Type-Arena-Name")); - return; - } - Arena arena = ArenaRegistry.getArena(args[1]); - if(arena == null) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.No-Arena-Like-That")); - return; - } - if(!confirmations.contains(sender)) { - confirmations.add(sender); - Bukkit.getScheduler().runTaskLater(registry.getPlugin(), () -> confirmations.remove(sender), 20 * 10); - sender.sendMessage(chatManager.getPrefix() + chatManager.colorRawMessage("&cAre you sure you want to do this action? Type the command again &6within 10 seconds &cto confirm!")); - return; - } - confirmations.remove(sender); - ArenaManager.stopGame(true, arena); - FileConfiguration config = ConfigUtils.getConfig(registry.getPlugin(), "arenas"); - config.set("instances." + args[1], null); - ConfigUtils.saveConfig(registry.getPlugin(), config, "arenas"); - ArenaRegistry.unregisterArena(arena); - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Removed-Game-Instance")); - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/ForceStartArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/ForceStartArgument.java deleted file mode 100644 index c6796549..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/ForceStartArgument.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.admin.arena; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import plugily.projects.murdermystery.arena.ArenaUtils; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class ForceStartArgument { - - public ForceStartArgument(ArgumentsRegistry registry) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("forcestart", "murdermystery.admin.forcestart", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mma forcestart", "/mma forcestart", "&7Force starts arena you're in\n&6Permission: &7murdermystery.admin.forcestart")) { - @Override - public void execute(CommandSender sender, String[] args) { - ArenaUtils.arenaForceStart((Player) sender); - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/ReloadArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/ReloadArgument.java deleted file mode 100644 index 29aafe4a..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/ReloadArgument.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.admin.arena; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import plugily.projects.commonsbox.minecraft.serialization.InventorySerializer; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.utils.Debugger; - -import java.util.HashSet; -import java.util.Set; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class ReloadArgument { - - private final Set confirmations = new HashSet<>(); - - public ReloadArgument(ArgumentsRegistry registry, ChatManager chatManager) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("reload", "murdermystery.admin.reload", CommandArgument.ExecutorType.BOTH, - new LabelData("/mma reload", "/mma reload", "&7Reload all game arenas and configurations\n&7&lArenas will be stopped!\n&6Permission: &7murdermystery.admin.reload")) { - @Override - public void execute(CommandSender sender, String[] args) { - if(!confirmations.contains(sender)) { - confirmations.add(sender); - Bukkit.getScheduler().runTaskLater(registry.getPlugin(), () -> confirmations.remove(sender), 20 * 10); - sender.sendMessage(chatManager.getPrefix() + chatManager.colorRawMessage("&cAre you sure you want to do this action? Type the command again &6within 10 seconds &cto confirm!")); - return; - } - confirmations.remove(sender); - Debugger.debug("Initiated plugin reload by {0}", sender.getName()); - long start = System.currentTimeMillis(); - - registry.getPlugin().reloadConfig(); - LanguageManager.reloadConfig(); - - for(Arena arena : ArenaRegistry.getArenas()) { - Debugger.debug("[Reloader] Stopping {0} instance."); - long stopTime = System.currentTimeMillis(); - for(Player player : arena.getPlayers()) { - arena.doBarAction(Arena.BarAction.REMOVE, player); - arena.teleportToEndLocation(player); - if(registry.getPlugin().getConfigPreferences().getOption(ConfigPreferences.Option.INVENTORY_MANAGER_ENABLED)) { - InventorySerializer.loadInventory(registry.getPlugin(), player); - } else { - player.getInventory().clear(); - player.getInventory().setArmorContents(null); - player.getActivePotionEffects().forEach(pe -> player.removePotionEffect(pe.getType())); - player.setWalkSpeed(0.2f); - } - } - ArenaManager.stopGame(true, arena); - Debugger.debug("[Reloader] Instance {0} stopped took {1}ms", arena.getId(), System.currentTimeMillis() - stopTime); - } - ArenaRegistry.registerArenas(); - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Admin-Commands.Success-Reload")); - Debugger.debug("[Reloader] Finished reloading took {0}ms", System.currentTimeMillis() - start); - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/SpecialBlockRemoverArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/SpecialBlockRemoverArgument.java index 53f77620..dc143384 100644 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/SpecialBlockRemoverArgument.java +++ b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/SpecialBlockRemoverArgument.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,80 +18,101 @@ package plugily.projects.murdermystery.commands.arguments.admin.arena; -import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; +import plugily.projects.minigamesbox.classic.arena.PluginArena; +import plugily.projects.minigamesbox.classic.commands.arguments.data.CommandArgument; +import plugily.projects.minigamesbox.classic.commands.arguments.data.LabelData; +import plugily.projects.minigamesbox.classic.commands.arguments.data.LabeledCommandArgument; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.utils.configuration.ConfigUtils; +import plugily.projects.minigamesbox.classic.utils.serialization.LocationSerializer; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; import plugily.projects.murdermystery.arena.special.SpecialBlock; import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; import java.util.ArrayList; import java.util.List; /** * @author Tigerpanzer_02 - *

- * Created at 22.10.2020 + *

Created at 22.10.2020 */ - public class SpecialBlockRemoverArgument { public SpecialBlockRemoverArgument(ArgumentsRegistry registry) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("removeblock", "murdermystery.admin.removeblock", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mma removeblock", "/mma removeblock", "&7Removes the special block you are looking at \n&6Permission: &7murdermystery.admin.removeblock")) { - @Override - public void execute(CommandSender sender, String[] args) { - //no need for check as argument is only for players - Player player = (Player) sender; - Block targetBlock = player.getTargetBlock(null, 7); - if(targetBlock.getType() == Material.CAULDRON || targetBlock.getType() == XMaterial.ENCHANTING_TABLE.parseMaterial()) { - for(Arena arena : ArenaRegistry.getArenas()) { - //do not check arenas that could not be the case - if(arena.getSpecialBlocks().isEmpty()) { - continue; - } - if(arena.getPlayerSpawnPoints().get(0).getWorld() != player.getWorld()) { - continue; - } - //get all special blocks - for(SpecialBlock specialBlock : new ArrayList<>(arena.getSpecialBlocks())) { - //check if targetBlock is specialblock - if(specialBlock.getLocation().getBlock().equals(targetBlock)) { - //get special blocks from config - FileConfiguration config = ConfigUtils.getConfig(registry.getPlugin(), "arenas"); - //remove special block from arena - arena.getSpecialBlocks().remove(specialBlock); - //remove hologram - if(specialBlock.getArmorStandHologram() != null) { - specialBlock.getArmorStandHologram().delete(); + registry.mapArgument( + "murdermysteryadmin", + new LabeledCommandArgument( + "removeblock", + "murdermystery.admin.removeblock", + CommandArgument.ExecutorType.PLAYER, + new LabelData( + "/mma removeblock", + "/mma removeblock", + "&7Removes the special block you are looking at \n&6Permission: &7murdermystery.admin.removeblock")) { + @Override + public void execute(CommandSender sender, String[] args) { + // no need for check as argument is only for players + Player player = (Player) sender; + Block targetBlock = player.getTargetBlock(null, 7); + if(targetBlock.getType() == Material.CAULDRON + || targetBlock.getType() == XMaterial.ENCHANTING_TABLE.parseMaterial()) { + for(PluginArena arena : registry.getPlugin().getArenaRegistry().getArenas()) { + + Arena pluginArena = (Arena) registry.getPlugin().getArenaRegistry().getArena(arena.getId()); + if(arena == null) { + return; } - //remove special block from arena file - String path = targetBlock.getType() == Material.CAULDRON ? ".mystery-cauldrons" : ".confessionals"; - String serializedLoc = LocationSerializer.locationToString(specialBlock.getLocation()); - List specialBlocksType = config.getStringList("instances." + arena.getId() + path); - specialBlocksType.remove(serializedLoc); - config.set("instances." + arena.getId() + path, specialBlocksType); - //save arena config after removing special block - ConfigUtils.saveConfig(registry.getPlugin(), config, "arenas"); - player.sendMessage(ChatColor.RED + "Removed special block at loc " + serializedLoc + " from arena " + arena.getId()); - return; + // do not check arenas that could not be the case + if(pluginArena.getSpecialBlocks().isEmpty()) { + continue; + } + if(pluginArena.getPlayerSpawnPoints().get(0).getWorld() != player.getWorld()) { + continue; + } + // get all special blocks + for(SpecialBlock specialBlock : new ArrayList<>(pluginArena.getSpecialBlocks())) { + // check if targetBlock is specialblock + if(specialBlock.getLocation().getBlock().equals(targetBlock)) { + // get special blocks from config + FileConfiguration config = + ConfigUtils.getConfig(registry.getPlugin(), "arenas"); + // remove special block from arena + pluginArena.getSpecialBlocks().remove(specialBlock); + // remove hologram + if(specialBlock.getArmorStandHologram() != null) { + specialBlock.getArmorStandHologram().delete(); + } + // remove special block from arena file + String path = + targetBlock.getType() == Material.CAULDRON + ? ".mystery-cauldrons" + : ".confessionals"; + String serializedLoc = + LocationSerializer.locationToString(specialBlock.getLocation()); + List specialBlocksType = + config.getStringList("instances." + arena.getId() + path); + specialBlocksType.remove(serializedLoc); + config.set("instances." + arena.getId() + path, specialBlocksType); + // save arena config after removing special block + ConfigUtils.saveConfig(registry.getPlugin(), config, "arenas"); + new MessageBuilder("&cRemoved special block at loc " + + serializedLoc + + " from arena " + + arena.getId()).player(player).sendPlayer(); + return; + } + } } } + new MessageBuilder("&cPlease target an special block to continue!").player(player).sendPlayer(); } - } - player.sendMessage(ChatColor.RED + "Please target an special block to continue!"); - } - }); + }); } } diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/StopArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/StopArgument.java deleted file mode 100644 index dd19c86b..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/admin/arena/StopArgument.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.admin.arena; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.utils.Utils; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class StopArgument { - - public StopArgument(ArgumentsRegistry registry) { - registry.mapArgument("murdermysteryadmin", new LabeledCommandArgument("stop", "murdermystery.admin.stop", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mma stop", "/mma stop", "&7Stops the arena you're in\n&7&lYou must be in target arena!\n&6Permission: &7murdermystery.admin.stop")) { - @Override - public void execute(CommandSender sender, String[] args) { - if(!Utils.checkIsInGameInstance((Player) sender)) { - return; - } - Arena arena = ArenaRegistry.getArena((Player) sender); - if(arena.getArenaState() != ArenaState.ENDING) { - ArenaManager.stopGame(true, arena); - //todo execute success command message - } - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/data/CommandArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/data/CommandArgument.java deleted file mode 100644 index 3dea8aac..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/data/CommandArgument.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.data; - -import org.bukkit.command.CommandSender; - -import java.util.Collections; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 11.01.2019 - */ -public class CommandArgument { - - private final String argumentName; - private final List permissions; - private final ExecutorType validExecutors; - - public CommandArgument(String argumentName, String permissions, ExecutorType validExecutors) { - this.argumentName = argumentName; - this.permissions = Collections.singletonList(permissions); - this.validExecutors = validExecutors; - } - - public CommandArgument(String argumentName, List permissions, ExecutorType validExecutors) { - this.argumentName = argumentName; - this.permissions = permissions; - this.validExecutors = validExecutors; - } - - public String getArgumentName() { - return argumentName; - } - - public List getPermissions() { - return permissions; - } - - public ExecutorType getValidExecutors() { - return validExecutors; - } - - public void execute(CommandSender sender, String[] args) { - } - - public enum ExecutorType { - BOTH, CONSOLE, PLAYER - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/data/LabelData.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/data/LabelData.java deleted file mode 100644 index a2f51070..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/data/LabelData.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.data; - -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.handlers.ChatManager; - -/** - * @author Plajer - *

- * Created at 11.01.2019 - */ -public class LabelData { - - private final String text; - private String command; - private String description; - - public LabelData(String text, String command, String description) { - ChatManager chatManager = JavaPlugin.getPlugin(Main.class).getChatManager(); - this.text = chatManager.colorRawMessage(text); - this.command = command; - this.description = chatManager.colorRawMessage(description); - } - - public String getText() { - return text; - } - - public String getCommand() { - return command; - } - - public void setCommand(String command) { - this.command = command; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/data/LabeledCommandArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/data/LabeledCommandArgument.java deleted file mode 100644 index 026f96af..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/data/LabeledCommandArgument.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.data; - -import java.util.List; - -/** - * @author Plajer - *

- * Created at 11.01.2019 - */ -public class LabeledCommandArgument extends CommandArgument { - - private final LabelData labelData; - - public LabeledCommandArgument(String argumentName, List permissions, ExecutorType validExecutors, LabelData labelData) { - super(argumentName, permissions, validExecutors); - this.labelData = labelData; - } - - public LabeledCommandArgument(String argumentName, String permissions, ExecutorType validExecutors, LabelData labelData) { - super(argumentName, permissions, validExecutors); - this.labelData = labelData; - } - - /** - * @return label data of command (description and usages of command) - */ - public LabelData getLabelData() { - return labelData; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/ArenaSelectorArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/ArenaSelectorArgument.java deleted file mode 100644 index 1089c821..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/ArenaSelectorArgument.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.game; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.utils.Utils; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author 2Wild4You - *

- * Created at 09.08.2020 - */ -public class ArenaSelectorArgument implements Listener { - - private final ChatManager chatManager; - - private final Map arenaMappings = new HashMap<>(); - - public ArenaSelectorArgument(ArgumentsRegistry registry, ChatManager chatManager) { - this.chatManager = chatManager; - registry.getPlugin().getServer().getPluginManager().registerEvents(this, registry.getPlugin()); - registry.mapArgument("murdermystery", new LabeledCommandArgument("arenas", "murdermystery.arenas", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mm arenas", "/mm arenas", "&7Select an arena\n&6Permission: &7murdermystery.arenas")) { - @Override - public void execute(CommandSender sender, String[] args) { - if(ArenaRegistry.getArenas().size() == 0) { - sender.sendMessage(chatManager.colorMessage("Validator.No-Instances-Created")); - return; - } - - Player player = (Player) sender; - Inventory inventory = ComplementAccessor.getComplement().createInventory(player, Utils.serializeInt(ArenaRegistry.getArenas().size()), chatManager.colorMessage("Arena-Selector.Inv-Title")); - - int sloti = 0; - arenaMappings.clear(); - - for(Arena arena : ArenaRegistry.getArenas()) { - arenaMappings.put(sloti, arena); - ItemStack itemStack = XMaterial.matchXMaterial(registry.getPlugin().getConfig().getString("Arena-Selector.State-Item." + arena.getArenaState().getFormattedName(), "YELLOW_WOOL").toUpperCase()).orElse(XMaterial.YELLOW_WOOL).parseItem(); - if(itemStack == null) - continue; - - ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta != null) { - ComplementAccessor.getComplement().setDisplayName(itemMeta, formatItem(LanguageManager.getLanguageMessage("Arena-Selector.Item.Name"), arena)); - - java.util.List lore = LanguageManager.getLanguageList("Arena-Selector.Item.Lore"); - for(int a = 0; a < lore.size(); a++) { - lore.set(a, formatItem(lore.get(a), arena)); - } - - ComplementAccessor.getComplement().setLore(itemMeta, lore); - itemStack.setItemMeta(itemMeta); - } - inventory.addItem(itemStack); - sloti++; - } - player.openInventory(inventory); - } - }); - } - - private String formatItem(String string, Arena arena) { - String formatted = string; - formatted = StringUtils.replace(formatted, "%mapname%", arena.getMapName()); - int maxPlayers = arena.getMaximumPlayers(); - if(arena.getPlayers().size() >= maxPlayers) { - formatted = StringUtils.replace(formatted, "%state%", chatManager.colorMessage("Signs.Game-States.Full-Game")); - } else { - formatted = StringUtils.replace(formatted, "%state%", arena.getArenaState().getPlaceholder()); - } - formatted = StringUtils.replace(formatted, "%playersize%", Integer.toString(arena.getPlayers().size())); - formatted = StringUtils.replace(formatted, "%maxplayers%", Integer.toString(maxPlayers)); - formatted = chatManager.colorRawMessage(formatted); - return formatted; - } - - @EventHandler - public void onArenaSelectorMenuClick(InventoryClickEvent e) { - if(!ComplementAccessor.getComplement().getTitle(e.getView()).equals(chatManager.colorMessage("Arena-Selector.Inv-Title"))) { - return; - } - ItemStack currentItem = e.getCurrentItem(); - if(currentItem == null || !currentItem.hasItemMeta()) { - return; - } - Player player = (Player) e.getWhoClicked(); - player.closeInventory(); - - Arena arena = arenaMappings.get(e.getRawSlot()); - if(arena != null) { - ArenaManager.joinAttempt(player, arena); - } else { - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.No-Arena-Like-That")); - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/CreateArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/CreateArgument.java deleted file mode 100644 index 7d0c196c..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/CreateArgument.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.game; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.special.SpecialBlock; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class CreateArgument { - - private final ArgumentsRegistry registry; - - public CreateArgument(ArgumentsRegistry registry, ChatManager chatManager) { - this.registry = registry; - registry.mapArgument("murdermystery", new LabeledCommandArgument("create", "murdermystery.admin.create", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mm create &6", "/mm create ", "&7Create new arena\n&6Permission: &7murdermystery.admin.create")) { - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length == 1) { - sender.sendMessage(chatManager.colorMessage("Commands.Type-Arena-Name")); - return; - } - for(Arena arena : ArenaRegistry.getArenas()) { - if(arena.getId().equalsIgnoreCase(args[1])) { - sender.sendMessage(ChatColor.DARK_RED + "Arena with that ID already exists!"); - sender.sendMessage(ChatColor.DARK_RED + "Usage: /mm create "); - return; - } - } - if(ConfigUtils.getConfig(registry.getPlugin(), "arenas").contains("instances." + args[1])) { - sender.sendMessage(ChatColor.DARK_RED + "Instance/Arena already exists! Use another ID or delete it first!"); - } else { - createInstanceInConfig(args[1], ((Player) sender).getWorld().getName()); - sender.sendMessage(ChatColor.BOLD + "------------------------------------------"); - sender.sendMessage(ChatColor.YELLOW + " Instance " + args[1] + " created!"); - sender.sendMessage(""); - sender.sendMessage(ChatColor.GREEN + "Edit this arena via " + ChatColor.GOLD + "/mm " + args[1] + " edit" + ChatColor.GREEN + "!"); - sender.sendMessage(ChatColor.GOLD + "Don't know where to start? Check out tutorial video:"); - sender.sendMessage(ChatColor.GOLD + SetupInventory.VIDEO_LINK); - sender.sendMessage(ChatColor.BOLD + "------------------------------------------- "); - } - } - }); - } - - private void createInstanceInConfig(String id, String worldName) { - String path = "instances." + id + "."; - FileConfiguration config = ConfigUtils.getConfig(registry.getPlugin(), "arenas"); - Location worldSpawn = Bukkit.getServer().getWorlds().get(0).getSpawnLocation(); - LocationSerializer.saveLoc(registry.getPlugin(), config, "arenas", path + "lobbylocation", worldSpawn); - LocationSerializer.saveLoc(registry.getPlugin(), config, "arenas", path + "Startlocation", worldSpawn); - LocationSerializer.saveLoc(registry.getPlugin(), config, "arenas", path + "Endlocation", worldSpawn); - config.set(path + "playerspawnpoints", new ArrayList<>()); - config.set(path + "goldspawnpoints", new ArrayList<>()); - config.set(path + "minimumplayers", 2); - config.set(path + "maximumplayers", 10); - config.set(path + "playerpermurderer", 5); - config.set(path + "playerperdetective", 7); - config.set(path + "mapname", id); - config.set(path + "signs", new ArrayList<>()); - config.set(path + "isdone", false); - config.set(path + "world", worldName); - config.set(path + "mystery-cauldrons", new ArrayList<>()); - config.set(path + "confessionals", new ArrayList<>()); - config.set(path + "spawngoldtime", 5); - config.set(path + "hidechances", false); - ConfigUtils.saveConfig(registry.getPlugin(), config, "arenas"); - - Arena arena = new Arena(id); - - List playerSpawnPoints = new ArrayList<>(); - for(String loc : config.getStringList(path + "playerspawnpoints")) { - playerSpawnPoints.add(LocationSerializer.getLocation(loc)); - } - arena.setPlayerSpawnPoints(playerSpawnPoints); - List goldSpawnPoints = new ArrayList<>(); - for(String loc : config.getStringList(path + "goldspawnpoints")) { - goldSpawnPoints.add(LocationSerializer.getLocation(loc)); - } - arena.setGoldSpawnPoints(goldSpawnPoints); - - List specialBlocks = new ArrayList<>(); - if(config.isSet("instances." + arena.getId() + ".mystery-cauldrons")) { - for(String loc : config.getStringList("instances." + arena.getId() + ".mystery-cauldrons")) { - specialBlocks.add(new SpecialBlock(LocationSerializer.getLocation(loc), SpecialBlock.SpecialBlockType.MYSTERY_CAULDRON)); - } - } - specialBlocks.forEach(arena::loadSpecialBlock); - - arena.setMinimumPlayers(config.getInt(path + "minimumplayers")); - arena.setMaximumPlayers(config.getInt(path + "maximumplayers")); - arena.setSpawnGoldTime(config.getInt(path + "spawngoldtime", 5)); - arena.setHideChances(config.getBoolean(path + "hidechances", false)); - arena.setDetectives(config.getInt(path + "playerperdetective")); - arena.setMurderers(config.getInt(path + "playerpermurderer")); - arena.setMapName(config.getString(path + "mapname")); - arena.setLobbyLocation(LocationSerializer.getLocation(config.getString(path + "lobbylocation"))); - arena.setEndLocation(LocationSerializer.getLocation(config.getString(path + "Endlocation"))); - arena.setReady(false); - - ArenaRegistry.registerArena(arena); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/JoinArguments.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/JoinArguments.java deleted file mode 100644 index ff3e23ca..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/JoinArguments.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.game; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; - -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; -import java.util.stream.Collectors; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class JoinArguments { - - public JoinArguments(ArgumentsRegistry registry, ChatManager chatManager) { - //join argument - registry.mapArgument("murdermystery", new CommandArgument("join", "", CommandArgument.ExecutorType.PLAYER) { - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length == 1) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Type-Arena-Name")); - return; - } - - if(!ArenaRegistry.getArenas().isEmpty() && args[1].equalsIgnoreCase("maxplayers") && ArenaRegistry.getArena("maxplayers") == null) { - if(ArenaRegistry.getArenaPlayersOnline() == 0) { - ArenaManager.joinAttempt((Player) sender, ArenaRegistry.getArenas().get(ThreadLocalRandom.current().nextInt(ArenaRegistry.getArenas().size()))); - return; - } - - Map arenas = new HashMap<>(); - for(Arena arena : ArenaRegistry.getArenas()) { - arenas.put(arena, arena.getPlayers().size()); - } - - LinkedHashMap orderedArenas = new LinkedHashMap<>(); - arenas.entrySet() - .stream() - .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) - .forEachOrdered(x -> orderedArenas.put(x.getKey(), x.getValue())); - - if(!orderedArenas.isEmpty()) { - Arena arena = orderedArenas.keySet().stream().findFirst().get(); - ArenaManager.joinAttempt((Player) sender, arena); - return; - } - return; - } - - for(Arena arena : ArenaRegistry.getArenas()) { - if(args[1].equalsIgnoreCase(arena.getId())) { - ArenaManager.joinAttempt((Player) sender, arena); - return; - } - } - - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.No-Arena-Like-That")); - } - }); - - //random join argument, register only for multi arena - if(!registry.getPlugin().getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - registry.mapArgument("murdermystery", new CommandArgument("randomjoin", "", CommandArgument.ExecutorType.PLAYER) { - @Override - public void execute(CommandSender sender, String[] args) { - //check starting arenas -> random - List arenas = ArenaRegistry.getArenas().stream().filter(arena -> arena.getArenaState() == ArenaState.STARTING && arena.getPlayers().size() < arena.getMaximumPlayers()).collect(Collectors.toList()); - if(!arenas.isEmpty()) { - Arena arena = arenas.get(ThreadLocalRandom.current().nextInt(arenas.size())); - ArenaManager.joinAttempt((Player) sender, arena); - return; - } - //check waiting arenas -> random - arenas = ArenaRegistry.getArenas().stream().filter(arena -> (arena.getArenaState() == ArenaState.WAITING_FOR_PLAYERS || arena.getArenaState() == ArenaState.STARTING) - && arena.getPlayers().size() < arena.getMaximumPlayers()).collect(Collectors.toList()); - if(!arenas.isEmpty()) { - Arena arena = arenas.get(ThreadLocalRandom.current().nextInt(arenas.size())); - ArenaManager.joinAttempt((Player) sender, arena); - return; - } - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.No-Free-Arenas")); - } - }); - } - } -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/LeaderboardArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/LeaderboardArgument.java deleted file mode 100644 index af953b87..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/LeaderboardArgument.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.game; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.completion.CompletableArgument; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.user.data.MysqlManager; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.UUID; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class LeaderboardArgument { - - private final ArgumentsRegistry registry; - private final ChatManager chatManager; - - public LeaderboardArgument(ArgumentsRegistry registry, ChatManager chatManager) { - this.registry = registry; - this.chatManager = chatManager; - - List stats = new ArrayList<>(); - for(StatsStorage.StatisticType value : StatsStorage.StatisticType.values()) { - if(value.isPersistent()) { - stats.add(value.name().toLowerCase()); - } - } - registry.getTabCompletion().registerCompletion(new CompletableArgument("murdermystery", "top", stats)); - registry.mapArgument("murdermystery", new CommandArgument("top", "", CommandArgument.ExecutorType.PLAYER) { - @Override - public void execute(CommandSender sender, String[] args) { - if(args.length == 1) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Statistics.Type-Name")); - return; - } - - StatsStorage.StatisticType statisticType; - - try { - statisticType = StatsStorage.StatisticType.valueOf(args[1].toUpperCase()); - } catch(IllegalArgumentException e) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Statistics.Invalid-Name")); - return; - } - - if(!statisticType.isPersistent()) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Statistics.Invalid-Name")); - return; - } - - printLeaderboard(sender, statisticType); - } - }); - } - - private void printLeaderboard(CommandSender sender, StatsStorage.StatisticType statisticType) { - java.util.Map stats = (LinkedHashMap) StatsStorage.getStats(statisticType); - - sender.sendMessage(chatManager.colorMessage("Commands.Statistics.Header")); - - String statistic = StringUtils.capitalize(statisticType.toString().toLowerCase().replace("_", " ")); - Object[] array = stats.keySet().toArray(); - UUID current = (UUID) array[array.length - 1]; - - for(int i = 0; i < 10; i++) { - try { - sender.sendMessage(formatMessage(statistic, Bukkit.getOfflinePlayer(current).getName(), i + 1, stats.remove(current))); - } catch(IndexOutOfBoundsException ex) { - sender.sendMessage(formatMessage(statistic, "Empty", i + 1, 0)); - } catch(NullPointerException ex) { - if(registry.getPlugin().getConfigPreferences().getOption(ConfigPreferences.Option.DATABASE_ENABLED)) { - try(Connection connection = registry.getPlugin().getMysqlDatabase().getConnection()) { - Statement statement = connection.createStatement(); - ResultSet set = statement.executeQuery("SELECT name FROM " + ((MysqlManager) registry.getPlugin().getUserManager().getDatabase()).getTableName() + " WHERE UUID='" + current.toString() + "'"); - if(set.next()) { - sender.sendMessage(formatMessage(statistic, set.getString(1), i + 1, stats.get(current))); - continue; - } - } catch(SQLException ignored) { - //it has failed second time, cannot continue - } - } - sender.sendMessage(formatMessage(statistic, "Unknown Player", i + 1, stats.get(current))); - } - } - } - - private String formatMessage(String statisticName, String playerName, int position, int value) { - String message = chatManager.colorMessage("Commands.Statistics.Format"); - message = StringUtils.replace(message, "%position%", Integer.toString(position)); - message = StringUtils.replace(message, "%name%", playerName); - message = StringUtils.replace(message, "%value%", Integer.toString(value)); - message = StringUtils.replace(message, "%statistic%", statisticName); - return message; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/LeaveArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/LeaveArgument.java deleted file mode 100644 index b4acec92..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/LeaveArgument.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.game; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.utils.Debugger; -import plugily.projects.murdermystery.utils.Utils; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class LeaveArgument { - - public LeaveArgument(ArgumentsRegistry registry, ChatManager chatManager) { - registry.mapArgument("murdermystery", new CommandArgument("leave", "", CommandArgument.ExecutorType.PLAYER) { - @Override - public void execute(CommandSender sender, String[] args) { - if(!registry.getPlugin().getConfig().getBoolean("Disable-Leave-Command")) { - Player player = (Player) sender; - if(!Utils.checkIsInGameInstance(player)) { - return; - } - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Teleported-To-The-Lobby", player)); - if(registry.getPlugin().getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - registry.getPlugin().getBungeeManager().connectToHub(player); - Debugger.debug("{0} was teleported to the Hub server", player.getName()); - return; - } - Arena arena = ArenaRegistry.getArena(player); - ArenaManager.leaveAttempt(player, arena); - Debugger.debug("{0} has left the arena {1}! Teleported to end location.", player.getName(), arena.getId()); - } - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/RoleSelectorArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/RoleSelectorArgument.java index 3426f69b..80bffc3d 100644 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/RoleSelectorArgument.java +++ b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/RoleSelectorArgument.java @@ -1,80 +1,93 @@ +/* + * MurderMystery - Find the murderer, kill him and survive! + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + package plugily.projects.murdermystery.commands.arguments.game; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.inventoryframework.gui.GuiItem; -import plugily.projects.inventoryframework.gui.type.ChestGui; -import plugily.projects.inventoryframework.pane.OutlinePane; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; +import plugily.projects.minigamesbox.classic.PluginMain; +import plugily.projects.minigamesbox.classic.commands.arguments.data.CommandArgument; +import plugily.projects.minigamesbox.classic.commands.arguments.data.LabelData; +import plugily.projects.minigamesbox.classic.commands.arguments.data.LabeledCommandArgument; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.helper.ItemBuilder; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; +import plugily.projects.minigamesbox.inventory.common.item.SimpleClickableItem; +import plugily.projects.minigamesbox.inventory.normal.NormalFastInv; import plugily.projects.murdermystery.arena.role.Role; import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.commands.arguments.data.LabelData; -import plugily.projects.murdermystery.commands.arguments.data.LabeledCommandArgument; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.user.User; -import plugily.projects.murdermystery.utils.Utils; +import java.util.ArrayList; +import java.util.List; import java.util.stream.Collectors; public class RoleSelectorArgument implements Listener { - public RoleSelectorArgument(ArgumentsRegistry registry) { - registry.mapArgument("murdermystery", new LabeledCommandArgument("roleselector", "murdermystery.roleselector", CommandArgument.ExecutorType.PLAYER, - new LabelData("/mm roleselector", "/mm roleselector", "&7Select a role\n&6Permission: &7murdermystery.roleselector")) { + registry.mapArgument("murdermystery", new LabeledCommandArgument("roleselector", "murdermystery.command.roleselector", CommandArgument.ExecutorType.PLAYER, + new LabelData("/mm roleselector", "/mm roleselector", "&7Select a role\n&6Permission: &7murdermystery.command.roleselector")) { @Override public void execute(CommandSender sender, String[] args) { Player player = (Player) sender; - if(!Utils.checkIsInGameInstance(player)) { - return; + + if(registry.getPlugin().getBukkitHelper().checkIsInGameInstance(player)) { + openRolePassMenu(player, registry.getPlugin()); } - openRolePassMenu((Player) sender, registry.getPlugin()); } }); } - public static void openRolePassMenu(Player player, Main plugin) { - int rows = Utils.serializeInt(Role.values().length) / 9; - ChestGui gui = new ChestGui(rows, plugin.getChatManager().colorMessage("In-Game.Role-Pass.Menu-Name")); - gui.setOnGlobalClick(event -> event.setCancelled(true)); - OutlinePane pane = new OutlinePane(9, rows); - gui.addPane(pane); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.IRON_SWORD.parseMaterial()) - .name(plugin.getChatManager().colorMessage("In-Game.Role-Pass.Role.Murderer.Name")) - .lore(LanguageManager.getLanguageList("In-Game.Role-Pass.Role.Murderer.Lore").stream().map(string -> string.replace("%amount%", Integer.toString(plugin.getUserManager().getUser(player).getStat(StatsStorage.StatisticType.DETECTIVE_PASS)))).collect(Collectors.toList())) - .build(), event -> { - event.setCancelled(true); + public static void openRolePassMenu(Player player, PluginMain plugin) { + NormalFastInv gui = new NormalFastInv(plugin.getBukkitHelper().serializeInt(Role.values().length), new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_NAME").asKey().build()); + List descriptionMurderer = new ArrayList<>(); + plugin.getLanguageManager().getLanguageListFromKey("IN_GAME_MESSAGES_ARENA_PASS_ROLE_MURDERER_LORE").forEach(string -> descriptionMurderer.add(new MessageBuilder(string).integer(plugin.getUserManager().getUser(player).getStatistic("PASS_MURDERER")).build())); + gui.addItem(new SimpleClickableItem(new ItemBuilder(XMaterial.IRON_SWORD.parseMaterial()) + .name(new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_ROLE_MURDERER_NAME").asKey().build()) + .lore(descriptionMurderer) + .build(), event -> { User user = plugin.getUserManager().getUser(player); - if(user.getStat(StatsStorage.StatisticType.MURDERER_PASS) <= 0) { - player.sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("In-Game.Role-Pass.Fail").replace("%role%", Role.MURDERER.name())); + if(user.getStatistic("PASS_MURDERER") <= 0) { + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_FAIL").asKey().player(player).value(Role.MURDERER.name()).sendPlayer(); return; } - user.addStat(StatsStorage.StatisticType.MURDERER_PASS, -1); - user.addStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, 999); - player.sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("In-Game.Role-Pass.Success").replace("%role%", Role.MURDERER.name())); + user.adjustStatistic("PASS_MURDERER", -1); + user.adjustStatistic("CONTRIBUTION_MURDERER", 999999999); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_SUCCESS").asKey().player(player).value(Role.MURDERER.name()).sendPlayer(); })); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.BOW.parseMaterial()) - .name(plugin.getChatManager().colorMessage("In-Game.Role-Pass.Role.Detective.Name")) - .lore(LanguageManager.getLanguageList("In-Game.Role-Pass.Role.Detective.Lore").stream().map(string -> string.replace("%amount%", Integer.toString(plugin.getUserManager().getUser(player).getStat(StatsStorage.StatisticType.DETECTIVE_PASS)))).collect(Collectors.toList())) - .build(), event -> { - event.setCancelled(true); + List descriptionDetective = new ArrayList<>(); + plugin.getLanguageManager().getLanguageListFromKey("IN_GAME_MESSAGES_ARENA_PASS_ROLE_DETECTIVE_LORE").forEach(string -> descriptionDetective.add(new MessageBuilder(string).integer(plugin.getUserManager().getUser(player).getStatistic("PASS_DETECTIVE")).build())); + gui.addItem(new SimpleClickableItem(new ItemBuilder(XMaterial.BOW.parseMaterial()) + .name(new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_ROLE_DETECTIVE_NAME").asKey().build()) + .lore(descriptionDetective) + .build(), event -> { User user = plugin.getUserManager().getUser(player); - if(user.getStat(StatsStorage.StatisticType.DETECTIVE_PASS) <= 0) { - player.sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("In-Game.Role-Pass.Fail").replace("%role%", Role.DETECTIVE.name())); + if(user.getStatistic("PASS_DETECTIVE") <= 0) { + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_FAIL").asKey().player(player).value(Role.DETECTIVE.name()).sendPlayer(); return; } - user.addStat(StatsStorage.StatisticType.DETECTIVE_PASS, -1); - user.addStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, 999); - player.sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("In-Game.Role-Pass.Success").replace("%role%", Role.DETECTIVE.name())); + user.adjustStatistic("PASS_DETECTIVE", -1); + user.adjustStatistic("CONTRIBUTION_DETECTIVE", 999999999); + new MessageBuilder("IN_GAME_MESSAGES_ARENA_PASS_SUCCESS").asKey().player(player).value(Role.DETECTIVE.name()).sendPlayer(); })); - gui.show(player); + gui.refresh(); + gui.open(player); } } diff --git a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/StatsArgument.java b/src/main/java/plugily/projects/murdermystery/commands/arguments/game/StatsArgument.java deleted file mode 100644 index f905dad1..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/arguments/game/StatsArgument.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.arguments.game; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.user.User; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class StatsArgument { - - public StatsArgument(ArgumentsRegistry registry, ChatManager chatManager) { - registry.mapArgument("murdermystery", new CommandArgument("stats", "", CommandArgument.ExecutorType.PLAYER) { - @Override - public void execute(@NotNull CommandSender sender, String[] args) { - Player player = args.length == 2 ? Bukkit.getPlayerExact(args[1]) : (Player) sender; - if(player == null) { - sender.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Commands.Admin-Commands.Player-Not-Found")); - return; - } - if(player.equals(sender)) { - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Header", player)); - } else { - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Header-Other", player).replace("%player%", player.getName())); - } - User user = registry.getPlugin().getUserManager().getUser(player); - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Kills", player) + user.getStat(StatsStorage.StatisticType.KILLS)); - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Deaths", player) + user.getStat(StatsStorage.StatisticType.DEATHS)); - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Wins", player) + user.getStat(StatsStorage.StatisticType.WINS)); - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Loses", player) + user.getStat(StatsStorage.StatisticType.LOSES)); - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Games-Played", player) + user.getStat(StatsStorage.StatisticType.GAMES_PLAYED)); - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Highest-Score", player) + user.getStat(StatsStorage.StatisticType.HIGHEST_SCORE)); - sender.sendMessage(chatManager.colorMessage("Commands.Stats-Command.Footer", player)); - } - }); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/completion/CompletableArgument.java b/src/main/java/plugily/projects/murdermystery/commands/completion/CompletableArgument.java deleted file mode 100644 index 70276c51..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/completion/CompletableArgument.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.completion; - -import java.util.List; - -/** - * @author Plajer - *

- * Created at 18.05.2019 - */ -public class CompletableArgument { - - private final String mainCommand; - private final String argument; - private final List completions; - - public CompletableArgument(String mainCommand, String argument, List completions) { - this.mainCommand = mainCommand; - this.argument = argument; - this.completions = completions; - } - - /** - * @return main command of the argument - */ - public String getMainCommand() { - return mainCommand; - } - - /** - * @return argument name - */ - public String getArgument() { - return argument; - } - - /** - * @return all possible completions for this command argument - */ - public List getCompletions() { - return completions; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/commands/completion/TabCompletion.java b/src/main/java/plugily/projects/murdermystery/commands/completion/TabCompletion.java deleted file mode 100644 index 659f02bc..00000000 --- a/src/main/java/plugily/projects/murdermystery/commands/completion/TabCompletion.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.commands.completion; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.commands.arguments.ArgumentsRegistry; -import plugily.projects.murdermystery.commands.arguments.data.CommandArgument; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - * @author Plajer - *

- * Created at 05.08.2018 - */ -public class TabCompletion implements TabCompleter { - - private final List registeredCompletions = new ArrayList<>(); - private final ArgumentsRegistry registry; - - public TabCompletion(ArgumentsRegistry registry) { - this.registry = registry; - } - - public void registerCompletion(CompletableArgument completion) { - registeredCompletions.add(completion); - } - - @Override - public List onTabComplete(CommandSender sender, Command cmd, String label, String[] args) { - List cmds = new ArrayList<>(); - - if(cmd.getName().equalsIgnoreCase("murdermysteryadmin")) { - if(args.length == 1) { - cmds.addAll(registry.getMappedArguments().get("murdermysteryadmin").stream().map(CommandArgument::getArgumentName) - .collect(Collectors.toList())); - } else if(args.length == 2 && args[0].equalsIgnoreCase("delete")) { - cmds.addAll(ArenaRegistry.getArenas().stream().map(Arena::getId).collect(Collectors.toList())); - } - } - - if(cmd.getName().equalsIgnoreCase("murdermystery")) { - if(args.length == 2 && args[0].equalsIgnoreCase("join")) { - cmds.addAll(ArenaRegistry.getArenas().stream().map(Arena::getId).collect(Collectors.toList())); - } else if(args.length == 1) { - cmds.addAll(registry.getMappedArguments().get("murdermystery").stream().map(CommandArgument::getArgumentName) - .collect(Collectors.toList())); - } - } - - // Completes the player names - if(cmds.isEmpty()) { - for(CompletableArgument completion : registeredCompletions) { - if(!cmd.getName().equalsIgnoreCase(completion.getMainCommand()) || !completion.getArgument().equalsIgnoreCase(args[0])) { - continue; - } - return completion.getCompletions(); - } - - return null; - } - - return cmds; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/events/ChatEvents.java b/src/main/java/plugily/projects/murdermystery/events/ChatEvents.java deleted file mode 100644 index 34fdb1e6..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/ChatEvents.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events; - -import me.clip.placeholderapi.PlaceholderAPI; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.user.User; - -import java.util.regex.Pattern; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class ChatEvents implements Listener { - - private final Main plugin; - private final String[] regexChars = {"$", "\\"}; - - public ChatEvents(Main plugin) { - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @EventHandler(ignoreCancelled = true) - public void onChatIngame(AsyncPlayerChatEvent event) { - Arena arena = ArenaRegistry.getArena(event.getPlayer()); - if(arena == null) { - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DISABLE_SEPARATE_CHAT)) { - for(Arena loopArena : ArenaRegistry.getArenas()) { - for(Player player : loopArena.getPlayers()) { - event.getRecipients().remove(player); - } - } - } - return; - } - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.CHAT_FORMAT_ENABLED)) { - String eventMessage = event.getMessage(); - for(String regexChar : regexChars) { - if(eventMessage.contains(regexChar)) { - eventMessage = eventMessage.replaceAll(Pattern.quote(regexChar), ""); - } - } - String message = formatChatPlaceholders(LanguageManager.getLanguageMessage("In-Game.Game-Chat-Format"), plugin.getUserManager().getUser(event.getPlayer()), eventMessage); - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DISABLE_SEPARATE_CHAT)) { - event.setCancelled(true); - boolean dead = !arena.getPlayersLeft().contains(event.getPlayer()); - for(Player player : arena.getPlayers()) { - if(dead && arena.getPlayersLeft().contains(player)) { - continue; - } - if(dead) { - String prefix = formatChatPlaceholders(LanguageManager.getLanguageMessage("In-Game.Game-Death-Format"), plugin.getUserManager().getUser(event.getPlayer()), null); - player.sendMessage(prefix + message); - } else { - player.sendMessage(message); - } - } - Bukkit.getConsoleSender().sendMessage(message); - } else { - event.setMessage(message); - } - } - } - - private String formatChatPlaceholders(String message, User user, String saidMessage) { - String formatted = message; - formatted = plugin.getChatManager().colorRawMessage(formatted); - formatted = StringUtils.replace(formatted, "%player%", user.getPlayer().getName()); - formatted = StringUtils.replace(formatted, "%message%", ChatColor.stripColor(saidMessage)); - if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) { - formatted = PlaceholderAPI.setPlaceholders(user.getPlayer(), formatted); - } - return formatted; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/events/Events.java b/src/main/java/plugily/projects/murdermystery/events/Events.java deleted file mode 100644 index 3f8117df..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/Events.java +++ /dev/null @@ -1,377 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events; - -import org.bukkit.Location; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Painting; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.player.PlayerArmorStandManipulateEvent; -import org.bukkit.event.player.PlayerBedEnterEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerDropItemEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.EulerAngle; -import org.bukkit.util.Vector; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.compat.events.api.CBPlayerInteractEvent; -import plugily.projects.commonsbox.minecraft.compat.events.api.CBPlayerSwapHandItemsEvent; -import plugily.projects.commonsbox.minecraft.compat.xseries.XSound; -import plugily.projects.commonsbox.minecraft.hologram.HologramManager; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaUtils; -import plugily.projects.murdermystery.arena.role.Role; -import plugily.projects.murdermystery.commands.arguments.game.RoleSelectorArgument; -import plugily.projects.murdermystery.handlers.items.SpecialItemManager; -import plugily.projects.murdermystery.user.User; -import plugily.projects.murdermystery.utils.Utils; - -/** - * @author Plajer - *

- * Created at 05.08.2018 - */ -public class Events implements Listener { - - private final Main plugin; - - public Events(Main plugin) { - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @EventHandler - public void onItemSwap(CBPlayerSwapHandItemsEvent e) { - if(ArenaRegistry.isInArena(e.getPlayer())) { - e.setCancelled(true); - } - } - - @EventHandler - public void onDrop(PlayerDropItemEvent event) { - if(ArenaRegistry.isInArena(event.getPlayer())) { - event.setCancelled(true); - } - } - - @EventHandler - public void onSwordThrow(PlayerInteractEvent e) { - if(e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.PHYSICAL) { - return; - } - Arena arena = ArenaRegistry.getArena(e.getPlayer()); - if(arena == null) { - return; - } - if(!Role.isRole(Role.MURDERER, e.getPlayer(), arena)) { - return; - } - Player attacker = e.getPlayer(); - if(VersionUtils.getItemInHand(attacker).getType() != plugin.getConfigPreferences().getMurdererSword().getType()) { - return; - } - User attackerUser = plugin.getUserManager().getUser(attacker); - if(attackerUser.getCooldown("sword_shoot") > 0) { - return; - } - - int swordFlyCooldown = plugin.getConfig().getInt("Murderer-Sword-Fly-Cooldown", 5); - - attackerUser.setCooldown("sword_shoot", swordFlyCooldown); - - if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_9_R1)) { - attackerUser.setCooldown("sword_attack", (plugin.getConfig().getInt("Murderer-Sword-Attack-Cooldown", 1))); - } else { - attacker.setCooldown(plugin.getConfigPreferences().getMurdererSword().getType(), 20 * (plugin.getConfig().getInt("Murderer-Sword-Attack-Cooldown", 1))); - } - - createFlyingSword(arena, attacker, attackerUser); - Utils.applyActionBarCooldown(attacker, swordFlyCooldown); - } - - private void createFlyingSword(Arena arena, Player attacker, User attackerUser) { - Location loc = attacker.getLocation(); - Vector vec = loc.getDirection(); - vec.normalize().multiply(plugin.getConfig().getDouble("Murderer-Sword-Speed", 0.65)); - Location standStart = Utils.rotateAroundAxisY(new Vector(1.0D, 0.0D, 0.0D), loc.getYaw()).toLocation(attacker.getWorld()).add(loc); - standStart.setYaw(loc.getYaw()); - ArmorStand stand = (ArmorStand) attacker.getWorld().spawnEntity(standStart, EntityType.ARMOR_STAND); - stand.setVisible(false); - if(ServerVersion.Version.isCurrentHigher(ServerVersion.Version.v1_8_R3)) { - stand.setInvulnerable(true); - stand.setSilent(true); - } - - VersionUtils.setItemInHand(stand, plugin.getConfigPreferences().getMurdererSword()); - - stand.setRightArmPose(new EulerAngle(Math.toRadians(350.0), Math.toRadians(loc.getPitch() * -1.0), Math.toRadians(90.0))); - VersionUtils.setCollidable(stand, false); - - stand.setGravity(false); - stand.setRemoveWhenFarAway(true); - - if(ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_8_R3)) { - stand.setMarker(true); - } - - Location initialise = Utils.rotateAroundAxisY(new Vector(-0.8D, 1.45D, 0.0D), loc.getYaw()).toLocation(attacker.getWorld()).add(standStart).add(Utils.rotateAroundAxisY(Utils.rotateAroundAxisX(new Vector(0.0D, 0.0D, 1.0D), loc.getPitch()), loc.getYaw())); - int maxRange = plugin.getConfig().getInt("Murderer-Sword-Fly-Range", 20); - double maxHitRange = plugin.getConfig().getDouble("Murderer-Sword-Fly-Hit-Range", 0.5); - new BukkitRunnable() { - @Override - public void run() { - stand.teleport(standStart.add(vec)); - initialise.add(vec); - initialise.getWorld().getNearbyEntities(initialise, maxHitRange, maxHitRange, maxHitRange).forEach(entity -> { - if(entity instanceof Player) { - Player victim = (Player) entity; - if(ArenaRegistry.isInArena(victim) && !plugin.getUserManager().getUser(victim).isSpectator() && !victim.equals(attacker)) { - killBySword(arena, attackerUser, victim); - cancel(); - stand.remove(); - } - } - }); - if(loc.distance(initialise) > maxRange || initialise.getBlock().getType().isSolid()) { - cancel(); - stand.remove(); - } - } - }.runTaskTimer(plugin, 0, 1); - } - - private void killBySword(Arena arena, User attackerUser, Player victim) { - Arena victimArena = ArenaRegistry.getArena(victim); - - //check if victim is murderer - if(Role.isRole(Role.MURDERER, victim, victimArena)) { - return; - } - XSound.ENTITY_PLAYER_DEATH.play(victim.getLocation(), 50, 1); - victim.damage(100.0); - VersionUtils.sendTitles(victim, plugin.getChatManager().colorMessage("In-Game.Messages.Game-End-Messages.Titles.Died", victim), - plugin.getChatManager().colorMessage("In-Game.Messages.Game-End-Messages.Subtitles.Murderer-Killed-You", victim), 5, 40, 5); - attackerUser.addStat(StatsStorage.StatisticType.LOCAL_KILLS, 1); - attackerUser.addStat(StatsStorage.StatisticType.KILLS, 1); - ArenaUtils.addScore(attackerUser, ArenaUtils.ScoreAction.KILL_PLAYER, 0); - if(Role.isRole(Role.ANY_DETECTIVE, victim, victimArena) && arena.lastAliveDetective()) { - if(Role.isRole(Role.FAKE_DETECTIVE, victim, victimArena)) { - arena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, null); - } - ArenaUtils.dropBowAndAnnounce(arena, victim); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onCommandExecute(PlayerCommandPreprocessEvent event) { - Arena arena = ArenaRegistry.getArena(event.getPlayer()); - if(arena == null) { - return; - } - if(!plugin.getConfig().getBoolean("Block-Commands-In-Game", true)) { - return; - } - - if(event.getPlayer().isOp() || event.getPlayer().hasPermission("murdermystery.admin") || event.getPlayer().hasPermission("murdermystery.command.bypass")) { - return; - } - - String command = event.getMessage().substring(1); - int index = command.indexOf(' '); - command = (index >= 0 ? command.substring(0, index) : command); - for(String msg : plugin.getConfig().getStringList("Whitelisted-Commands")) { - if(command.equalsIgnoreCase(msg)) { - return; - } - } - - if(command.equalsIgnoreCase("mm") || command.equalsIgnoreCase("murdermystery") - || event.getMessage().contains("murdermysteryadmin") || event.getMessage().contains("leave") - || command.equalsIgnoreCase("stats") || command.equalsIgnoreCase("mma")) { - return; - } - event.setCancelled(true); - event.getPlayer().sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("In-Game.Only-Command-Ingame-Is-Leave")); - } - - @EventHandler - public void onInGameInteract(PlayerInteractEvent event) { - Arena arena = ArenaRegistry.getArena(event.getPlayer()); - if(arena == null || event.getClickedBlock() == null) { - return; - } - if(event.getClickedBlock().getType() == XMaterial.PAINTING.parseMaterial() || event.getClickedBlock().getType() == XMaterial.FLOWER_POT.parseMaterial()) { - event.setCancelled(true); - } - } - - @EventHandler - public void onInGameBedEnter(PlayerBedEnterEvent event) { - if(ArenaRegistry.isInArena(event.getPlayer())) { - event.setCancelled(true); - } - } - - @EventHandler - public void onSpecialItem(CBPlayerInteractEvent event) { - if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.PHYSICAL) { - return; - } - Arena arena = ArenaRegistry.getArena(event.getPlayer()); - ItemStack itemStack = VersionUtils.getItemInHand(event.getPlayer()); - if(arena == null || !Utils.isNamed(itemStack)) { - return; - } - String key = plugin.getSpecialItemManager().getRelatedSpecialItem(itemStack).getName(); - if(key == null) { - return; - } - if(key.equalsIgnoreCase(SpecialItemManager.SpecialItems.ROLE_PASS.getName())) { - event.setCancelled(true); - RoleSelectorArgument.openRolePassMenu(event.getPlayer(), plugin); - return; - } - if(key.equalsIgnoreCase(SpecialItemManager.SpecialItems.FORCESTART.getName())) { - event.setCancelled(true); - ArenaUtils.arenaForceStart(event.getPlayer()); - return; - } - if(key.equals(SpecialItemManager.SpecialItems.LOBBY_LEAVE_ITEM.getName()) || key.equals(SpecialItemManager.SpecialItems.SPECTATOR_LEAVE_ITEM.getName())) { - event.setCancelled(true); - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - plugin.getBungeeManager().connectToHub(event.getPlayer()); - } else { - ArenaManager.leaveAttempt(event.getPlayer(), arena); - } - } - } - - - - @EventHandler(priority = EventPriority.HIGH) - public void onFoodLevelChange(FoodLevelChangeEvent event) { - if(event.getEntity().getType() == EntityType.PLAYER && ArenaRegistry.isInArena((Player) event.getEntity())) { - event.setFoodLevel(20); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - //highest priority to fully protect our game - public void onBlockBreakEvent(BlockBreakEvent event) { - if(ArenaRegistry.isInArena(event.getPlayer())) { - event.setCancelled(true); - return; - } - if(event.getBlock().getType() != XMaterial.ARMOR_STAND.parseMaterial()) { - return; - } - - HologramManager.getArmorStands().removeIf(armorStand -> { - boolean isSameType = armorStand.getLocation().getBlock().getType() == event.getBlock().getType(); - if(isSameType) { - armorStand.remove(); - armorStand.setCustomNameVisible(false); - } - return isSameType; - }); - } - - @EventHandler(priority = EventPriority.HIGH) - //highest priority to fully protect our game - public void onBuild(BlockPlaceEvent event) { - if(ArenaRegistry.isInArena(event.getPlayer())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - //highest priority to fully protect our game - public void onHangingBreakEvent(HangingBreakByEntityEvent event) { - if(event.getEntity() instanceof ItemFrame || event.getEntity() instanceof Painting) { - if(event.getRemover() instanceof Player && ArenaRegistry.isInArena((Player) event.getRemover())) { - event.setCancelled(true); - return; - } - if(!(event.getRemover() instanceof Arrow)) { - return; - } - Arrow arrow = (Arrow) event.getRemover(); - if(arrow.getShooter() instanceof Player && ArenaRegistry.isInArena((Player) arrow.getShooter())) { - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onArmorStandDestroy(EntityDamageByEntityEvent e) { - if(!(e.getEntity() instanceof LivingEntity)) { - return; - } - LivingEntity livingEntity = (LivingEntity) e.getEntity(); - if(livingEntity.getType() != EntityType.ARMOR_STAND) { - return; - } - if((e.getDamager() instanceof Arrow && ((Arrow) e.getDamager()).getShooter() instanceof Player && ArenaRegistry.isInArena((Player) ((Arrow) e.getDamager()).getShooter())) - || (e.getDamager() instanceof Player && ArenaRegistry.isInArena((Player) e.getDamager()))) { - e.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onInteractWithArmorStand(PlayerArmorStandManipulateEvent event) { - if(ArenaRegistry.isInArena(event.getPlayer())) { - event.setCancelled(true); - } - } - - @EventHandler - public void onCraft(PlayerInteractEvent event) { - if(!ArenaRegistry.isInArena(event.getPlayer())) { - return; - } - if(event.getPlayer().getTargetBlock(null, 7).getType() == XMaterial.CRAFTING_TABLE.parseMaterial()) { - event.setCancelled(true); - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/events/JoinEvent.java b/src/main/java/plugily/projects/murdermystery/events/JoinEvent.java deleted file mode 100644 index 595aaec7..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/JoinEvent.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerLoginEvent; - -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.serialization.InventorySerializer; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.handlers.PermissionsManager; -import plugily.projects.murdermystery.utils.UpdateChecker; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class JoinEvent implements Listener { - - private final Main plugin; - - public JoinEvent(Main plugin) { - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @EventHandler - public void onLogin(PlayerLoginEvent e) { - if(!plugin.getServer().hasWhitelist() && !plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED) - || e.getResult() != PlayerLoginEvent.Result.KICK_WHITELIST) { - return; - } - if(e.getPlayer().hasPermission(PermissionsManager.getJoinFullGames())) { - e.setResult(PlayerLoginEvent.Result.ALLOWED); - } - } - - @EventHandler - public void onJoin(PlayerJoinEvent event) { - //Load statistics first - plugin.getUserManager().loadStatistics(plugin.getUserManager().getUser(event.getPlayer())); - //Teleport to lobby on bungee mode - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - ArenaRegistry.getArenas().get(ArenaRegistry.getBungeeArena()).teleportToLobby(event.getPlayer()); - return; - } - for(Player player : plugin.getServer().getOnlinePlayers()) { - if(ArenaRegistry.getArena(player) == null) { - continue; - } - VersionUtils.hidePlayer(plugin, player, event.getPlayer()); - VersionUtils.hidePlayer(plugin, event.getPlayer(), player); - } - //load player inventory in case of server crash, file is deleted once loaded so if file was already - //deleted player won't receive his backup, in case of crash he will get it back - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.INVENTORY_MANAGER_ENABLED)) { - InventorySerializer.loadInventory(plugin, event.getPlayer()); - } - } - - @EventHandler - public void onJoinCheckVersion(final PlayerJoinEvent event) { - if(!plugin.getConfig().getBoolean("Update-Notifier.Enabled", true) || !event.getPlayer().hasPermission("murdermystery.updatenotify")) { - return; - } - //we want to be the first :) - Bukkit.getScheduler().runTaskLater(plugin, () -> UpdateChecker.init(plugin, 66614).requestUpdateCheck().whenComplete((result, exception) -> { - if(!result.requiresUpdate()) { - return; - } - if(result.getNewestVersion().contains("b")) { - event.getPlayer().sendMessage(""); - event.getPlayer().sendMessage(ChatColor.BOLD + "MURDER MYSTERY UPDATE NOTIFY"); - event.getPlayer().sendMessage(ChatColor.RED + "BETA version of software is ready for update! Proceed with caution."); - event.getPlayer().sendMessage(ChatColor.YELLOW + "Current version: " + ChatColor.RED + plugin.getDescription().getVersion() + ChatColor.YELLOW + " Latest version: " + ChatColor.GREEN + result.getNewestVersion()); - } else { - event.getPlayer().sendMessage(""); - event.getPlayer().sendMessage(ChatColor.BOLD + "MURDER MYSTERY UPDATE NOTIFY"); - event.getPlayer().sendMessage(ChatColor.GREEN + "Software is ready for update! Download it to keep with latest changes and fixes."); - event.getPlayer().sendMessage(ChatColor.YELLOW + "Current version: " + ChatColor.RED + plugin.getDescription().getVersion() + ChatColor.YELLOW + " Latest version: " + ChatColor.GREEN + result.getNewestVersion()); - } - }), 25); - } -} diff --git a/src/main/java/plugily/projects/murdermystery/events/LobbyEvent.java b/src/main/java/plugily/projects/murdermystery/events/LobbyEvent.java deleted file mode 100644 index 33adc9be..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/LobbyEvent.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events; - -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; - -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; - -/** - * @author Plajer - *

- * Created at 05.08.2018 - */ -public class LobbyEvent implements Listener { - - public LobbyEvent(Main plugin) { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onFoodLose(FoodLevelChangeEvent event) { - if(event.getEntity().getType() != EntityType.PLAYER) { - return; - } - Arena arena = ArenaRegistry.getArena((Player) event.getEntity()); - if(arena != null && (arena.getArenaState() == ArenaState.STARTING || arena.getArenaState() == ArenaState.WAITING_FOR_PLAYERS)) { - event.setCancelled(true); - } - } - - @EventHandler - public void onLobbyDamage(EntityDamageEvent event) { - if(event.getEntity().getType() != EntityType.PLAYER) { - return; - } - Player player = (Player) event.getEntity(); - Arena arena = ArenaRegistry.getArena(player); - if(arena == null || arena.getArenaState() == ArenaState.IN_GAME) { - return; - } - event.setCancelled(true); - player.setFireTicks(0); - player.setHealth(VersionUtils.getMaxHealth(player)); - } - - @EventHandler - public void onItemFrameRotate(PlayerInteractEntityEvent event) { - Player player = event.getPlayer(); - Arena arena = ArenaRegistry.getArena(player); - if(arena == null || arena.getArenaState() == ArenaState.IN_GAME) { - return; - } - if(event.getRightClicked() instanceof ItemFrame && !((ItemFrame) event.getRightClicked()).getItem().getType().equals(Material.AIR)) { - event.setCancelled(true); - } - } - - @EventHandler - public void onHangingBreak(HangingBreakByEntityEvent event) { - if(event.getEntity().getType() != EntityType.PLAYER) { - return; - } - Player player = (Player) event.getEntity(); - Arena arena = ArenaRegistry.getArena(player); - if(arena == null || arena.getArenaState() == ArenaState.IN_GAME) { - return; - } - event.setCancelled(true); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/events/PluginEvents.java b/src/main/java/plugily/projects/murdermystery/events/PluginEvents.java new file mode 100644 index 00000000..002ac8b3 --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/events/PluginEvents.java @@ -0,0 +1,214 @@ +/* + * MurderMystery - Find the murderer, kill him and survive! + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package plugily.projects.murdermystery.events; + +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.EulerAngle; +import org.bukkit.util.Vector; +import plugily.projects.minigamesbox.classic.user.User; +import plugily.projects.minigamesbox.classic.utils.version.ServerVersion; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XSound; +import plugily.projects.murdermystery.Main; +import plugily.projects.murdermystery.arena.Arena; +import plugily.projects.murdermystery.arena.ArenaUtils; +import plugily.projects.murdermystery.arena.role.Role; + +/** + * @author Plajer + *

Created at 05.08.2018 + */ +public class PluginEvents implements Listener { + + private final Main plugin; + + public PluginEvents(Main plugin) { + this.plugin = plugin; + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } + + @EventHandler + public void onSwordThrow(PlayerInteractEvent event) { + if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.PHYSICAL) { + return; + } + Player attacker = event.getPlayer(); + Arena arena = plugin.getArenaRegistry().getArena(attacker); + if(arena == null) { + return; + } + + User attackerUser = plugin.getUserManager().getUser(attacker); + if(!Role.isRole(Role.MURDERER, attackerUser, arena)) { + return; + } + + ItemStack murdererSword = plugin.getSwordSkinManager().getMurdererSword(attacker); + + if(murdererSword == null) { + return; + } + + if(VersionUtils.getItemInHand(attacker).getType() != murdererSword.getType()) { + return; + } + if(attackerUser.getCooldown("sword_shoot") > 0) { + return; + } + + int swordFlyCooldown = plugin.getConfig().getInt("Sword.Cooldown.Fly", 5); + + attackerUser.setCooldown("sword_shoot", swordFlyCooldown); + + if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_10_R1)) { + attackerUser.setCooldown("sword_attack", (plugin.getConfig().getInt("Sword.Cooldown.Attack", 1))); + } else { + VersionUtils.setMaterialCooldown(attacker ,plugin.getSwordSkinManager().getMurdererSword(attacker).getType(), 20 * (plugin.getConfig().getInt("Sword.Cooldown.Attack", 1))); + } + + createFlyingSword(attacker, attackerUser); + plugin.getBukkitHelper().applyActionBarCooldown(attacker, swordFlyCooldown); + } + + private void createFlyingSword(Player attacker, User attackerUser) { + Location loc = attacker.getLocation(); + Vector vec = loc.getDirection(); + vec.normalize().multiply(plugin.getConfig().getDouble("Sword.Speed", 0.65)); + Location standStart = plugin.getBukkitHelper().rotateAroundAxisY(new Vector(1.0D, 0.0D, 0.0D), loc.getYaw()).toLocation(attacker.getWorld()).add(loc); + standStart.setYaw(loc.getYaw()); + ArmorStand stand = (ArmorStand) attacker.getWorld().spawnEntity(standStart, EntityType.ARMOR_STAND); + stand.setVisible(false); + if(ServerVersion.Version.isCurrentHigher(ServerVersion.Version.v1_8_R3)) { + stand.setInvulnerable(true); + stand.setSilent(true); + } + + VersionUtils.setItemInHand(stand, plugin.getSwordSkinManager().getMurdererSword(attacker)); + + stand.setRightArmPose(new EulerAngle(Math.toRadians(350.0), Math.toRadians(loc.getPitch() * -1.0), Math.toRadians(90.0))); + VersionUtils.setCollidable(stand, false); + + stand.setGravity(false); + stand.setRemoveWhenFarAway(true); + + if(ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_8_R3)) { + stand.setMarker(true); + } + + Location initialise = plugin.getBukkitHelper().rotateAroundAxisY(new Vector(-0.8D, 1.45D, 0.0D), loc.getYaw()).toLocation(attacker.getWorld()).add(standStart) + .add(plugin.getBukkitHelper().rotateAroundAxisY(plugin.getBukkitHelper().rotateAroundAxisX(new Vector(0.0D, 0.0D, 1.0D), loc.getPitch()), loc.getYaw())); + int maxRange = plugin.getConfig().getInt("Sword.Fly.Range", 20); + double maxHitRange = plugin.getConfig().getDouble("Sword.Fly.Radius", 0.5); + new BukkitRunnable() { + @Override + public void run() { + VersionUtils.teleport(stand, standStart.add(vec)); + initialise.add(vec); + initialise.getWorld().getNearbyEntities(initialise, maxHitRange, maxHitRange, maxHitRange) + .forEach(entity -> { + if(entity instanceof Player) { + Player victim = (Player) entity; + Arena arena = plugin.getArenaRegistry().getArena(victim); + if(arena == null) { + return; + } + if(!plugin.getUserManager().getUser(victim).isSpectator() && !victim.equals(attacker)) { + killBySword(arena, attackerUser, victim); + cancel(); + stand.remove(); + } + } + }); + if(loc.distance(initialise) > maxRange || initialise.getBlock().getType().isSolid()) { + cancel(); + stand.remove(); + } + } + }.runTaskTimer(plugin, 0, 1); + } + + private void killBySword(Arena arena, User attackerUser, Player victim) { + Arena victimArena = plugin.getArenaRegistry().getArena(victim); + if(arena == null) { + return; + } + User user = plugin.getUserManager().getUser(victim); + + // check if victim is murderer + if(Role.isRole(Role.MURDERER, user, victimArena)) { + return; + } + XSound.ENTITY_PLAYER_DEATH.play(victim.getLocation(), 50, 1); + victim.damage(100.0); + attackerUser.adjustStatistic("LOCAL_KILLS", 1); + attackerUser.adjustStatistic("KILLS", 1); + arena.adjustContributorValue(Role.DETECTIVE, user, plugin.getRandom().nextInt(2)); + ArenaUtils.addScore(attackerUser, ArenaUtils.ScoreAction.KILL_PLAYER, 0); + if(Role.isRole(Role.ANY_DETECTIVE, user, victimArena) && arena.lastAliveDetective()) { + if(Role.isRole(Role.FAKE_DETECTIVE, user, victimArena)) { + arena.setCharacter(Arena.CharacterType.FAKE_DETECTIVE, null); + } + ArenaUtils.dropBowAndAnnounce(arena, victim); + } + } + + @EventHandler(priority = EventPriority.HIGH) + // highest priority to fully protect our game + public void onBlockBreak(BlockBreakEvent event) { + Arena arena = plugin.getArenaRegistry().getArena(event.getPlayer()); + if(arena == null) { + return; + } + event.setCancelled(true); + if(event.getBlock().getType() != XMaterial.ARMOR_STAND.parseMaterial()) { + return; + } + plugin.getHologramManager().getArmorStands().removeIf(armorStand -> { + boolean isSameType = armorStand.getLocation().getBlock().getType() == event.getBlock().getType(); + if(isSameType) { + armorStand.remove(); + armorStand.setCustomNameVisible(false); + } + return isSameType; + }); + } + + @EventHandler(priority = EventPriority.HIGH) + // highest priority to fully protect our game + public void onBuild(BlockPlaceEvent event) { + Arena arena = plugin.getArenaRegistry().getArena(event.getPlayer()); + if(arena == null) { + return; + } + event.setCancelled(true); + } +} diff --git a/src/main/java/plugily/projects/murdermystery/events/QuitEvent.java b/src/main/java/plugily/projects/murdermystery/events/QuitEvent.java deleted file mode 100644 index 0cf12515..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/QuitEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; - -/** - * @author Plajer - *

- * Created at 05.08.2018 - */ -public class QuitEvent implements Listener { - - private final Main plugin; - - public QuitEvent(Main plugin) { - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @EventHandler - public void onQuit(PlayerQuitEvent event) { - onQuit(event.getPlayer()); - } - - @EventHandler - public void onKick(PlayerKickEvent event) { - onQuit(event.getPlayer()); - } - - private void onQuit(Player player) { - Arena arena = ArenaRegistry.getArena(player); - if(arena != null) { - ArenaManager.leaveAttempt(player, arena); - } - plugin.getUserManager().removeUser(plugin.getUserManager().getUser(player)); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorEvents.java b/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorEvents.java deleted file mode 100644 index 8bf2aceb..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorEvents.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events.spectator; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.entity.EntityDamageByBlockEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityTargetEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerDropItemEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerItemConsumeEvent; -import org.bukkit.event.player.PlayerShearEntityEvent; - -import plugily.projects.commonsbox.minecraft.compat.events.api.CBEntityPickupItemEvent; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.ArenaRegistry; - -/** - * @author Plajer - *

- * Created at 05.08.2018 - */ -public class SpectatorEvents implements Listener { - - private final Main plugin; - - public SpectatorEvents(Main plugin) { - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onSpectatorTarget(EntityTargetEvent e) { - if(!(e.getTarget() instanceof Player)) { - return; - } - if(plugin.getUserManager().getUser((Player) e.getTarget()).isSpectator()) { - e.setCancelled(true); - e.setTarget(null); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onSpectatorTarget(EntityTargetLivingEntityEvent e) { - if(!(e.getTarget() instanceof Player)) { - return; - } - if(plugin.getUserManager().getUser((Player) e.getTarget()).isSpectator()) { - e.setCancelled(true); - e.setTarget(null); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onBlockPlace(BlockPlaceEvent event) { - if(plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onBlockBreak(BlockBreakEvent event) { - if(plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onDropItem(PlayerDropItemEvent event) { - if(plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onBucketEmpty(PlayerBucketEmptyEvent event) { - if(plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onInteract(PlayerInteractEntityEvent event) { - if(plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onShear(PlayerShearEntityEvent event) { - if(plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onConsume(PlayerItemConsumeEvent event) { - if(plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onFoodLevelChange(FoodLevelChangeEvent event) { - if(event.getEntity() instanceof Player && plugin.getUserManager().getUser((Player) event.getEntity()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onDamage(EntityDamageEvent event) { - if(!(event.getEntity() instanceof Player)) { - return; - } - Player player = (Player) event.getEntity(); - if(!plugin.getUserManager().getUser(player).isSpectator() || !ArenaRegistry.isInArena(player)) { - return; - } - if(player.getLocation().getY() < 1) { - player.teleport(ArenaRegistry.getArena(player).getPlayerSpawnPoints().get(0)); - event.setDamage(0); - } - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onDamageByBlock(EntityDamageByBlockEvent event) { - if(event.getEntity() instanceof Player && plugin.getUserManager().getUser((Player) event.getEntity()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onDamageByEntity(EntityDamageByEntityEvent event) { - if(event.getDamager() instanceof Player && plugin.getUserManager().getUser((Player) event.getDamager()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPickup(CBEntityPickupItemEvent event) { - if(event.getEntity() instanceof Player && plugin.getUserManager().getUser((Player) event.getEntity()).isSpectator()) { - event.setCancelled(true); - } - } - - @EventHandler - public void onRightClick(PlayerInteractEvent event) { - if(ArenaRegistry.isInArena(event.getPlayer()) && plugin.getUserManager().getUser(event.getPlayer()).isSpectator()) { - event.setCancelled(true); - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorItemEvents.java b/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorItemEvents.java deleted file mode 100644 index 8f1440e7..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorItemEvents.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events.spectator; - -import plugily.projects.commonsbox.minecraft.item.ItemUtils; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; -import plugily.projects.commonsbox.number.NumberUtils; -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.compat.events.api.CBPlayerInteractEvent; -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.inventoryframework.gui.GuiItem; -import plugily.projects.inventoryframework.gui.type.ChestGui; -import plugily.projects.inventoryframework.pane.OutlinePane; -import org.apache.commons.lang.StringUtils; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.role.Role; -import plugily.projects.murdermystery.handlers.items.SpecialItemManager; -import plugily.projects.murdermystery.utils.Utils; - -import java.util.ArrayList; - -/** - * @author Plajer - *

- * Created at 05.08.2018 - */ -public class SpectatorItemEvents implements Listener { - - private final Main plugin; - private final SpectatorSettingsMenu spectatorSettingsMenu; - - public SpectatorItemEvents(Main plugin) { - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - spectatorSettingsMenu = new SpectatorSettingsMenu(plugin, plugin.getChatManager().colorMessage("In-Game.Spectator.Settings-Menu.Inventory-Name"), - plugin.getChatManager().colorMessage("In-Game.Spectator.Settings-Menu.Speed-Name")); - } - - @EventHandler - public void onSpectatorItemClick(CBPlayerInteractEvent e) { - if(e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.PHYSICAL) { - return; - } - Arena arena = ArenaRegistry.getArena(e.getPlayer()); - ItemStack stack = VersionUtils.getItemInHand(e.getPlayer()); - if(arena == null || !ItemUtils.isItemStackNamed(stack)) { - return; - } - if(plugin.getSpecialItemManager().getRelatedSpecialItem(stack).getName().equals(SpecialItemManager.SpecialItems.PLAYERS_LIST.getName())) { - e.setCancelled(true); - openSpectatorMenu(e.getPlayer(), arena); - } else if(plugin.getSpecialItemManager().getRelatedSpecialItem(stack).getName().equals(SpecialItemManager.SpecialItems.SPECTATOR_OPTIONS.getName())) { - e.setCancelled(true); - spectatorSettingsMenu.openSpectatorSettingsMenu(e.getPlayer()); - } else if(plugin.getSpecialItemManager().getRelatedSpecialItem(stack).getName().equals(SpecialItemManager.SpecialItems.SPECTATOR_LEAVE_ITEM.getName())) { - e.setCancelled(true); - ArenaManager.leaveAttempt(e.getPlayer(), arena); - } - } - - private void openSpectatorMenu(Player player, Arena arena) { - int rows = Utils.serializeInt(arena.getPlayers().size()) / 9; - ChestGui gui = new ChestGui(rows, plugin.getChatManager().colorMessage("In-Game.Spectator.Spectator-Menu-Name")); - OutlinePane pane = new OutlinePane(9, rows); - gui.addPane(pane); - - ItemStack skull = XMaterial.PLAYER_HEAD.parseItem(); - - for(Player arenaPlayer : arena.getPlayers()) { - if(plugin.getUserManager().getUser(arenaPlayer).isSpectator()) { - continue; - } - //Get the raw role message and replace old placeholder, we don't want to do this inside the for loop. - String roleRaw = plugin.getChatManager().colorMessage("In-Game.Spectator.Target-Player-Role", arenaPlayer); - roleRaw = StringUtils.replace(roleRaw, "%ROLE%", "%role%"); - ItemStack cloneSkull = skull.clone(); - SkullMeta meta = VersionUtils.setPlayerHead(arenaPlayer, (SkullMeta) cloneSkull.getItemMeta()); - ComplementAccessor.getComplement().setDisplayName(meta, arenaPlayer.getName()); - - ArrayList lore = new ArrayList<>(); - - lore.add(plugin.getChatManager().colorMessage("In-Game.Spectator.Target-Player-Health") - .replace("%health%", Double.toString(NumberUtils.round(arenaPlayer.getHealth(), 2)))); - String role = roleRaw; - if(Role.isRole(Role.MURDERER, player, arena)) { - role = StringUtils.replace(role, "%role%", plugin.getChatManager().colorMessage("Scoreboard.Roles.Murderer")); - } else if(Role.isRole(Role.ANY_DETECTIVE, player, arena)) { - role = StringUtils.replace(role, "%role%", plugin.getChatManager().colorMessage("Scoreboard.Roles.Detective")); - } else { - role = StringUtils.replace(role, "%role%", plugin.getChatManager().colorMessage("Scoreboard.Roles.Innocent")); - } - lore.add(role); - ComplementAccessor.getComplement().setLore(meta, lore); - cloneSkull.setItemMeta(meta); - pane.addItem(new GuiItem(cloneSkull, e -> { - e.setCancelled(true); - e.getWhoClicked().sendMessage(plugin.getChatManager().formatMessage(arena, plugin.getChatManager().colorMessage("Commands.Admin-Commands.Teleported-To-Player"), arenaPlayer)); - e.getWhoClicked().closeInventory(); - e.getWhoClicked().teleport(arenaPlayer); - })); - } - gui.show(player); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorSettingsMenu.java b/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorSettingsMenu.java deleted file mode 100644 index e8156ec4..00000000 --- a/src/main/java/plugily/projects/murdermystery/events/spectator/SpectatorSettingsMenu.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.events.spectator; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.handlers.ChatManager; - -/** - * @author Plajer - *

- * Created at 06.04.2019 - */ -public class SpectatorSettingsMenu implements Listener { - - private final String inventoryName; - private final String speedOptionName; - private final Main plugin; - private final Inventory inv; - - public SpectatorSettingsMenu(Main plugin, String inventoryName, String speedOptionName) { - this.inventoryName = inventoryName; - this.speedOptionName = speedOptionName; - (this.plugin = plugin).getServer().getPluginManager().registerEvents(this, plugin); - this.inv = initInventory(); - } - - public void openSpectatorSettingsMenu(Player player) { - player.openInventory(this.inv); - } - - @EventHandler - public void onSpectatorMenuClick(InventoryClickEvent e) { - if(!ComplementAccessor.getComplement().getTitle(e.getView()).equals(plugin.getChatManager().colorRawMessage(inventoryName))) { - return; - } - org.bukkit.inventory.ItemStack currentItem = e.getCurrentItem(); - if(currentItem == null || !currentItem.hasItemMeta()) { - return; - } - Player p = (Player) e.getWhoClicked(); - p.closeInventory(); - - switch(currentItem.getType()) { - case LEATHER_BOOTS: - p.removePotionEffect(PotionEffectType.SPEED); - p.setFlySpeed(0.15f); - p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 0, false, false)); - break; - case CHAINMAIL_BOOTS: - p.removePotionEffect(PotionEffectType.SPEED); - p.setFlySpeed(0.2f); - p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 1, false, false)); - break; - case IRON_BOOTS: - p.removePotionEffect(PotionEffectType.SPEED); - p.setFlySpeed(0.25f); - p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2, false, false)); - break; - case GOLDEN_BOOTS: - p.removePotionEffect(PotionEffectType.SPEED); - p.setFlySpeed(0.3f); - p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 3, false, false)); - break; - case DIAMOND_BOOTS: - p.removePotionEffect(PotionEffectType.SPEED); - p.setFlySpeed(0.35f); - p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 4, false, false)); - break; - default: - break; - } - } - - private Inventory initInventory() { - Inventory inv = ComplementAccessor.getComplement().createInventory(null, 9 * 3, inventoryName); - ChatManager chatManager = plugin.getChatManager(); - inv.setItem(11, new ItemBuilder(Material.LEATHER_BOOTS) - .name(chatManager.colorRawMessage(speedOptionName + " I")).build()); - inv.setItem(12, new ItemBuilder(Material.CHAINMAIL_BOOTS) - .name(chatManager.colorRawMessage(speedOptionName + " II")).build()); - inv.setItem(13, new ItemBuilder(Material.IRON_BOOTS) - .name(chatManager.colorRawMessage(speedOptionName + " III")).build()); - inv.setItem(14, new ItemBuilder(XMaterial.GOLDEN_BOOTS.parseItem()) - .name(chatManager.colorRawMessage(speedOptionName + " IV")).build()); - inv.setItem(15, new ItemBuilder(Material.DIAMOND_BOOTS) - .name(chatManager.colorRawMessage(speedOptionName + " V")).build()); - return inv; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/BungeeManager.java b/src/main/java/plugily/projects/murdermystery/handlers/BungeeManager.java deleted file mode 100644 index d58e7857..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/BungeeManager.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers; - -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.server.ServerListPingEvent; - -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; - -import java.util.EnumMap; -import java.util.Map; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class BungeeManager implements Listener { - - private final Main plugin; - private final Map gameStateToString = new EnumMap<>(ArenaState.class); - private final String motd; - private final FileConfiguration bungee; - - public BungeeManager(Main plugin) { - this.plugin = plugin; - bungee = ConfigUtils.getConfig(plugin, "bungee"); - - ChatManager chatManager = plugin.getChatManager(); - - gameStateToString.put(ArenaState.WAITING_FOR_PLAYERS, chatManager.colorRawMessage(bungee.getString("MOTD.Game-States.Inactive", "Inactive"))); - gameStateToString.put(ArenaState.STARTING, chatManager.colorRawMessage(bungee.getString("MOTD.Game-States.Starting", "Starting"))); - gameStateToString.put(ArenaState.IN_GAME, chatManager.colorRawMessage(bungee.getString("MOTD.Game-States.In-Game", "In-Game"))); - gameStateToString.put(ArenaState.ENDING, chatManager.colorRawMessage(bungee.getString("MOTD.Game-States.Ending", "Ending"))); - gameStateToString.put(ArenaState.RESTARTING, chatManager.colorRawMessage(bungee.getString("MOTD.Game-States.Restarting", "Restarting"))); - motd = chatManager.colorRawMessage(bungee.getString("MOTD.Message", "The actual game state of mm is %state%")); - plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord"); - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - public void connectToHub(Player player) { - if(!plugin.isEnabled() || !bungee.getBoolean("Connect-To-Hub", true)) { - return; - } - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - out.writeUTF("Connect"); - out.writeUTF(bungee.getString("Hub")); - player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onServerListPing(ServerListPingEvent event) { - if(ArenaRegistry.getArenas().isEmpty() || !bungee.getBoolean("MOTD.Manager")) { - return; - } - Arena arena = ArenaRegistry.getArenas().get(ArenaRegistry.getBungeeArena()); - event.setMaxPlayers(arena.getMaximumPlayers()); - ComplementAccessor.getComplement().setMotd(event, motd.replace("%state%", gameStateToString.get(arena.getArenaState()))); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onJoin(final PlayerJoinEvent event) { - if(ArenaRegistry.getArenas().isEmpty()) { - return; - } - - ComplementAccessor.getComplement().setJoinMessage(event, ""); - plugin.getServer().getScheduler().runTaskLater(plugin, () -> ArenaManager.joinAttempt(event.getPlayer(), ArenaRegistry.getArenas().get(ArenaRegistry.getBungeeArena())), 1L); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onQuit(PlayerQuitEvent event) { - if(ArenaRegistry.getArenas().isEmpty()) { - return; - } - - ComplementAccessor.getComplement().setQuitMessage(event, ""); - if(ArenaRegistry.isInArena(event.getPlayer())) { - ArenaManager.leaveAttempt(event.getPlayer(), ArenaRegistry.getArenas().get(ArenaRegistry.getBungeeArena())); - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/ChatManager.java b/src/main/java/plugily/projects/murdermystery/handlers/ChatManager.java deleted file mode 100644 index 824d6eee..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/ChatManager.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers; - -import me.clip.placeholderapi.PlaceholderAPI; -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.misc.MiscUtils; -import plugily.projects.commonsbox.string.StringFormatUtils; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.handlers.language.LanguageManager; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class ChatManager { - - private final String pluginPrefix; - private final Main plugin; - - public ChatManager(Main plugin) { - this.plugin = plugin; - pluginPrefix = colorMessage("In-Game.Plugin-Prefix"); - } - - /** - * @return game prefix - */ - public String getPrefix() { - return pluginPrefix; - } - - public String colorMessage(String message) { - return colorRawMessage(LanguageManager.getLanguageMessage(message)); - } - - public String colorRawMessage(String message) { - if(message == null) { - return ""; - } - - if(ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_16_R1) && message.indexOf('#') >= 0) { - message = MiscUtils.matchColorRegex(message); - } - - return ChatColor.translateAlternateColorCodes('&', message); - } - - public String colorMessage(String message, Player player) { - String returnString = LanguageManager.getLanguageMessage(message); - if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) { - returnString = PlaceholderAPI.setPlaceholders(player, returnString); - } - return colorRawMessage(returnString); - } - - public void broadcast(Arena arena, String message) { - if (message != null && !message.isEmpty()) { - for(Player p : arena.getPlayers()) { - p.sendMessage(pluginPrefix + message); - } - } - } - - public String formatMessage(Arena arena, String message, int integer) { - String returnString = message; - returnString = StringUtils.replace(returnString, "%NUMBER%", Integer.toString(integer)); - returnString = colorRawMessage(formatPlaceholders(returnString, arena)); - return returnString; - } - - public String formatMessage(Arena arena, String message, Player player) { - String returnString = message; - returnString = StringUtils.replace(returnString, "%PLAYER%", player.getName()); - returnString = colorRawMessage(formatPlaceholders(returnString, arena)); - if(plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) { - returnString = PlaceholderAPI.setPlaceholders(player, returnString); - } - return returnString; - } - - private String formatPlaceholders(String message, Arena arena) { - String returnString = message; - - int timer = arena.getTimer(); - - returnString = StringUtils.replace(returnString, "%ARENANAME%", arena.getMapName()); - returnString = StringUtils.replace(returnString, "%TIME%", Integer.toString(timer)); - returnString = StringUtils.replace(returnString, "%FORMATTEDTIME%", StringFormatUtils.formatIntoMMSS(timer)); - returnString = StringUtils.replace(returnString, "%PLAYERSIZE%", Integer.toString(arena.getPlayers().size())); - returnString = StringUtils.replace(returnString, "%MAXPLAYERS%", Integer.toString(arena.getMaximumPlayers())); - returnString = StringUtils.replace(returnString, "%MINPLAYERS%", Integer.toString(arena.getMinimumPlayers())); - return returnString; - } - - public void broadcastAction(Arena a, Player p, ActionType action) { - String message; - switch(action) { - case JOIN: - message = formatMessage(a, colorMessage("In-Game.Messages.Join"), p); - break; - case LEAVE: - message = formatMessage(a, colorMessage("In-Game.Messages.Leave"), p); - break; - case DEATH: - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DISABLE_DEATH_MESSAGE)) { - return; - } - - message = formatMessage(a, colorMessage("In-Game.Messages.Death"), p); - break; - default: - return; //likely won't ever happen - } - for(Player player : a.getPlayers()) { - player.sendMessage(pluginPrefix + message); - } - } - - public enum ActionType { - JOIN, LEAVE, DEATH - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/CorpseHandler.java b/src/main/java/plugily/projects/murdermystery/handlers/CorpseHandler.java index 583aed62..3976411f 100644 --- a/src/main/java/plugily/projects/murdermystery/handlers/CorpseHandler.java +++ b/src/main/java/plugily/projects/murdermystery/handlers/CorpseHandler.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -31,15 +31,15 @@ import org.golde.bukkit.corpsereborn.CorpseAPI.events.CorpseSpawnEvent; import org.golde.bukkit.corpsereborn.nms.Corpses; -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.hologram.ArmorStandHologram; -import plugily.projects.commonsbox.minecraft.hologram.HologramManager; -import plugily.projects.murdermystery.HookManager; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.utils.hologram.ArmorStandHologram; +import plugily.projects.minigamesbox.classic.utils.version.ServerVersion; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; import plugily.projects.murdermystery.Main; +import plugily.projects.murdermystery.api.events.game.MurderGameCorpseSpawnEvent; import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; +import plugily.projects.murdermystery.HookManager; import plugily.projects.murdermystery.arena.corpse.Corpse; import plugily.projects.murdermystery.arena.corpse.Stand; @@ -54,7 +54,6 @@ public class CorpseHandler implements Listener { private final Main plugin; - private final ChatManager chatManager; private Corpses.CorpseData lastSpawnedCorpse; private final Map registeredLastWords = new HashMap<>(); @@ -62,7 +61,6 @@ public class CorpseHandler implements Listener { public CorpseHandler(Main plugin) { this.plugin = plugin; - chatManager = plugin.getChatManager(); //run bit later than hook manager to ensure it's not null Bukkit.getScheduler().runTaskLater(plugin, () -> { if(plugin.getHookManager().isFeatureEnabled(HookManager.HookFeature.CORPSES)) { @@ -76,11 +74,16 @@ public void registerLastWord(String permission, String lastWord) { } @SuppressWarnings("deprecation") - public void spawnCorpse(Player p, Arena arena) { + public void spawnCorpse(Player player, Arena arena) { + MurderGameCorpseSpawnEvent murderGameCorpseSpawnEvent = new MurderGameCorpseSpawnEvent(arena, player.getPlayer(), player.getLocation()); + Bukkit.getPluginManager().callEvent(murderGameCorpseSpawnEvent); + if(murderGameCorpseSpawnEvent.isCancelled()) { + return; + } if(!plugin.getHookManager().isFeatureEnabled(HookManager.HookFeature.CORPSES)) { - ArmorStand stand = p.getLocation().getWorld().spawn(p.getLocation().add(0.0D, -1.25D, 0.0D), ArmorStand.class); + ArmorStand stand = player.getLocation().getWorld().spawn(player.getLocation().add(0.0D, -1.25D, 0.0D), ArmorStand.class); SkullMeta meta = (SkullMeta) head.getItemMeta(); - meta = VersionUtils.setPlayerHead(p, meta); + meta = VersionUtils.setPlayerHead(player, meta); head.setItemMeta(meta); stand.setVisible(false); @@ -91,22 +94,22 @@ public void spawnCorpse(Player p, Arena arena) { } stand.setGravity(false); stand.setCustomNameVisible(false); - stand.setHeadPose(new EulerAngle(Math.toRadians(p.getLocation().getX()), Math.toRadians(p.getLocation().getPitch()), Math.toRadians(p.getLocation().getZ()))); + stand.setHeadPose(new EulerAngle(Math.toRadians(player.getLocation().getX()), Math.toRadians(player.getLocation().getPitch()), Math.toRadians(player.getLocation().getZ()))); - HologramManager.getArmorStands().add(stand); - ArmorStandHologram hologram = getLastWordsHologram(p); + plugin.getHologramManager().getArmorStands().add(stand); + ArmorStandHologram hologram = getLastWordsHologram(player); arena.addHead(new Stand(hologram, stand)); Bukkit.getScheduler().runTaskLater(plugin, () -> { hologram.delete(); - HologramManager.getArmorStands().remove(stand); + plugin.getHologramManager().getArmorStands().remove(stand); Bukkit.getScheduler().runTaskLater(plugin, stand::remove, 20 * 20); }, 15 * 20); return; } - ArmorStandHologram hologram = getLastWordsHologram(p); - Corpses.CorpseData corpse = CorpseAPI.spawnCorpse(p, p.getLocation()); + ArmorStandHologram hologram = getLastWordsHologram(player); + Corpses.CorpseData corpse = CorpseAPI.spawnCorpse(player, player.getLocation()); lastSpawnedCorpse = corpse; - //spawns 2 corpses - Corpses.CorpseData corpse = lastSpawnedCorpse = CorpseAPI.spawnCorpse(p, p.getLocation()); + //spawns 2 corpses - Corpses.CorpseData corpse = lastSpawnedCorpse = CorpseAPI.spawnCorpse(player, player.getLocation()); arena.addCorpse(new Corpse(hologram, corpse)); Bukkit.getScheduler().runTaskLater(plugin, () -> { hologram.delete(); @@ -116,24 +119,24 @@ public void spawnCorpse(Player p, Arena arena) { private ArmorStandHologram getLastWordsHologram(Player player) { ArmorStandHologram hologram = new ArmorStandHologram(player.getLocation()); - hologram.appendLine(chatManager.colorMessage("In-Game.Messages.Corpse-Last-Words", player).replace("%player%", player.getName())); + hologram.appendLine(new MessageBuilder(plugin.getLastWordsManager().getHologramTitle()).player(player).build()); hologram.appendLine(plugin.getLastWordsManager().getRandomLastWord(player)); return hologram; } @EventHandler public void onCorpseSpawn(CorpseSpawnEvent e) { - if(!plugin.getConfig().getBoolean("Override-Corpses-Spawn", true) || lastSpawnedCorpse == null) { + if(lastSpawnedCorpse == null) { return; } - if(!lastSpawnedCorpse.equals(e.getCorpse())) { + if(plugin.getConfigPreferences().getOption("CORPSES_INTEGRATION_OVERWRITE") && !lastSpawnedCorpse.equals(e.getCorpse())) { e.setCancelled(true); } } @EventHandler public void onCorpseClick(CorpseClickEvent e) { - if(ArenaRegistry.isInArena(e.getClicker())) { + if(plugin.getArenaRegistry().isInArena(e.getClicker())) { e.setCancelled(true); e.getClicker().closeInventory(); } diff --git a/src/main/java/plugily/projects/murdermystery/handlers/PermissionsManager.java b/src/main/java/plugily/projects/murdermystery/handlers/PermissionsManager.java deleted file mode 100644 index 142fe825..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/PermissionsManager.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers; - -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.utils.Debugger; - -import java.util.logging.Level; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class PermissionsManager { - - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private static String joinFullPerm = "murdermystery.fullgames"; - private static String joinPerm = "murdermystery.join."; - - public static void init() { - setupPermissions(); - } - - public static String getJoinFullGames() { - return joinFullPerm; - } - - private static void setJoinFullGames(String joinFullGames) { - PermissionsManager.joinFullPerm = joinFullGames; - } - - public static String getJoinPerm() { - return joinPerm; - } - - private static void setJoinPerm(String joinPerm) { - PermissionsManager.joinPerm = joinPerm; - } - - private static void setupPermissions() { - PermissionsManager.setJoinFullGames(plugin.getConfig().getString("Basic-Permissions.Full-Games-Permission", "murdermystery.fullgames")); - PermissionsManager.setJoinPerm(plugin.getConfig().getString("Basic-Permissions.Join-Permission", "murdermystery.join.")); - Debugger.debug(Level.INFO, "Basic permissions registered"); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/PlaceholderManager.java b/src/main/java/plugily/projects/murdermystery/handlers/PlaceholderManager.java deleted file mode 100644 index 1d306dbf..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/PlaceholderManager.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; - -/** - * @author Plajer - *

- * Created at 08.08.2018 - */ -public class PlaceholderManager extends PlaceholderExpansion { - - @Override - public boolean persist() { - return true; - } - - @Override - public @NotNull String getIdentifier() { - return "murdermystery"; - } - - @Override - public @NotNull String getAuthor() { - return "Plugily Projects"; - } - - @Override - public @NotNull String getVersion() { - return "1.0.2"; - } - - @Override - public String onPlaceholderRequest(Player player, String id) { - if(player == null) { - return null; - } - switch(id.toLowerCase()) { - case "kills": - return Integer.toString(StatsStorage.getUserStats(player, StatsStorage.StatisticType.KILLS)); - case "deaths": - return Integer.toString(StatsStorage.getUserStats(player, StatsStorage.StatisticType.DEATHS)); - case "games_played": - return Integer.toString(StatsStorage.getUserStats(player, StatsStorage.StatisticType.GAMES_PLAYED)); - case "highest_score": - return Integer.toString(StatsStorage.getUserStats(player, StatsStorage.StatisticType.HIGHEST_SCORE)); - case "wins": - return Integer.toString(StatsStorage.getUserStats(player, StatsStorage.StatisticType.WINS)); - case "loses": - return Integer.toString(StatsStorage.getUserStats(player, StatsStorage.StatisticType.LOSES)); - case "arena_players_online": - return Integer.toString(ArenaRegistry.getArenaPlayersOnline()); - default: - return handleArenaPlaceholderRequest(id); - } - } - - private String handleArenaPlaceholderRequest(String id) { - String[] data = id.split(":", 2); - if (data.length < 2) - return null; - - Arena arena = ArenaRegistry.getArena(data[0]); - if(arena == null) { - return null; - } - switch(data[1].toLowerCase()) { - case "players": - return Integer.toString(arena.getPlayers().size()); - case "max_players": - return Integer.toString(arena.getMaximumPlayers()); - case "state": - return arena.getArenaState().getFormattedName(); - case "state_pretty": - return arena.getArenaState().getPlaceholder(); - case "mapname": - return arena.getMapName(); - default: - return null; - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/items/SpecialItem.java b/src/main/java/plugily/projects/murdermystery/handlers/items/SpecialItem.java deleted file mode 100644 index 24f29060..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/items/SpecialItem.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2021 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package plugily.projects.murdermystery.handlers.items; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -/** - * Created by Tom on 5/02/2016. - */ -public class SpecialItem { - - public static final SpecialItem INVALID_ITEM = new SpecialItem("INVALID", new ItemStack(Material.BEDROCK), -1, DisplayStage.LOBBY); - private final String name; - private final ItemStack itemStack; - private int slot; - private final DisplayStage displayStage; - - public SpecialItem(String name, ItemStack itemStack, int slot, DisplayStage displayStage) { - this.name = name; - this.itemStack = itemStack; - this.slot = slot; - this.displayStage = displayStage; - } - - public String getName() { - return name; - } - - public ItemStack getItemStack() { - return itemStack; - } - - public int getSlot() { - return slot; - } - - public void setSlot(int slot) { - this.slot = slot; - } - - public DisplayStage getDisplayStage() { - return displayStage; - } - - public enum DisplayStage { - LOBBY, SPECTATOR - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/items/SpecialItemManager.java b/src/main/java/plugily/projects/murdermystery/handlers/items/SpecialItemManager.java deleted file mode 100644 index 2cd595ae..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/items/SpecialItemManager.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2021 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package plugily.projects.murdermystery.handlers.items; - -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.utils.Debugger; - -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.stream.Collectors; - -/** - * Created by Tom on 5/02/2016. - */ -public class SpecialItemManager { - - private final List specialItems = new ArrayList<>(); - private final FileConfiguration config; - private final Main plugin; - - public SpecialItemManager(Main plugin) { - this.plugin = plugin; - this.config = ConfigUtils.getConfig(plugin, "special_items"); - registerItems(); - } - - public void addItem(SpecialItem item) { - specialItems.add(item); - } - - @NotNull - public SpecialItem getSpecialItem(String name) { - for(SpecialItem item : specialItems) { - if(item.getName().equals(name)) { - return item; - } - } - return SpecialItem.INVALID_ITEM; - } - - @NotNull - public SpecialItem getRelatedSpecialItem(ItemStack itemStack) { - for(SpecialItem item : specialItems) { - if(item.getItemStack().isSimilar(itemStack)) { - return item; - } - } - return SpecialItem.INVALID_ITEM; - } - - public void registerItems() { - for(String key : config.getKeys(false)) { - if("Version".equals(key)) { - continue; - } - Material mat; - String name; - List lore; - int slot; - try { - mat = XMaterial.matchXMaterial(config.getString(key + ".material-name", "BEDROCK").toUpperCase()).orElse(XMaterial.BEDROCK).parseMaterial(); - name = plugin.getChatManager().colorRawMessage(config.getString(key + ".displayname")); - lore = config.getStringList(key + ".lore").stream() - .map(itemLore -> itemLore = plugin.getChatManager().colorRawMessage(itemLore)) - .collect(Collectors.toList()); - slot = config.getInt(key + ".slot"); - } catch(Exception ex) { - plugin.getLogger().log(Level.WARNING, "Configuration of " + key + "is missing a value. (material-name, displayname, lore or slot)"); - continue; - } - SpecialItem.DisplayStage stage; - try { - stage = SpecialItem.DisplayStage.valueOf(config.getString(key + ".stage").toUpperCase()); - } catch(Exception ex) { - Debugger.debug(Level.WARNING, "Invalid display stage of special item " + key + " in special_items.yml! Please use lobby or spectator!"); - stage = SpecialItem.DisplayStage.LOBBY; - } - SpecialItem item = new SpecialItem(key, new ItemBuilder(mat).name(name).lore(lore).build(), slot, stage); - addItem(item); - } - } - - public List getSpecialItems() { - return specialItems; - } - - public enum SpecialItems { - ROLE_PASS("Role-Pass"), FORCESTART("Forcestart"), LOBBY_LEAVE_ITEM("Leave-Lobby"), PLAYERS_LIST("Player-List"), - SPECTATOR_OPTIONS("Spectator-Options"), SPECTATOR_LEAVE_ITEM("Leave-Spectator"), BASE_SELECTOR("Base-Selector"); - - private final String name; - - SpecialItems(String name) { - this.name = name; - } - - public String getName() { - return name; - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/language/LanguageManager.java b/src/main/java/plugily/projects/murdermystery/handlers/language/LanguageManager.java deleted file mode 100644 index 82fda92d..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/language/LanguageManager.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.language; - -import org.bukkit.configuration.file.FileConfiguration; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.utils.Debugger; -import plugily.projects.murdermystery.utils.services.ServiceRegistry; -import plugily.projects.murdermystery.utils.services.locale.Locale; -import plugily.projects.murdermystery.utils.services.locale.LocaleRegistry; -import plugily.projects.murdermystery.utils.services.locale.LocaleService; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.stream.Collectors; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class LanguageManager { - - private static final Properties properties = new Properties(); - private static Main plugin; - private static Locale pluginLocale; - private static FileConfiguration languageConfig; - private static FileConfiguration defaultLanguageConfig; - - private LanguageManager() { - } - - public static void init(Main plugin) { - LanguageManager.plugin = plugin; - if(!new File(LanguageManager.plugin.getDataFolder() + File.separator + "language.yml").exists()) { - plugin.saveResource("language.yml", false); - } - //auto update - plugin.saveResource("locales/language_default.yml", true); - - new LanguageMigrator(plugin); - languageConfig = ConfigUtils.getConfig(plugin, "language"); - defaultLanguageConfig = ConfigUtils.getConfig(plugin, "locales/language_default"); - registerLocales(); - setupLocale(); - } - - private static void registerLocales() { - Arrays.asList( - new Locale("Afrikaans", "Afrikaans", "af_ZA", "POEditor contributors", Arrays.asList("afrika", "af", "afr")), - new Locale("Chinese (Simplified)", "简体中文", "zh_CN", "POEditor contributors", Arrays.asList("简体中文", "中文", "chinese", "chinese_simplified", "cn")), - new Locale("Chinese (Traditional)", "繁體中文", "zh_TW", "POEditor contributors", Arrays.asList("中文(繁體)", "繁體中文", "chinese_traditional", "zh_tw")), - new Locale("Czech", "Český", "cs_CZ", "POEditor contributors", Arrays.asList("czech", "cesky", "český", "cs")), - new Locale("Danish", "Dänemark", "da_DK", "POEditor contributors", Arrays.asList("dänisch", "da", "dk")), - new Locale("Dutch", "Nederlands", "nl_NL", "POEditor contributors", Arrays.asList("dutch", "nederlands", "nl")), - new Locale("English", "English", "en_GB", "Plajer", Arrays.asList("default", "english", "en")), - new Locale("French", "Français", "fr_FR", "POEditor contributors", Arrays.asList("french", "francais", "français", "fr")), - new Locale("German", "Deutsch", "de_DE", "Tigerkatze and POEditor contributors", Arrays.asList("deutsch", "german", "de")), - new Locale("Hungarian", "Magyar", "hu_HU", "POEditor contributors", Arrays.asList("hungarian", "magyar", "hu")), - new Locale("Indonesian", "Indonesia", "id_ID", "POEditor contributors", Arrays.asList("indonesian", "indonesia", "id")), - new Locale("Italian", "Italiano", "it_IT", "POEditor contributors", Arrays.asList("italian", "italiano", "it")), - new Locale("Japanese", "Japan", "ja_JP", "POEditor contributors", Arrays.asList("japan", "japanese", "ja")), - new Locale("Korean", "한국의", "ko_KR", "POEditor contributors", Arrays.asList("korean", "한국의", "kr")), - new Locale("Polish", "Polski", "pl_PL", "Plajer", Arrays.asList("polish", "polski", "pl")), - new Locale("Portuguese (BR)", "Português (Brasil)", "pt_BR", "POEditor contributors", Arrays.asList("portuguese br", "português br", "português brasil", "pt_br")), - new Locale("Romanian", "Românesc", "ro_RO", "POEditor contributors", Arrays.asList("romanian", "romanesc", "românesc", "ro")), - new Locale("Russian", "Pусский", "ru_RU", "POEditor contributors", Arrays.asList("russian", "pусский", "pyccknn", "russkiy", "ru")), - new Locale("Slovak", "Slovenský", "sk_SK", "POEditor contributors", Arrays.asList("slovak", "slovenský", "slovensky", "sk")), - new Locale("Spanish", "Español", "es_ES", "POEditor contributors", Arrays.asList("spanish", "espanol", "español", "es")), - new Locale("Thai", "Thai", "th_TH", "POEditor contributors", Arrays.asList("thai", "th")), - new Locale("Turkish", "Türkçe", "tr_TR", "POEditor contributors", Arrays.asList("turkish", "türkçe", "turkce", "tr")), - new Locale("Ukrainian", "Ukraine", "uk_UA", "POEditor contributors", Arrays.asList("ukraine", "ua", "uk")), - new Locale("Vietnamese", "Việt", "vn_VN", "POEditor contributors", Arrays.asList("vietnamese", "viet", "việt", "vn"))) - .forEach(LocaleRegistry::registerLocale); - } - - private static void loadProperties() { - LocaleService service = ServiceRegistry.getLocaleService(plugin); - /* is beta release */ - if((plugin.getDescription().getVersion().contains("locales") || plugin.getDescription().getVersion().contains("pre")) && !plugin.getConfig().getBoolean("Developer-Mode", false)) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Locales aren't supported in beta versions because they're lacking latest translations! Enabling English one..."); - pluginLocale = LocaleRegistry.getByName("English"); - return; - } - if(service == null) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Locales cannot be downloaded because API website is unreachable, locales will be disabled."); - pluginLocale = LocaleRegistry.getByName("English"); - return; - } - if(service.isValidVersion()) { - LocaleService.DownloadStatus status = service.demandLocaleDownload(pluginLocale); - if(status == LocaleService.DownloadStatus.FAIL) { - pluginLocale = LocaleRegistry.getByName("English"); - Debugger.sendConsoleMsg("&c[Murder Mystery] Locale service couldn't download latest locale for plugin! English locale will be used instead!"); - return; - } else if(status == LocaleService.DownloadStatus.SUCCESS) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Downloaded locale " + pluginLocale.getPrefix() + " properly!"); - } else if(status == LocaleService.DownloadStatus.LATEST) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Locale " + pluginLocale.getPrefix() + " is latest! Awesome!"); - } - } else { - pluginLocale = LocaleRegistry.getByName("English"); - Debugger.sendConsoleMsg("&c[Murder Mystery] Your plugin version is too old to use latest locale! Please update plugin to access latest updates of locale!"); - return; - } - try(InputStreamReader reader = new InputStreamReader(new FileInputStream(plugin.getDataFolder() + "/locales/" - + pluginLocale.getPrefix() + ".properties"), StandardCharsets.UTF_8)) { - properties.load(reader); - } catch(IOException e) { - e.printStackTrace(); - } - } - - private static void setupLocale() { - String localeName = plugin.getConfig().getString("locale", "default").toLowerCase(); - for(Locale locale : LocaleRegistry.getRegisteredLocales()) { - if(locale.getPrefix().equalsIgnoreCase(localeName)) { - pluginLocale = locale; - break; - } - for(String alias : locale.getAliases()) { - if(alias.equals(localeName)) { - pluginLocale = locale; - break; - } - } - } - if(pluginLocale == null) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Plugin locale is invalid! Using default one..."); - pluginLocale = LocaleRegistry.getByName("English"); - } - Debugger.sendConsoleMsg("&a[Murder Mystery] Loaded locale " + pluginLocale.getName() + " (" + pluginLocale.getOriginalName() + " ID: " - + pluginLocale.getPrefix() + ") by " + pluginLocale.getAuthor()); - loadProperties(); - } - - public static boolean isDefaultLanguageUsed() { - return pluginLocale.getName().equals("English"); - } - - public static String getLanguageMessage(String path) { - if(isDefaultLanguageUsed()) { - return getString(path); - } - String prop = properties.getProperty(path); - if(prop == null) { - return getString(path); - } - if(getString(path).equalsIgnoreCase(defaultLanguageConfig.getString(path, "not found"))) { - return prop; - } - return getString(path); - } - - public static List getLanguageList(String path) { - if(isDefaultLanguageUsed()) { - return getStrings(path); - } - String prop = properties.getProperty(path); - if(prop == null) { - return getStrings(path); - } - if(getString(path).equalsIgnoreCase(defaultLanguageConfig.getString(path, "not found"))) { - return Arrays.asList(plugin.getChatManager().colorRawMessage(prop).split(";")); - } - return getStrings(path); - } - - - private static List getStrings(String path) { - if(!languageConfig.isSet(path)) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Game message not found in your locale!"); - Debugger.sendConsoleMsg("&c[Murder Mystery] Please regenerate your language.yml file! If error still occurs report it to the developer on discord!"); - Debugger.sendConsoleMsg("&c[Murder Mystery] Path: " + path); - return Collections.singletonList("ERR_MESSAGE_" + path + "_NOT_FOUND"); - } - List list = languageConfig.getStringList(path); - list = list.stream().map(string -> string = plugin.getChatManager().colorRawMessage(string)).collect(Collectors.toList()); - return list; - } - - - private static String getString(String path) { - if(!languageConfig.isSet(path)) { - Debugger.sendConsoleMsg("&c[Murder Mystery] Game message not found in your locale!"); - Debugger.sendConsoleMsg("&c[Murder Mystery] Please regenerate your language.yml file! If error still occurs report it to the developer on discord!"); - Debugger.sendConsoleMsg("&c[Murder Mystery] Path: " + path); - return "ERR_MESSAGE_" + path + "_NOT_FOUND"; - } - return languageConfig.getString(path, "not found"); - } - - public static void reloadConfig() { - languageConfig = ConfigUtils.getConfig(plugin, "language"); - } - - public static Locale getPluginLocale() { - return pluginLocale; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/language/LanguageMigrator.java b/src/main/java/plugily/projects/murdermystery/handlers/language/LanguageMigrator.java deleted file mode 100644 index b6778b31..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/language/LanguageMigrator.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.language; - -import org.apache.commons.lang.math.NumberUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.configuration.file.FileConfiguration; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.migrator.MigratorUtils; -import plugily.projects.murdermystery.Main; - -import java.io.File; - -/* - NOTE FOR CONTRIBUTORS - Please do not touch this class if you don't now how it works! You can break migrator modyfing these values! - */ -@SuppressWarnings("deprecation") -public class LanguageMigrator { - - public static final int CONFIG_FILE_VERSION = 23; - public static final int LANGUAGE_FILE_VERSION = 8; - private final Main plugin; - - public LanguageMigrator(Main plugin) { - this.plugin = plugin; - - //initializes migrator to update files with latest values - configUpdate(); - languageFileUpdate(); - } - - private void configUpdate() { - if(plugin.getConfig().getInt("Version") == CONFIG_FILE_VERSION) { - return; - } - Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Murder Mystery] System notify >> Your config file is outdated! Updating..."); - File file = new File(plugin.getDataFolder() + "/config.yml"); - File bungeefile = new File(plugin.getDataFolder() + "/bungee.yml"); - - int version = plugin.getConfig().getInt("Version", CONFIG_FILE_VERSION - 1); - - for(int i = version; i < CONFIG_FILE_VERSION; i++) { - switch(i) { - case 1: - MigratorUtils.addNewLines(file, "\r\n# How many blocks per tick sword thrown by murderer should fly\r\n" + - "# Please avoid high values as it might look like the sword is\r\n" + - "# blinking each tick\r\n" + - "Murderer-Sword-Speed: 0.65\r\n"); - break; - case 2: - MigratorUtils.addNewLines(file, "\r\n# Should players' name tags in game be hidden?\r\n" + - "Nametags-Hidden: true\r\n"); - break; - case 3: - MigratorUtils.addNewLines(file, "\r\n# Lobby waiting time set when lobby max players number is reached, used to start game quicker.\r\n" + - "Start-Time-On-Full-Lobby: 15\r\n"); - break; - case 4: - MigratorUtils.addNewLines(file, "\r\n# Should players get no fall damage?\r\n" + - "Disable-Fall-Damage: false\r\n"); - break; - case 5: - MigratorUtils.addNewLines(file, "\r\n#How long should be the sword attack after throw cooldown in seconds?\r\n" + - "#Its normal lower than Murderer-Sword-Fly-Cooldown!\r\n" + - "Murderer-Sword-Attack-Cooldown: 1\r\n" + - "\r\n" + - "#How long should be the sword fly cooldown in seconds?\r\n" + - "Murderer-Sword-Fly-Cooldown: 5\r\n" + - "\r\n" + - "#How long should be the bow shoot cooldown in seconds?\r\n" + - "Detective-Bow-Cooldown: 5\r\n"); - break; - case 6: - MigratorUtils.addNewLines(file, "\r\n# Which item should be your Murderer sword?\r\n" + - "Murderer-Sword-Material: IRON_SWORD\r\n"); - break; - case 7: - MigratorUtils.addNewLines(file, "\r\n#How much arrows should a player with bow gets when he pick up a gold ingot?\r\n" + - "Detective-Gold-Pick-Up-Arrows: 1\r\n" + - "\r\n" + - "#How much arrows should the detective gets on game start or when a player get a bow?\r\n" + - "Detective-Default-Arrows: 3\r\n" + - "\r\n" + - "#How much arrows should the player get when the prayer gives a bow to him?\r\n" + - "Detective-Prayer-Arrows: 2\r\n"); - break; - case 8: - MigratorUtils.removeLineFromFile(bungeefile, "# This is useful for bungee game systems."); - MigratorUtils.removeLineFromFile(bungeefile, "# Game state will be visible at MOTD."); - MigratorUtils.removeLineFromFile(bungeefile, "MOTD-manager: false"); - MigratorUtils.removeLineFromFile(bungeefile, "MOTD-manager: true"); - MigratorUtils.addNewLines(bungeefile, "\r\n# This is useful for bungee game systems.\r\n" + - "# %state% - Game state will be visible at MOTD.\r\n" + - "MOTD:\r\n" + - " Manager: false\r\n" + - " Message: \"The actual game state of mm is %state%\"\r\n" + - " Game-States:\r\n" + - " Inactive: \"&lInactive...\"\r\n" + - " In-Game: \"&lIn-game\"\r\n" + - " Starting: \"&e&lStarting\"\r\n" + - " Full-Game: \"&4&lFULL\"\r\n" + - " Ending: \"&lEnding\"\r\n" + - " Restarting: \"&c&lRestarting\"\r\n"); - break; - case 9: - MigratorUtils.addNewLines(file, "\r\n" + - "# Should we enable short commands such as /start and /leave\r\n" + - "Enable-Short-Commands: false\r\n"); - break; - case 10: - MigratorUtils.addNewLines(file, "\r\n" + - "#Should Detectives be killed if they kill a innocent?\r\n" + - "Enable-Kill-Detective-If-Innocent-Killed: true\r\n"); - break; - case 11: - MigratorUtils.addNewLines(file, "\r\n#Should the murderer get speed effect?\r\n" + - "Speed-Effect-Murderer:\r\n" + - " Enabled: true\r\n" + - " #Enter a multiplier (min 2, max 10)\r\n" + - " Speed: 3\r\n"); - break; - case 12: - MigratorUtils.addNewLines(file, "\r\n" + - "#Should we change spawner mode to spawn on all spawners instant of random one\r\n" + - "Change-Gold-Spawner-Mode-To-All: false\r\n"); - MigratorUtils.addNewLines(file, "\r\n" + - "#Should we disable the gold spawn limit (It does not spawn more gold than spawner locations)\r\n" + - "Disable-Gold-Limiter: false\r\n"); - break; - case 13: - MigratorUtils.addNewLines(file, "\r\n" + - "# How many blocks should the sword fly\r\n" + - "Murderer-Sword-Fly-Range: 20\r\n" + - "\r\n" + - "# In what radius should we hit the players\r\n" + - "Murderer-Sword-Fly-Hit-Range: 0.5\r\n"); - break; - case 14: - MigratorUtils.addNewLines(file, "\r\n" + - "#How much gold should a player need to get a bow\r\n" + - "Gold-For-Bow: 10\r\n"); - break; - case 15: - MigratorUtils.addNewLines(file, "\r\n" + - "#How much arrows should the fake detective get? (Cause: Player pick up bow after detective died)\r\n" + - "Detective-Fake-Arrows: 3\r\n" + - "\r\n" + - "#How much arrows should the player get? (Cause: Bow because enough gold collected)\r\n" + - "Gold-Bow-Arrows: 3\r\n"); - break; - case 16: - MigratorUtils.addNewLines(file, "\r\n" + - "# Should we disable all chat related stuff?\r\n" + - "# It will disable the separated chat, for example\r\n" + - "Disable-Separate-Chat: false\r\n"); - break; - case 17: - MigratorUtils.addNewLines(file, "\r\n" + - "#Disable Party features of external party plugins (such as PAF, Parties ...)\r\n" + - "Disable-Parties: true\r\n"); - break; - case 18: - MigratorUtils.addNewLines(file, "\r\n" + - "#Should there be a innocent locator\r\n" + - "Enable-Innocent-Locator: true\r\n"); - break; - case 19: - MigratorUtils.addNewLines(file, "\r\n" + - "# Should we disable death messages, so the player dies without other recognizes it\r\n" + - "# It will not broadcast the death message to all ;)\r\n" + - "Hide-Death: false\r\n" + - "\r\n"); - break; - case 20: - MigratorUtils.addNewLines(file, "\r\nArena-Selector:\r\n" + - " Items:\r\n" + - " waiting-for-players: lime_concrete\r\n" + - " starting: yellow_concrete\r\n" + - " other: red_concrete\r\n"); - break; - case 21: - MigratorUtils.insertAfterLine(file, "Arena-Selector:", " State-Item:\r\n" + - " Waiting: LIME_wool\r\n" + - " Starting: YELLOW_wool\r\n" + - " In-Game: RED_wool\r\n" + - " Ending: RED_wool\r\n" + - " Restarting: RED_wool\r\n"); - break; - case 22: - MigratorUtils.addNewLines(file, "\r\n#Add trails that you want to blacklist from all trails(particles)\r\n" + - "Blacklisted-Trails:\r\n" + - " - \"elder_guardian\"\r\n" + - " - \"block_crack\"\r\n" + - " - \"item_crack\"\r\n" + - " - \"block_dust\"\r\n"); - default: - break; - } - i++; - } - updateConfigVersionControl(version); - plugin.reloadConfig(); - Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[Murder Mystery] [System notify] Config updated, no comments were removed :)"); - Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[Murder Mystery] [System notify] You're using latest config file version! Nice!"); - } - - private void languageFileUpdate() { - FileConfiguration config = ConfigUtils.getConfig(plugin, "language"); - if(config.getString("File-Version-Do-Not-Edit", "").equals(Integer.toString(LANGUAGE_FILE_VERSION))) { - return; - } - Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[Murder Mystery] [System notify] Your language file is outdated! Updating..."); - - int version = LANGUAGE_FILE_VERSION - 1; - if(NumberUtils.isNumber(config.getString("File-Version-Do-Not-Edit"))) { - version = Integer.parseInt(config.getString("File-Version-Do-Not-Edit")); - } else { - Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[Murder Mystery] [System notify] Failed to parse language file version!"); - } - updateLanguageVersionControl(version); - - File file = new File(plugin.getDataFolder() + "/language.yml"); - - for(int i = version; i < LANGUAGE_FILE_VERSION; i++) { - switch(version) { - case 1: - MigratorUtils.insertAfterLine(file, "Lobby-Messages:", " Not-Enough-Space-For-Party: \"&cYour party is bigger than free places on the arena %ARENANAME%\""); - MigratorUtils.insertAfterLine(file, "In-Game:", " Join-As-Party-Member: \"&cYou joined %ARENANAME% because the party leader joined it!\""); - break; - case 2: - MigratorUtils.addNewLines(file, "Arena-Selector:\r\n" + - " Inv-Title: \"Arena selector\"\r\n" + - " Item:\r\n" + - " Name: \"&f%mapname%\"\r\n" + - " Lore:\r\n" + - " - \"&4Murder Mystery &f- &e%mapname%\"\r\n" + - " - \" \"\r\n" + - " - \" \"\r\n" + - " - \" &fOnline: %playersize%/%maxplayers%\"\r\n" + - " - \" &fState: %state%\"\r\n" + - " - \" \"\r\n" + - " - \" \"\r\n" + - " - \"&eClick to join this arena\"\r\n"); - break; - case 3: - MigratorUtils.insertAfterLine(file, "In-Game:", " Game-Death-Format: \"&7[&4☠&7] &r\""); - break; - case 4: - MigratorUtils.insertAfterLine(file, " Item:", " Name: \"&f%mapname%\""); - break; - case 5: - MigratorUtils.addNewLines(file, "Placeholders:\r\n" + - " Game-States:\r\n" + - " Waiting: \"&lWaiting for players...\"\r\n" + - " Starting: \"&e&lStarting\"\r\n" + - " In-Game: \"&lPlaying\"\r\n" + - " Ending: \"&lEnding\"\r\n" + - " Restarting: \"&c&lRestarting\"\r\n"); - break; - case 6: - //No migrator as we can't handle that - break; - case 7: - MigratorUtils.insertAfterLine(file, " Spectator:", " Target-Player-Health: \"&cHealth: &7%health%\"\r\n"); - MigratorUtils.insertAfterLine(file, "In-Game:", " Role-Pass:\r\n" + - " Menu-Name: \"Role pass menu\"\r\n" + - " Role:\r\n" + - " Murderer:\r\n" + - " Name: \"Be murderer\"\r\n" + - " Lore:\r\n" + - " - \"Cost 1 murderer pass\"\r\n" + - " - \"You got %amount%\"\r\n" + - " Detective:\r\n" + - " Name: \"Be detective\"\r\n" + - " Lore:\r\n" + - " - \"Cost 1 detective pass\"\r\n" + - " - \"You got %amount%\"\r\n" + - " Fail: \"You do not got enough passes for %role% role\"\r\n" + - " Success: \"You will be %role% next round!\"\r\n" + - " Change: \"You now got %amount% %role% passes!\"\r\n"); - default: - break; - } - version++; - } - Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[Murder Mystery] [System notify] Language file updated! Nice!"); - Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[Murder Mystery] [System notify] You're using latest language file version! Nice!"); - } - - private void updateConfigVersionControl(int oldVersion) { - File file = new File(plugin.getDataFolder() + "/config.yml"); - MigratorUtils.removeLineFromFile(file, "# Don't modify"); - MigratorUtils.removeLineFromFile(file, "Version: " + oldVersion); - MigratorUtils.removeLineFromFile(file, "# No way! You've reached the end! But... where's the dragon!?"); - MigratorUtils.addNewLines(file, "# Don't modify\r\nVersion: " + CONFIG_FILE_VERSION + "\r\n# No way! You've reached the end! But... where's the dragon!?"); - } - - private void updateLanguageVersionControl(int oldVersion) { - File file = new File(plugin.getDataFolder() + "/language.yml"); - MigratorUtils.removeLineFromFile(file, "# Don't edit it. But who's stopping you? It's your server!"); - MigratorUtils.removeLineFromFile(file, "# Really, don't edit ;p"); - MigratorUtils.removeLineFromFile(file, "File-Version-Do-Not-Edit: " + oldVersion); - MigratorUtils.addNewLines(file, "# Don't edit it. But who's stopping you? It's your server!\r\n# Really, don't edit ;p\r\nFile-Version-Do-Not-Edit: " + LANGUAGE_FILE_VERSION + "\r\n"); - } -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWord.java b/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWord.java index 83440484..0aaa58b8 100644 --- a/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWord.java +++ b/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWord.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWordsManager.java b/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWordsManager.java index a0a8dfbe..50672965 100644 --- a/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWordsManager.java +++ b/src/main/java/plugily/projects/murdermystery/handlers/lastwords/LastWordsManager.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,9 +20,9 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.utils.configuration.ConfigUtils; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.utils.Debugger; import java.util.ArrayList; import java.util.List; @@ -38,25 +38,19 @@ public class LastWordsManager { private final List registeredLastWords = new ArrayList<>(); + private String hologramTitle = ""; + public LastWordsManager(Main plugin) { registerLastWords(plugin); } public void registerLastWords(Main plugin) { - FileConfiguration config = ConfigUtils.getConfig(plugin, "language"); - ConfigurationSection section = config.getConfigurationSection("In-Game.Messages.Last-Words"); - if(section == null) { - //use old formatting under v1.7.5 - addLastWord(new LastWord(plugin.getChatManager().colorMessage("In-Game.Messages.Last-Words.Meme"), "murdermystery.lastwords.meme")); - addLastWord(new LastWord(plugin.getChatManager().colorMessage("In-Game.Messages.Last-Words.Rage"), "murdermystery.lastwords.rage")); - addLastWord(new LastWord(plugin.getChatManager().colorMessage("In-Game.Messages.Last-Words.Pro"), "murdermystery.lastwords.pro")); - addLastWord(new LastWord(plugin.getChatManager().colorMessage("In-Game.Messages.Last-Words.Default"), "")); - Debugger.sendConsoleMsg("[Murder Mystery] Please check your language.yml and update it to the new last words design that can be found on the latest language.yml"); - return; - } - String path = "In-Game.Messages.Last-Words."; + FileConfiguration config = ConfigUtils.getConfig(plugin, "lastwords"); + hologramTitle = config.getString("Last-Words.Hologram.Title", "-"); + ConfigurationSection section = config.getConfigurationSection("Last-Words.Hologram.Content"); + String path = "Last-Words.Hologram.Content."; for(String id : section.getKeys(false)) { - addLastWord(new LastWord(plugin.getChatManager().colorMessage(path + id + ".Message"), config.getString(path + id + ".Permission", ""))); + addLastWord(new LastWord(new MessageBuilder(config.getString(path + id + ".Message")).build(), config.getString(path + id + ".Permission", ""))); } } @@ -64,6 +58,10 @@ public List getRegisteredLastWords() { return registeredLastWords; } + public String getHologramTitle() { + return hologramTitle; + } + public void addLastWord(LastWord lastWord) { registeredLastWords.add(lastWord); } diff --git a/src/main/java/plugily/projects/murdermystery/handlers/party/PAFBPartyHandlerImpl.java b/src/main/java/plugily/projects/murdermystery/handlers/party/PAFBPartyHandlerImpl.java deleted file mode 100644 index daddeb27..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/party/PAFBPartyHandlerImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.party; - -import de.simonsator.partyandfriends.spigot.api.pafplayers.PAFPlayer; -import de.simonsator.partyandfriends.spigot.api.pafplayers.PAFPlayerManager; -import de.simonsator.partyandfriends.spigot.api.party.PartyManager; -import de.simonsator.partyandfriends.spigot.api.party.PlayerParty; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -/** - * @author Plajer - *

- * Created at 09.02.2020 - */ -public class PAFBPartyHandlerImpl implements PartyHandler { - - @Override - public boolean isPlayerInParty(Player player) { - return PartyManager.getInstance().getParty(PAFPlayerManager.getInstance().getPlayer(player.getUniqueId())) != null; - } - - @Override - public GameParty getParty(Player player) { - PartyManager api = PartyManager.getInstance(); - PAFPlayer partyPlayer = PAFPlayerManager.getInstance().getPlayer(player.getUniqueId()); - PlayerParty party = api.getParty(partyPlayer); - - java.util.List players = new java.util.ArrayList<>(); - - for (PAFPlayer localPlayer : party.getAllPlayers()) { - Player pl = Bukkit.getPlayer(localPlayer.getUniqueId()); - - if (pl != null) - players.add(pl); - } - - return new GameParty(players, Bukkit.getPlayer(party.getLeader().getUniqueId())); - } - - @Override - public boolean partiesSupported() { - return true; - } - - @Override - public PartyPluginType getPartyPluginType() { - return PartyPluginType.PAFBungee; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/party/PAFSPartyHandlerImpl.java b/src/main/java/plugily/projects/murdermystery/handlers/party/PAFSPartyHandlerImpl.java deleted file mode 100644 index f962b714..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/party/PAFSPartyHandlerImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.party; - -import de.simonsator.partyandfriends.api.pafplayers.OnlinePAFPlayer; -import de.simonsator.partyandfriends.api.party.PartyManager; -import de.simonsator.partyandfriends.api.party.PlayerParty; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -/** - * @author Plajer - *

- * Created at 09.02.2020 - */ -public class PAFSPartyHandlerImpl implements PartyHandler { - - @Override - public boolean isPlayerInParty(Player player) { - return PartyManager.getInstance().getParty(player.getUniqueId()) != null; - } - - @Override - public GameParty getParty(Player player) { - PartyManager api = PartyManager.getInstance(); - PlayerParty party = api.getParty(player.getUniqueId()); - - java.util.List players = new java.util.ArrayList<>(); - - for (OnlinePAFPlayer localPlayer : party.getAllPlayers()) { - Player pl = Bukkit.getPlayer(localPlayer.getUniqueId()); - - if (pl != null) - players.add(pl); - } - - return new GameParty(players, Bukkit.getPlayer(party.getLeader().getUniqueId())); - } - - @Override - public boolean partiesSupported() { - return true; - } - - @Override - public PartyPluginType getPartyPluginType() { - return PartyPluginType.PAFSpigot; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/party/PartiesPartyHandlerImpl.java b/src/main/java/plugily/projects/murdermystery/handlers/party/PartiesPartyHandlerImpl.java deleted file mode 100644 index 067005b7..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/party/PartiesPartyHandlerImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.party; - -import com.alessiodp.parties.api.Parties; -import com.alessiodp.parties.api.interfaces.PartiesAPI; -import com.alessiodp.parties.api.interfaces.Party; -import com.alessiodp.parties.api.interfaces.PartyPlayer; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -/** - * @author Plajer - *

- * Created at 09.02.2020 - */ -public class PartiesPartyHandlerImpl implements PartyHandler { - - @Override - public boolean isPlayerInParty(Player player) { - PartiesAPI api = Parties.getApi(); - PartyPlayer partyPlayer = api.getPartyPlayer(player.getUniqueId()); - if(partyPlayer == null) return false; - - Party party = api.getParty(partyPlayer.getPartyId()); - return party != null && party.getMembers().size() > 1; - } - - @Override - public GameParty getParty(Player player) { - PartiesAPI api = Parties.getApi(); - PartyPlayer partyPlayer = api.getPartyPlayer(player.getUniqueId()); - Party party = api.getParty(partyPlayer.getPartyId()); - - java.util.List players = new java.util.ArrayList<>(); - - for (PartyPlayer localPlayer : party.getOnlineMembers(true)) { - Player pl = Bukkit.getPlayer(localPlayer.getPlayerUUID()); - - if (pl != null) - players.add(pl); - } - - return new GameParty(players, Bukkit.getPlayer(party.getLeader())); - } - - @Override - public boolean partiesSupported() { - return true; - } - - @Override - public PartyPluginType getPartyPluginType() { - return PartyPluginType.PARTIES; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/party/PartyHandler.java b/src/main/java/plugily/projects/murdermystery/handlers/party/PartyHandler.java deleted file mode 100644 index d12359a3..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/party/PartyHandler.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.party; - -import org.bukkit.entity.Player; - -/** - * @author Plajer - *

- * Created at 09.02.2020 - */ -public interface PartyHandler { - - boolean isPlayerInParty(Player player); - - GameParty getParty(Player player); - - boolean partiesSupported(); - - PartyPluginType getPartyPluginType(); - - enum PartyPluginType { - PARTIES, PAFSpigot, PAFBungee, NONE - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/party/PartySupportInitializer.java b/src/main/java/plugily/projects/murdermystery/handlers/party/PartySupportInitializer.java deleted file mode 100644 index 7e283f8c..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/party/PartySupportInitializer.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.party; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; - -/** - * @author Plajer - *

- * Created at 09.02.2020 - */ -public class PartySupportInitializer { - - public PartyHandler initialize(Main plugin) { - PartyHandler partyHandler; - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DISABLE_PARTIES)) { - if(Bukkit.getServer().getPluginManager().getPlugin("Parties") != null) { - return new PartiesPartyHandlerImpl(); - } else if(Bukkit.getServer().getPluginManager().getPlugin("Spigot-Party-API-PAF") != null) { - return new PAFBPartyHandlerImpl(); - } else if(Bukkit.getServer().getPluginManager().getPlugin("PartyAndFriends") != null) { - return new PAFSPartyHandlerImpl(); - } - } - partyHandler = new PartyHandler() { - @Override - public boolean isPlayerInParty(Player player) { - return false; - } - - @Override - public GameParty getParty(Player player) { - return null; - } - - @Override - public boolean partiesSupported() { - return false; - } - - @Override - public PartyPluginType getPartyPluginType() { - return PartyPluginType.NONE; - } - }; - return partyHandler; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/rewards/Reward.java b/src/main/java/plugily/projects/murdermystery/handlers/rewards/Reward.java deleted file mode 100644 index bd7cac77..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/rewards/Reward.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.rewards; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; - -/** - * @author Plajer - *

- * Created at 06.04.2019 - */ -public class Reward { - - private final RewardType type; - private final RewardExecutor executor; - private String executableCode; - private final double chance; - - public Reward(RewardType type, String rawCode) { - this.type = type; - String processedCode = rawCode; - - //set reward executor based on provided code - if(rawCode.contains("p:")) { - this.executor = RewardExecutor.PLAYER; - processedCode = StringUtils.replace(processedCode, "p:", ""); - } else if(rawCode.contains("script:")) { - this.executor = RewardExecutor.SCRIPT; - processedCode = StringUtils.replace(processedCode, "script:", ""); - } else { - this.executor = RewardExecutor.CONSOLE; - } - - //search for chance modifier - if(processedCode.contains("chance(")) { - int loc = processedCode.indexOf(")"); - //modifier is invalid - if(loc == -1) { - Bukkit.getLogger().warning("rewards.yml configuration is broken! Make sure you don't forget using ')' character in chance condition! Command: " + rawCode); - //invalid code, 0% chance to execute - this.chance = 0.0; - return; - } - String chanceStr = processedCode; - chanceStr = chanceStr.substring(0, loc).replaceAll("[^0-9]+", ""); - double chance = Double.parseDouble(chanceStr); - processedCode = StringUtils.replace(processedCode, "chance(" + chanceStr + "):", ""); - this.chance = chance; - } else { - this.chance = 100.0; - } - this.executableCode = processedCode; - } - - public RewardExecutor getExecutor() { - return executor; - } - - public String getExecutableCode() { - return executableCode; - } - - public double getChance() { - return chance; - } - - public RewardType getType() { - return type; - } - - public enum RewardType { - DETECTIVE_KILL("detectivekill"), MURDERER_KILL("murdererkill"), END_GAME("endgame"), - LOSE("lose"), WIN("win"), DEATH("death"), GOLD_PICKUP("gold_pickup"); - - private final String path; - - RewardType(String path) { - this.path = path; - } - - public String getPath() { - return path; - } - - } - - public enum RewardExecutor { - CONSOLE, PLAYER, SCRIPT - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/rewards/RewardsFactory.java b/src/main/java/plugily/projects/murdermystery/handlers/rewards/RewardsFactory.java deleted file mode 100644 index 6aeea3f3..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/rewards/RewardsFactory.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.rewards; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.engine.ScriptEngine; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.utils.Debugger; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ThreadLocalRandom; -import java.util.logging.Level; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class RewardsFactory { - - private final Set rewards = new HashSet<>(); - private final FileConfiguration config; - private final boolean enabled; - - public RewardsFactory(Main plugin) { - enabled = plugin.getConfig().getBoolean("Rewards-Enabled"); - config = ConfigUtils.getConfig(plugin, "rewards"); - registerRewards(); - } - - public void performReward(Arena arena, Reward.RewardType type) { - if(enabled) { - arena.getPlayers().forEach(p -> performReward(p, type)); - } - } - - public void performReward(Player player, Reward.RewardType type) { - if(!enabled) { - return; - } - Arena arena = ArenaRegistry.getArena(player); - if(arena == null) { - return; - } - for(Reward reward : rewards) { - if(reward.getType() == type) { - //cannot execute if chance wasn't met - if(reward.getChance() != -1 && ThreadLocalRandom.current().nextInt(0, 100) > reward.getChance()) { - continue; - } - String command = reward.getExecutableCode(); - command = StringUtils.replace(command, "%PLAYER%", player.getName()); - command = formatCommandPlaceholders(command, arena); - switch(reward.getExecutor()) { - case CONSOLE: - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); - break; - case PLAYER: - player.performCommand(command); - break; - case SCRIPT: - ScriptEngine engine = new ScriptEngine(); - engine.setValue("player", player); - engine.setValue("server", Bukkit.getServer()); - engine.setValue("arena", arena); - engine.execute(command); - break; - default: - break; - } - } - } - } - - private String formatCommandPlaceholders(String command, Arena arena) { - String formatted = command; - formatted = StringUtils.replace(formatted, "%ARENA-ID%", arena.getId()); - formatted = StringUtils.replace(formatted, "%MAPNAME%", arena.getMapName()); - formatted = StringUtils.replace(formatted, "%PLAYERAMOUNT%", Integer.toString(arena.getPlayers().size())); - return formatted; - } - - private void registerRewards() { - if(!enabled) { - return; - } - Debugger.debug(Level.INFO, "[RewardsFactory] Starting rewards registration"); - long start = System.currentTimeMillis(); - - Map registeredRewards = new HashMap<>(); - for(Reward.RewardType rewardType : Reward.RewardType.values()) { - try { - for(String reward : config.getStringList("rewards." + rewardType.getPath())) { - rewards.add(new Reward(rewardType, reward)); - registeredRewards.put(rewardType, registeredRewards.getOrDefault(rewardType, 0) + 1); - } - } catch(Exception ignored) {/*ignored*/} - } - for(Reward.RewardType rewardType : registeredRewards.keySet()) { - Debugger.debug(Level.INFO, "[RewardsFactory] Registered {0} {1} rewards!", registeredRewards.get(rewardType), rewardType.name()); - } - Debugger.debug(Level.INFO, "[RewardsFactory] Registered all rewards took {0}ms", System.currentTimeMillis() - start); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/LocationCategory.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/LocationCategory.java new file mode 100644 index 00000000..07af04c0 --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/handlers/setup/LocationCategory.java @@ -0,0 +1,53 @@ +/* + * + * MurderMystery + * Copyright (C) 2021 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package plugily.projects.murdermystery.handlers.setup; + +import plugily.projects.minigamesbox.classic.handlers.language.MessageBuilder; +import plugily.projects.minigamesbox.classic.handlers.setup.categories.PluginLocationCategory; +import plugily.projects.minigamesbox.classic.handlers.setup.categories.PluginSpecificCategory; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.CountItem; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.LocationItem; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.MultiLocationItem; +import plugily.projects.minigamesbox.classic.utils.helper.ItemBuilder; +import plugily.projects.minigamesbox.classic.utils.serialization.LocationSerializer; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; +import plugily.projects.minigamesbox.inventory.normal.NormalFastInv; + + +/** + * @author Tigerpanzer_02 + *

+ * Created at 01.07.2022 + */ +public class LocationCategory extends PluginLocationCategory { + @Override + public void addItems(NormalFastInv gui) { + super.addItems(gui); + + MultiLocationItem starting = new MultiLocationItem(getSetupInventory(), new ItemBuilder(XMaterial.EMERALD_BLOCK.parseMaterial()), "Player Spawn Points", "Location where players will be randomly teleported when the game starts", "playerspawnpoints", 4, inventoryClickEvent -> { + LocationSerializer.saveLoc(getSetupInventory().getPlugin(), getSetupInventory().getConfig(), "arenas", "instances." + getSetupInventory().getArenaKey() + "." + "startlocation", inventoryClickEvent.getWhoClicked().getLocation()); + }, (emptyConsumer) -> { + }, true, true, true); + getItemList().add(starting); + gui.setItem((getInventoryLine() * 9) + 2, starting); + } + +} \ No newline at end of file diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupCategoryManager.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupCategoryManager.java new file mode 100644 index 00000000..33c951ed --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupCategoryManager.java @@ -0,0 +1,22 @@ +package plugily.projects.murdermystery.handlers.setup; + +import plugily.projects.minigamesbox.classic.handlers.setup.SetupInventory; +import plugily.projects.minigamesbox.classic.handlers.setup.categories.PluginSetupCategoryManager; +import plugily.projects.minigamesbox.classic.handlers.setup.categories.SetupCategory; + +/** + * @author Tigerpanzer_02 + *

+ * Created at 01.07.2022 + */ +public class SetupCategoryManager extends PluginSetupCategoryManager { + + public SetupCategoryManager(SetupInventory setupInventory) { + super(setupInventory); + getCategoryHandler().put(SetupCategory.LOCATIONS, new LocationCategory()); + getCategoryHandler().put(SetupCategory.SPECIFIC, new SpecificCategory()); + getCategoryHandler().put(SetupCategory.SWITCH, new SwitchCategory()); + super.init(); + } + +} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupInventory.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupInventory.java deleted file mode 100644 index 73e10366..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupInventory.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup; - -import plugily.projects.inventoryframework.gui.type.ChestGui; -import plugily.projects.inventoryframework.pane.StaticPane; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.components.ArenaRegisterComponent; -import plugily.projects.murdermystery.handlers.setup.components.MiscComponents; -import plugily.projects.murdermystery.handlers.setup.components.PlayerAmountComponents; -import plugily.projects.murdermystery.handlers.setup.components.SpawnComponents; -import plugily.projects.murdermystery.handlers.setup.components.SpecialBlocksComponents; - -import java.util.Random; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class SetupInventory { - - public static final String VIDEO_LINK = "https://tutorial.plugily.xyz"; - private static final Random random = new Random(); - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private final FileConfiguration config = ConfigUtils.getConfig(plugin, "arenas"); - private final Arena arena; - private final Player player; - private ChestGui gui; - private final SetupUtilities setupUtilities; - - public SetupInventory(Arena arena, Player player) { - this.arena = arena; - this.player = player; - this.setupUtilities = new SetupUtilities(config, arena, plugin.getChatManager()); - prepareGui(); - } - - private void prepareGui() { - this.gui = new ChestGui(4, "Murder Mystery Arena Setup"); - this.gui.setOnGlobalClick(e -> e.setCancelled(true)); - StaticPane pane = new StaticPane(9, 4); - this.gui.addPane(pane); - - prepareComponents(pane); - } - - private void prepareComponents(StaticPane pane) { - SpawnComponents spawnComponents = new SpawnComponents(); - spawnComponents.prepare(this); - spawnComponents.injectComponents(pane); - - PlayerAmountComponents playerAmountComponents = new PlayerAmountComponents(); - playerAmountComponents.prepare(this); - playerAmountComponents.injectComponents(pane); - - MiscComponents miscComponents = new MiscComponents(); - miscComponents.prepare(this); - miscComponents.injectComponents(pane); - - ArenaRegisterComponent arenaRegisterComponent = new ArenaRegisterComponent(); - arenaRegisterComponent.prepare(this); - arenaRegisterComponent.injectComponents(pane); - - SpecialBlocksComponents specialBlocksComponents = new SpecialBlocksComponents(); - specialBlocksComponents.prepare(this); - specialBlocksComponents.injectComponents(pane); - } - - private void sendProTip(Player p) { - ChatManager chatManager = plugin.getChatManager(); - - switch(random.nextInt(16 + 1)) { - case 0: - p.sendMessage(chatManager.colorRawMessage("&e&lTIP: &7Help us translating plugin to your language here: https://translate.plugily.xyz")); - break; - case 1: - p.sendMessage(chatManager.colorRawMessage("&e&lTIP: &7PlaceholderApi plugin is supported with our plugin! Check here: https://wiki.plugily.xyz/murdermystery/placeholders/placeholderapi")); - break; - case 2: - p.sendMessage(chatManager.colorRawMessage("&e&lTIP: &7We are open source! You can always help us by contributing! Check https://github.com/Plugily-Projects/MurderMystery")); - break; - case 3: - p.sendMessage(chatManager.colorRawMessage("&e&lTIP: &7Need help? Check wiki &8https://wiki.plugily.xyz/minecraft/murdermystery &7or discord https://discord.gg/UXzUdTP")); - break; - case 4: - p.sendMessage(chatManager.colorRawMessage("&e&lTIP: &7Suggest new ideas for the plugin or vote on current ones! https://app.feedbacky.net/b/MurderMystery")); - break; - case 5: - p.sendMessage(chatManager.colorRawMessage("&e&lTIP: &7Achievements, ranks and replay ability are things available in our paid addon for this minigame! https://wiki.plugily.xyz/murdermystery/addon/overview")); - break; - default: - break; - } - } - - public void openInventory() { - sendProTip(player); - gui.show(player); - } - - public Main getPlugin() { - return plugin; - } - - public FileConfiguration getConfig() { - return config; - } - - public Arena getArena() { - return arena; - } - - public Player getPlayer() { - return player; - } - - public ChestGui getGui() { - return gui; - } - - public SetupUtilities getSetupUtilities() { - return setupUtilities; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupUtilities.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupUtilities.java deleted file mode 100644 index 3b827995..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/SetupUtilities.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; - -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.handlers.ChatManager; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class SetupUtilities { - - private final FileConfiguration config; - private final Arena arena; - private final ChatManager chatManager; - - SetupUtilities(FileConfiguration config, Arena arena, ChatManager chatManager) { - this.config = config; - this.arena = arena; - this.chatManager = chatManager; - } - - public String isOptionDone(String path) { - if(config.isSet(path)) { - return chatManager.colorRawMessage("&a&l✔ Completed &7(value: &8" + config.getString(path) + "&7)"); - } - return chatManager.colorRawMessage("&c&l✘ Not Completed"); - } - - public String isOptionDoneList(String path, int minimum) { - if(config.isSet(path)) { - if(config.getStringList(path).size() < minimum) { - return chatManager.colorRawMessage("&c&l✘ Not Completed | &cPlease add more spawns"); - } - return chatManager.colorRawMessage("&a&l✔ Completed &7(value: &8" + config.getStringList(path).size() + "&7)"); - } - return chatManager.colorRawMessage("&c&l✘ Not Completed"); - } - - public String isOptionDoneBool(String path) { - if(config.isSet(path)) { - if(Bukkit.getServer().getWorlds().get(0).getSpawnLocation().equals(LocationSerializer.getLocation(config.getString(path)))) { - return chatManager.colorRawMessage("&c&l✘ Not Completed"); - } - return chatManager.colorRawMessage("&a&l✔ Completed"); - } - return chatManager.colorRawMessage("&c&l✘ Not Completed"); - } - - public int getMinimumValueHigherThanZero(String path) { - int amount = config.getInt("instances." + arena.getId() + "." + path); - return amount == 0 ? 1 : amount; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/SpecificCategory.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/SpecificCategory.java new file mode 100644 index 00000000..190949f6 --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/handlers/setup/SpecificCategory.java @@ -0,0 +1,73 @@ +/* + * + * MurderMystery + * Copyright (C) 2021 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package plugily.projects.murdermystery.handlers.setup; + +import org.bukkit.Material; +import plugily.projects.minigamesbox.classic.handlers.setup.categories.PluginSpecificCategory; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.CountItem; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.MaterialLocationItem; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.MaterialMultiLocationItem; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.MultiLocationItem; +import plugily.projects.minigamesbox.classic.utils.helper.ItemBuilder; +import plugily.projects.minigamesbox.classic.utils.helper.MaterialUtils; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; +import plugily.projects.minigamesbox.inventory.normal.NormalFastInv; + +import java.util.Collections; + + +/** + * @author Tigerpanzer_02 + *

+ * Created at 01.07.2022 + */ +public class SpecificCategory extends PluginSpecificCategory { + @Override + public void addItems(NormalFastInv gui) { + super.addItems(gui); + + CountItem spawnGoldTime = new CountItem(getSetupInventory(), new ItemBuilder(XMaterial.REDSTONE_TORCH.parseMaterial()), "Gold Spawn Time (Seconds)", "How much gold should be spawned? \nThat means 1 gold spawned every ... seconds\nDefault: 5\nEvery 5 seconds it will spawn 1 gold", "spawngoldtime"); + gui.setItem((getInventoryLine() * 9) + 1, spawnGoldTime); + getItemList().add(spawnGoldTime); + + CountItem playerMurderer = new CountItem(getSetupInventory(), new ItemBuilder(XMaterial.IRON_SWORD.parseMaterial()), "Player Per Murderer", "How many murderer should be ingame? This means \none murderer for that amount of players. Default: \n5 players are 1 murderer, that means if we have \n14 Players it will calculate 2 murderer! \nSet it to 1 if you want only one murderer ", "playerpermurderer"); + gui.setItem((getInventoryLine() * 9) + 2, playerMurderer); + getItemList().add(playerMurderer); + + CountItem playerDetective = new CountItem(getSetupInventory(), new ItemBuilder(XMaterial.IRON_SWORD.parseMaterial()), "Player Per Murderer", "How many detectives should be ingame? This means \none detective for that amount of players. Default: \n7 players are 1 detective, that means if we have \n18 Players it will calculate 2 detectives! \nSet it to 1 if you want only one detective ", "playerperdetective"); + gui.setItem((getInventoryLine() * 9) + 3, playerDetective); + getItemList().add(playerDetective); + + MultiLocationItem goldSpawn = new MultiLocationItem(getSetupInventory(), new ItemBuilder(XMaterial.GOLD_INGOT.parseMaterial()), "Gold Spawn", "Add new gold spawn \n on the place you're standing at.", "goldspawnpoints", 4); + gui.setItem((getInventoryLine() * 9) + 4, goldSpawn); + getItemList().add(goldSpawn); + + MaterialMultiLocationItem mysteryCauldron = new MaterialMultiLocationItem(getSetupInventory(), new ItemBuilder(XMaterial.CAULDRON.parseMaterial()), "Mystery Cauldron", "Target a cauldron and add it to the game\nit will cost 1 gold per potion!\nConfigure cauldron potions \nin special_blocks.yml file!", "mystery-cauldrons", Collections.singleton(Material.CAULDRON), false, 0); + gui.setItem((getInventoryLine() * 9) + 5, mysteryCauldron); + getItemList().add(mysteryCauldron); + + MaterialMultiLocationItem confessional = new MaterialMultiLocationItem(getSetupInventory(), new ItemBuilder(XMaterial.ENCHANTING_TABLE.parseMaterial()), "Confessional", "Target enchanting table and\nadd praise to the developer\nconfessional, gift for\nthe developer costs 1 gold!\nAdd some levers in radius\nof 3 blocks near the enchant table\nto allow users to pray there!\nYou can either get gifts\nor curses from prayer!", "confessionals", Collections.singleton(XMaterial.ENCHANTING_TABLE.parseMaterial()), false, 0); + gui.setItem((getInventoryLine() * 9) + 6, confessional); + getItemList().add(confessional); + + } + +} \ No newline at end of file diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/SwitchCategory.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/SwitchCategory.java new file mode 100644 index 00000000..ba6f4063 --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/handlers/setup/SwitchCategory.java @@ -0,0 +1,29 @@ +package plugily.projects.murdermystery.handlers.setup; + +import org.bukkit.plugin.java.JavaPlugin; +import plugily.projects.minigamesbox.classic.PluginMain; +import plugily.projects.minigamesbox.classic.handlers.setup.categories.PluginSwitchCategory; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.BooleanItem; +import plugily.projects.minigamesbox.classic.handlers.setup.items.category.SwitchItem; +import plugily.projects.minigamesbox.classic.utils.helper.ItemBuilder; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; +import plugily.projects.minigamesbox.inventory.normal.NormalFastInv; +import plugily.projects.murdermystery.Main; + +import java.util.Arrays; + +/** + * @author Tigerpanzer_02 + *

+ * Created at 01.07.2022 + */ +public class SwitchCategory extends PluginSwitchCategory { + @Override + public void addItems(NormalFastInv gui) { + super.addItems(gui); + BooleanItem goldVisuals = new BooleanItem(getSetupInventory(), new ItemBuilder(XMaterial.REDSTONE.parseMaterial()), "Gold Visuals", "Enables gold visuals to spawn\nsome particle effects above gold locations", "goldvisuals"); + gui.setItem((getInventoryLine() * 9) + 1, goldVisuals); + getItemList().add(goldVisuals); + } + +} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/ArenaRegisterComponent.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/components/ArenaRegisterComponent.java deleted file mode 100644 index 0ecb0c59..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/ArenaRegisterComponent.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup.components; - -import plugily.projects.inventoryframework.gui.GuiItem; -import plugily.projects.inventoryframework.pane.StaticPane; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Sign; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.inventory.ItemStack; -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.special.SpecialBlock; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; -import plugily.projects.murdermystery.handlers.sign.ArenaSign; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class ArenaRegisterComponent implements SetupComponent { - - private SetupInventory setupInventory; - - @Override - public void prepare(SetupInventory setupInventory) { - this.setupInventory = setupInventory; - } - - @Override - public void injectComponents(StaticPane pane) { - Main plugin = setupInventory.getPlugin(); - ChatManager chatManager = plugin.getChatManager(); - ItemStack registeredItem; - if(!setupInventory.getArena().isReady()) { - registeredItem = new ItemBuilder(XMaterial.FIREWORK_ROCKET.parseItem()) - .name(chatManager.colorRawMessage("&e&lRegister Arena - Finish Setup")) - .lore(ChatColor.GRAY + "Click this when you're done with configuration.") - .lore(ChatColor.GRAY + "It will validate and register arena.") - .build(); - } else { - registeredItem = new ItemBuilder(Material.BARRIER) - .name(chatManager.colorRawMessage("&a&lArena Registered - Congratulations")) - .lore(ChatColor.GRAY + "This arena is already registered!") - .lore(ChatColor.GRAY + "Good job, you went through whole setup!") - .lore(ChatColor.GRAY + "You can play on this arena now!") - .build(); - } - pane.addItem(new GuiItem(registeredItem, e -> { - Arena arena = setupInventory.getArena(); - e.getWhoClicked().closeInventory(); - if(arena.isReady()) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&a&l✔ &aThis arena was already validated and is ready to use!")); - return; - } - String path = "instances." + arena.getId() + "."; - FileConfiguration arenasConfig = ConfigUtils.getConfig(plugin, "arenas"); - for(String s : new String[]{"lobbylocation", "Endlocation"}) { - if(!arenasConfig.isSet(path + s) || arenasConfig.getString(path + s).equals(LocationSerializer.locationToString(Bukkit.getWorlds().get(0).getSpawnLocation()))) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✘ &cArena validation failed! Please configure following spawn properly: " + s + " (cannot be world spawn location)")); - return; - } - } - for(String s : new String[]{"goldspawnpoints", "playerspawnpoints"}) { - if(!arenasConfig.isSet(path + s) || arenasConfig.getStringList(path + s).size() < 4) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✘ &cArena validation failed! Please configure following spawns properly: " + s + " (must be minimum 4 spawns)")); - return; - } - } - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&a&l✔ &aValidation succeeded! Registering new arena instance: " + arena.getId())); - - arenasConfig.set(path + "isdone", true); - ConfigUtils.saveConfig(plugin, arenasConfig, "arenas"); - - List signsToUpdate = new ArrayList<>(); - ArenaRegistry.unregisterArena(setupInventory.getArena()); - - plugin.getSignManager().getArenaSigns().stream().filter(arenaSign -> arenaSign.getArena().equals(setupInventory.getArena())) - .forEach(arenaSign -> signsToUpdate.add(arenaSign.getSign())); - - arena = new Arena(setupInventory.getArena().getId()); - arena.setReady(true); - List playerSpawnPoints = new ArrayList<>(); - for(String loc : arenasConfig.getStringList(path + "playerspawnpoints")) { - playerSpawnPoints.add(LocationSerializer.getLocation(loc)); - } - arena.setPlayerSpawnPoints(playerSpawnPoints); - List goldSpawnPoints = new ArrayList<>(); - for(String loc : arenasConfig.getStringList(path + "goldspawnpoints")) { - goldSpawnPoints.add(LocationSerializer.getLocation(loc)); - } - arena.setGoldSpawnPoints(goldSpawnPoints); - - List specialBlocks = new ArrayList<>(); - if(arenasConfig.isSet(path + "mystery-cauldrons")) { - for(String loc : arenasConfig.getStringList(path + "mystery-cauldrons")) { - specialBlocks.add(new SpecialBlock(LocationSerializer.getLocation(loc), SpecialBlock.SpecialBlockType.MYSTERY_CAULDRON)); - } - } - if(arenasConfig.isSet(path + "confessionals")) { - for(String loc : arenasConfig.getStringList(path + "confessionals")) { - specialBlocks.add(new SpecialBlock(LocationSerializer.getLocation(loc), SpecialBlock.SpecialBlockType.PRAISE_DEVELOPER)); - } - } - for(SpecialBlock specialBlock : specialBlocks) { - if(!arena.getSpecialBlocks().contains(specialBlock)) { - arena.loadSpecialBlock(specialBlock); - } - } - arena.setMinimumPlayers(arenasConfig.getInt(path + "minimumplayers")); - arena.setMaximumPlayers(arenasConfig.getInt(path + "maximumplayers")); - arena.setMapName(arenasConfig.getString(path + "mapname")); - arena.setSpawnGoldTime(arenasConfig.getInt(path + "spawngoldtime", 5)); - arena.setHideChances(arenasConfig.getBoolean(path + "hidechances", false)); - arena.setLobbyLocation(LocationSerializer.getLocation(arenasConfig.getString(path + "lobbylocation"))); - arena.setEndLocation(LocationSerializer.getLocation(arenasConfig.getString(path + "Endlocation"))); - arena.setMurderers(arenasConfig.getInt(path + "playerpermurderer", 5)); - arena.setDetectives(arenasConfig.getInt(path + "playerperdetective", 7)); - ArenaRegistry.registerArena(arena); - arena.start(); - plugin.getSignManager().getArenaSigns().clear(); - for(Sign s : signsToUpdate) { - plugin.getSignManager().getArenaSigns().add(new ArenaSign(s, arena)); - plugin.getSignManager().updateSigns(); - } - }), 8, 0); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/MiscComponents.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/components/MiscComponents.java deleted file mode 100644 index 79d222c1..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/MiscComponents.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup.components; - -import plugily.projects.inventoryframework.gui.GuiItem; -import plugily.projects.inventoryframework.pane.StaticPane; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Sign; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.conversations.ConversationContext; -import org.bukkit.conversations.Prompt; -import org.bukkit.conversations.StringPrompt; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; -import plugily.projects.murdermystery.handlers.sign.ArenaSign; -import plugily.projects.murdermystery.utils.conversation.SimpleConversationBuilder; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class MiscComponents implements SetupComponent { - - private SetupInventory setupInventory; - - @Override - public void prepare(SetupInventory setupInventory) { - this.setupInventory = setupInventory; - } - - @Override - public void injectComponents(StaticPane pane) { - Player player = setupInventory.getPlayer(); - FileConfiguration config = setupInventory.getConfig(); - Arena arena = setupInventory.getArena(); - Main plugin = setupInventory.getPlugin(); - ChatManager chatManager = plugin.getChatManager(); - ItemStack bungeeItem; - if(!plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - bungeeItem = new ItemBuilder(XMaterial.OAK_SIGN.parseMaterial()) - .name(chatManager.colorRawMessage("&e&lAdd Game Sign")) - .lore(ChatColor.GRAY + "Target a sign and click this.") - .lore(ChatColor.DARK_GRAY + "(this will set target sign as game sign)") - .build(); - } else { - bungeeItem = new ItemBuilder(Material.BARRIER) - .name(chatManager.colorRawMessage("&c&lAdd Game Sign")) - .lore(ChatColor.GRAY + "Option disabled in bungee cord mode.") - .lore(ChatColor.DARK_GRAY + "Bungee mode is meant to be one arena per server") - .lore(ChatColor.DARK_GRAY + "If you wish to have multi arena, disable bungee in config!") - .build(); - } - pane.addItem(new GuiItem(bungeeItem, e -> { - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.BUNGEE_ENABLED)) { - return; - } - e.getWhoClicked().closeInventory(); - Location location = player.getTargetBlock(null, 10).getLocation(); - if(!(location.getBlock().getState() instanceof Sign)) { - player.sendMessage(chatManager.colorMessage("Commands.Look-Sign")); - return; - } - if(location.distance(e.getWhoClicked().getWorld().getSpawnLocation()) <= Bukkit.getServer().getSpawnRadius() - && e.getClick() != ClickType.SHIFT_LEFT) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✖ &cWarning | Server spawn protection is set to &6" + Bukkit.getServer().getSpawnRadius() - + " &cand sign you want to place is in radius of this protection! &c&lNon opped players won't be able to interact with this sign and can't join the game so.")); - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&cYou can ignore this warning and add sign with Shift + Left Click, but for now &c&loperation is cancelled")); - return; - } - plugin.getSignManager().getArenaSigns().add(new ArenaSign((Sign) location.getBlock().getState(), arena)); - plugin.getSignManager().updateSigns(); - player.sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Signs.Sign-Created")); - String signLoc = location.getBlock().getWorld().getName() + "," + location.getBlock().getX() + "," + location.getBlock().getY() + "," + location.getBlock().getZ() + ",0.0,0.0"; - List locs = config.getStringList("instances." + arena.getId() + ".signs"); - locs.add(signLoc); - config.set("instances." + arena.getId() + ".signs", locs); - ConfigUtils.saveConfig(plugin, config, "arenas"); - }), 5, 0); - - pane.addItem(new GuiItem(new ItemBuilder(Material.NAME_TAG) - .name(chatManager.colorRawMessage("&e&lSet Map Name")) - .lore(ChatColor.GRAY + "Click to set arena map name") - .lore("", chatManager.colorRawMessage("&a&lCurrently: &e" + config.getString("instances." + arena.getId() + ".mapname"))) - .build(), e -> { - e.getWhoClicked().closeInventory(); - new SimpleConversationBuilder().withPrompt(new StringPrompt() { - @Override - public String getPromptText(@NotNull ConversationContext context) { - return chatManager.colorRawMessage(chatManager.getPrefix() + "&ePlease type in chat arena name! You can use color codes."); - } - - @Override - public Prompt acceptInput(@NotNull ConversationContext context, String input) { - String name = chatManager.colorRawMessage(input); - player.sendRawMessage(chatManager.colorRawMessage("&e✔ Completed | &aName of arena " + arena.getId() + " set to " + name)); - arena.setMapName(name); - config.set("instances." + arena.getId() + ".mapname", arena.getMapName()); - ConfigUtils.saveConfig(plugin, config, "arenas"); - - new SetupInventory(arena, player).openInventory(); - return Prompt.END_OF_CONVERSATION; - } - }).buildFor(player); - }), 6, 0); - - pane.addItem(new GuiItem(new ItemBuilder(Material.GOLD_INGOT) - .name(chatManager.colorRawMessage("&e&lAdd Gold Spawn")) - .lore(ChatColor.GRAY + "Add new gold spawn") - .lore(ChatColor.GRAY + "on the place you're standing at.") - .lore("", setupInventory.getSetupUtilities().isOptionDoneList("instances." + arena.getId() + ".goldspawnpoints", 4)) - .lore("", chatManager.colorRawMessage("&8Shift + Right Click to remove all spawns")) - .build(), e -> { - e.getWhoClicked().closeInventory(); - if(e.getClick() == ClickType.SHIFT_RIGHT) { - config.set("instances." + arena.getId() + ".goldspawnpoints", new ArrayList<>()); - arena.setGoldSpawnPoints(new ArrayList<>()); - player.sendMessage(chatManager.colorRawMessage("&eDone | &aGold spawn points deleted, you can add them again now!")); - arena.setReady(false); - ConfigUtils.saveConfig(plugin, config, "arenas"); - return; - } - List goldSpawns = config.getStringList("instances." + arena.getId() + ".goldspawnpoints"); - goldSpawns.add(LocationSerializer.locationToString(player.getLocation())); - config.set("instances." + arena.getId() + ".goldspawnpoints", goldSpawns); - String goldProgress = goldSpawns.size() >= 4 ? "&e✔ Completed | " : "&c✘ Not completed | "; - player.sendMessage(chatManager.colorRawMessage(goldProgress + "&aGold spawn added! &8(&7" + goldSpawns.size() + "/4&8)")); - if(goldSpawns.size() == 4) { - player.sendMessage(chatManager.colorRawMessage("&eInfo | &aYou can add more than 4 gold spawns! Four is just a minimum!")); - } - List spawns = new ArrayList<>(arena.getGoldSpawnPoints()); - spawns.add(player.getLocation()); - arena.setGoldSpawnPoints(spawns); - ConfigUtils.saveConfig(plugin, config, "arenas"); - }), 7, 0); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.GOLD_NUGGET.parseItem()) - .amount(config.getInt("instances." + arena.getId() + ".spawngoldtime", 3)) - .name(chatManager.colorRawMessage("&e&lSet gold spawn time in seconds")) - .lore(ChatColor.GRAY + "LEFT click to decrease") - .lore(ChatColor.GRAY + "RIGHT click to increase") - .lore(ChatColor.DARK_GRAY + "How much gold should be spawned? ") - .lore(ChatColor.DARK_GRAY + "That means 1 gold spawned every ... seconds") - .lore(ChatColor.DARK_GRAY + "Default: 5") - .lore(ChatColor.DARK_GRAY + "Every 5 seconds it will spawn 1 gold") - .lore("", setupInventory.getSetupUtilities().isOptionDone("instances." + arena.getId() + ".spawngoldtime")) - .build(), e -> { - if(e.getClick().isRightClick()) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() + 1); - } - if(e.getClick().isLeftClick() && e.getCurrentItem().getAmount() > 1) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() - 1); - } - if(e.getInventory().getItem(e.getSlot()).getAmount() < 1) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✖ &cWarning | Please do not set amount lower than 1! Game is not designed without gold!")); - e.getInventory().getItem(e.getSlot()).setAmount(1); - } - config.set("instances." + arena.getId() + ".spawngoldtime", e.getCurrentItem().getAmount()); - arena.setSpawnGoldTime(e.getCurrentItem().getAmount()); - ConfigUtils.saveConfig(plugin, config, "arenas"); - new SetupInventory(arena, setupInventory.getPlayer()).openInventory(); - }), 7, 1); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.REDSTONE.parseItem()) - .name(chatManager.colorRawMessage(arena.isGoldVisuals() ? "&c&lDisable Gold Visuals" : "&a&lEnable Gold Visuals")) - .lore(ChatColor.GRAY + "Enables gold visuals to spawn").lore(ChatColor.GRAY + "some particle effects above gold locations") - .build(), e -> { - arena.toggleGoldVisuals(); - config.set("instances." + arena.getId() + ".goldvisuals", arena.isGoldVisuals()); - ConfigUtils.saveConfig(plugin, config, "arenas"); - new SetupInventory(arena, setupInventory.getPlayer()).openInventory(); - }), 7, 2); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.FILLED_MAP.parseItem()) - .name(chatManager.colorRawMessage("&e&lView Setup Video")) - .lore(ChatColor.GRAY + "Having problems with setup or wanna") - .lore(ChatColor.GRAY + "know some useful tips? Click to get video link!") - .build(), e -> { - e.getWhoClicked().closeInventory(); - player.sendMessage(chatManager.getPrefix() + chatManager.colorRawMessage("&6Check out this video: " + SetupInventory.VIDEO_LINK)); - }), 8, 1); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/PlayerAmountComponents.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/components/PlayerAmountComponents.java deleted file mode 100644 index b4aa6771..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/PlayerAmountComponents.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup.components; - -import plugily.projects.inventoryframework.gui.GuiItem; -import plugily.projects.inventoryframework.pane.StaticPane; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class PlayerAmountComponents implements SetupComponent { - - private SetupInventory setupInventory; - - @Override - public void prepare(SetupInventory setupInventory) { - this.setupInventory = setupInventory; - } - - @Override - public void injectComponents(StaticPane pane) { - FileConfiguration config = setupInventory.getConfig(); - Arena arena = setupInventory.getArena(); - Main plugin = setupInventory.getPlugin(); - ChatManager chatManager = plugin.getChatManager(); - pane.addItem(new GuiItem(new ItemBuilder(Material.COAL).amount(setupInventory.getSetupUtilities().getMinimumValueHigherThanZero("minimumplayers")) - .name(chatManager.colorRawMessage("&e&lSet Minimum Players Amount")) - .lore(ChatColor.GRAY + "LEFT click to decrease") - .lore(ChatColor.GRAY + "RIGHT click to increase") - .lore(ChatColor.DARK_GRAY + "(how many players are needed") - .lore(ChatColor.DARK_GRAY + "for game to start lobby countdown)") - .lore("", setupInventory.getSetupUtilities().isOptionDone("instances." + arena.getId() + ".minimumplayers")) - .build(), e -> { - if(e.getClick().isRightClick()) { - e.getInventory().getItem(e.getSlot()).setAmount(e.getCurrentItem().getAmount() + 1); - } - if(e.getClick().isLeftClick()) { - e.getInventory().getItem(e.getSlot()).setAmount(e.getCurrentItem().getAmount() - 1); - } - if(e.getInventory().getItem(e.getSlot()).getAmount() <= 1) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✖ &cWarning | Please do not set amount lower than 2! Game is designed for 2 or more players!")); - e.getInventory().getItem(e.getSlot()).setAmount(2); - } - config.set("instances." + arena.getId() + ".minimumplayers", e.getCurrentItem().getAmount()); - arena.setMinimumPlayers(e.getCurrentItem().getAmount()); - ConfigUtils.saveConfig(plugin, config, "arenas"); - new SetupInventory(arena, setupInventory.getPlayer()).openInventory(); - }), 3, 0); - - pane.addItem(new GuiItem(new ItemBuilder(Material.REDSTONE) - .amount(setupInventory.getSetupUtilities().getMinimumValueHigherThanZero("maximumplayers")) - .name(chatManager.colorRawMessage("&e&lSet Maximum Players Amount")) - .lore(ChatColor.GRAY + "LEFT click to decrease") - .lore(ChatColor.GRAY + "RIGHT click to increase") - .lore(ChatColor.DARK_GRAY + "(how many players arena can hold)") - .lore("", setupInventory.getSetupUtilities().isOptionDone("instances." + arena.getId() + ".maximumplayers")) - .build(), e -> { - if(e.getClick().isRightClick()) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() + 1); - } - if(e.getClick().isLeftClick()) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() - 1); - } - if(e.getInventory().getItem(e.getSlot()).getAmount() <= 1) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✖ &cWarning | Please do not set amount lower than 2! Game is designed for 2 or more players!")); - e.getInventory().getItem(e.getSlot()).setAmount(2); - } - config.set("instances." + arena.getId() + ".maximumplayers", e.getCurrentItem().getAmount()); - arena.setMaximumPlayers(e.getCurrentItem().getAmount()); - ConfigUtils.saveConfig(plugin, config, "arenas"); - new SetupInventory(arena, setupInventory.getPlayer()).openInventory(); - }), 4, 0); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.IRON_SWORD.parseItem()) - .amount(setupInventory.getSetupUtilities().getMinimumValueHigherThanZero("playerpermurderer")) - .name(chatManager.colorRawMessage("&e&lSet Player Per Murderer Amount")) - .lore(ChatColor.GRAY + "LEFT click to decrease") - .lore(ChatColor.GRAY + "RIGHT click to increase") - .lore(ChatColor.DARK_GRAY + "How many murderer should be ingame? This means ") - .lore(ChatColor.DARK_GRAY + "one murderer for that amount of players. Default: ") - .lore(ChatColor.DARK_GRAY + "5 players are 1 murderer, that means if we have ") - .lore(ChatColor.DARK_GRAY + "14 Players it will calculate 2 murderer! ") - .lore(ChatColor.DARK_GRAY + "Set it to 1 if you want only one murderer ") - .lore("", setupInventory.getSetupUtilities().isOptionDone("instances." + arena.getId() + ".playerpermurderer")) - .build(), e -> { - if(e.getClick().isRightClick()) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() + 1); - } - if(e.getClick().isLeftClick() && e.getCurrentItem().getAmount() > 1) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() - 1); - } - if(e.getInventory().getItem(e.getSlot()).getAmount() < 1) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✖ &cWarning | Please do not set amount lower than 1! Game is not designed for more murderers than players!")); - e.getInventory().getItem(e.getSlot()).setAmount(1); - } - config.set("instances." + arena.getId() + ".playerpermurderer", e.getCurrentItem().getAmount()); - arena.setMurderers(e.getCurrentItem().getAmount()); - ConfigUtils.saveConfig(plugin, config, "arenas"); - new SetupInventory(arena, setupInventory.getPlayer()).openInventory(); - }), 3, 1); - - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.BOW.parseItem()) - .amount(setupInventory.getSetupUtilities().getMinimumValueHigherThanZero("playerperdetective")) - .name(chatManager.colorRawMessage("&e&lSet Player Per Detective Amount")) - .lore(ChatColor.GRAY + "LEFT click to decrease") - .lore(ChatColor.GRAY + "RIGHT click to increase") - .lore(ChatColor.DARK_GRAY + "How many detectives should be ingame? This means ") - .lore(ChatColor.DARK_GRAY + "one detective for that amount of players. Default: ") - .lore(ChatColor.DARK_GRAY + "7 players are 1 detective, that means if we have ") - .lore(ChatColor.DARK_GRAY + "18 Players it will calculate 2 detectives! ") - .lore(ChatColor.DARK_GRAY + "Set it to 1 if you want only one detectives ") - .lore("", setupInventory.getSetupUtilities().isOptionDone("instances." + arena.getId() + ".playerperdetective")) - .build(), e -> { - if(e.getClick().isRightClick()) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() + 1); - } - if(e.getClick().isLeftClick() && e.getCurrentItem().getAmount() > 1) { - e.getCurrentItem().setAmount(e.getCurrentItem().getAmount() - 1); - } - if(e.getInventory().getItem(e.getSlot()).getAmount() < 1) { - e.getWhoClicked().sendMessage(chatManager.colorRawMessage("&c&l✖ &cWarning | Please do not set amount lower than 1! Game is not designed for more detectives than players!")); - e.getInventory().getItem(e.getSlot()).setAmount(1); - } - config.set("instances." + arena.getId() + ".playerperdetective", e.getCurrentItem().getAmount()); - arena.setDetectives(e.getCurrentItem().getAmount()); - ConfigUtils.saveConfig(plugin, config, "arenas"); - new SetupInventory(arena, setupInventory.getPlayer()).openInventory(); - }), 4, 1); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SetupComponent.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SetupComponent.java deleted file mode 100644 index 074f6c0f..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SetupComponent.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup.components; - -import plugily.projects.inventoryframework.pane.StaticPane; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public interface SetupComponent { - - void prepare(SetupInventory setupInventory); - - void injectComponents(StaticPane pane); - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SpawnComponents.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SpawnComponents.java deleted file mode 100644 index 4c33bf7c..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SpawnComponents.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup.components; - -import plugily.projects.inventoryframework.gui.GuiItem; -import plugily.projects.inventoryframework.pane.StaticPane; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.ClickType; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class SpawnComponents implements SetupComponent { - - private SetupInventory setupInventory; - - @Override - public void prepare(SetupInventory setupInventory) { - this.setupInventory = setupInventory; - } - - @Override - public void injectComponents(StaticPane pane) { - Player player = setupInventory.getPlayer(); - FileConfiguration config = setupInventory.getConfig(); - Arena arena = setupInventory.getArena(); - Main plugin = setupInventory.getPlugin(); - ChatManager chatManager = plugin.getChatManager(); - String serializedLocation = player.getLocation().getWorld().getName() + "," + player.getLocation().getX() + "," + player.getLocation().getY() + "," - + player.getLocation().getZ() + "," + player.getLocation().getYaw() + ",0.0"; - pane.addItem(new GuiItem(new ItemBuilder(Material.REDSTONE_BLOCK) - .name(chatManager.colorRawMessage("&e&lSet Ending Location")) - .lore(ChatColor.GRAY + "Click to set the ending location") - .lore(ChatColor.GRAY + "on the place where you are standing.") - .lore(ChatColor.DARK_GRAY + "(location where players will be") - .lore(ChatColor.DARK_GRAY + "teleported after the game)") - .lore("", setupInventory.getSetupUtilities().isOptionDoneBool("instances." + arena.getId() + ".Endlocation")) - .build(), e -> { - e.getWhoClicked().closeInventory(); - config.set("instances." + arena.getId() + ".Endlocation", serializedLocation); - arena.setEndLocation(player.getLocation()); - player.sendMessage(chatManager.colorRawMessage("&e✔ Completed | &aEnding location for arena " + arena.getId() + " set at your location!")); - ConfigUtils.saveConfig(plugin, config, "arenas"); - }), 0, 0); - - pane.addItem(new GuiItem(new ItemBuilder(Material.LAPIS_BLOCK) - .name(chatManager.colorRawMessage("&e&lSet Lobby Location")) - .lore(ChatColor.GRAY + "Click to set the lobby location") - .lore(ChatColor.GRAY + "on the place where you are standing") - .lore("", setupInventory.getSetupUtilities().isOptionDoneBool("instances." + arena.getId() + ".lobbylocation")) - .build(), e -> { - e.getWhoClicked().closeInventory(); - config.set("instances." + arena.getId() + ".lobbylocation", serializedLocation); - arena.setLobbyLocation(player.getLocation()); - player.sendMessage(chatManager.colorRawMessage("&e✔ Completed | &aLobby location for arena " + arena.getId() + " set at your location!")); - ConfigUtils.saveConfig(plugin, config, "arenas"); - }), 1, 0); - - pane.addItem(new GuiItem(new ItemBuilder(Material.EMERALD_BLOCK) - .name(chatManager.colorRawMessage("&e&lAdd Starting Location")) - .lore(ChatColor.GRAY + "Click to add the starting location") - .lore(ChatColor.GRAY + "on the place where you are standing.") - .lore(ChatColor.DARK_GRAY + "(locations where players will be") - .lore(ChatColor.DARK_GRAY + "teleported when game starts)") - .lore("", setupInventory.getSetupUtilities().isOptionDoneList("instances." + arena.getId() + ".playerspawnpoints", 4)) - .lore("", chatManager.colorRawMessage("&8Shift + Right Click to remove all spawns")) - .build(), e -> { - e.getWhoClicked().closeInventory(); - if(e.getClick() == ClickType.SHIFT_RIGHT) { - config.set("instances." + arena.getId() + ".playerspawnpoints", new ArrayList<>()); - arena.setPlayerSpawnPoints(new ArrayList<>()); - player.sendMessage(chatManager.colorRawMessage("&eDone | &aPlayer spawn points deleted, you can add them again now!")); - arena.setReady(false); - ConfigUtils.saveConfig(plugin, config, "arenas"); - return; - } - List startingSpawns = config.getStringList("instances." + arena.getId() + ".playerspawnpoints"); - startingSpawns.add(LocationSerializer.locationToString(player.getLocation())); - config.set("instances." + arena.getId() + ".playerspawnpoints", startingSpawns); - String startingProgress = startingSpawns.size() >= 4 ? "&e✔ Completed | " : "&c✘ Not completed | "; - player.sendMessage(chatManager.colorRawMessage(startingProgress + "&aPlayer spawn added! &8(&7" + startingSpawns.size() + "/4&8)")); - if(startingSpawns.size() == 4) { - player.sendMessage(chatManager.colorRawMessage("&eInfo | &aYou can add more than 4 player spawns! Four is just a minimum!")); - } - List spawns = new ArrayList<>(arena.getPlayerSpawnPoints()); - spawns.add(player.getLocation()); - arena.setPlayerSpawnPoints(spawns); - ConfigUtils.saveConfig(plugin, config, "arenas"); - }), 2, 0); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SpecialBlocksComponents.java b/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SpecialBlocksComponents.java deleted file mode 100644 index 7dbc6555..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/setup/components/SpecialBlocksComponents.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.setup.components; - -import plugily.projects.inventoryframework.gui.GuiItem; -import plugily.projects.inventoryframework.pane.StaticPane; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.item.ItemBuilder; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.special.SpecialBlock; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.setup.SetupInventory; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class SpecialBlocksComponents implements SetupComponent { - - private SetupInventory setupInventory; - - @Override - public void prepare(SetupInventory setupInventory) { - this.setupInventory = setupInventory; - } - - @Override - public void injectComponents(StaticPane pane) { - Player player = setupInventory.getPlayer(); - FileConfiguration config = setupInventory.getConfig(); - Arena arena = setupInventory.getArena(); - Main plugin = setupInventory.getPlugin(); - ChatManager chatManager = plugin.getChatManager(); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.PAPER.parseItem()) - .name(chatManager.colorRawMessage("&6&lSpecial Blocks Section")) - .lore(ChatColor.GRAY + "Items on the right will allow") - .lore(ChatColor.GRAY + "you to add special game blocks!") - .build()), 0, 3); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.ENDER_CHEST.parseItem()) - .name(chatManager.colorRawMessage("&e&lAdd Mystery Cauldron")) - .lore(ChatColor.GRAY + "Target a cauldron and add it to the game") - .lore(ChatColor.GRAY + "it will cost 1 gold per potion!") - .lore(ChatColor.GRAY + "Configure cauldron potions in specialblocks.yml file!") - .build(), e -> { - e.getWhoClicked().closeInventory(); - Block targetBlock = e.getWhoClicked().getTargetBlock(null, 7); - if(targetBlock.getType() != Material.CAULDRON) { - e.getWhoClicked().sendMessage(ChatColor.RED + "Please target cauldron to continue!"); - return; - } - arena.loadSpecialBlock(new SpecialBlock(targetBlock.getLocation(), - SpecialBlock.SpecialBlockType.MYSTERY_CAULDRON)); - List cauldrons = new ArrayList<>(config.getStringList("instances." + arena.getId() + ".mystery-cauldrons")); - cauldrons.add(LocationSerializer.locationToString(targetBlock.getLocation())); - config.set("instances." + arena.getId() + ".mystery-cauldrons", cauldrons); - player.sendMessage(chatManager.colorRawMessage("&e✔ Completed | &aAdded Cauldron special block!")); - ConfigUtils.saveConfig(plugin, config, "arenas"); - }), 1, 3); - - pane.addItem(new GuiItem(new ItemBuilder(XMaterial.ENCHANTING_TABLE.parseItem()) - .name(chatManager.colorRawMessage("&e&lAdd Confessional")) - .lore(ChatColor.GRAY + "Target enchanting table and") - .lore(ChatColor.GRAY + "add praise to the developer") - .lore(ChatColor.GRAY + "confessional, gift for") - .lore(ChatColor.GRAY + "the developer costs 1 gold!") - .lore(ChatColor.GOLD + "Add some levers in radius") - .lore(ChatColor.GOLD + "of 3 blocks near the enchant table") - .lore(ChatColor.GOLD + "to allow users to pray there!") - .lore(ChatColor.RED + "You can either get gifts") - .lore(ChatColor.RED + "or curses from prayer!") - .build(), e -> { - e.getWhoClicked().closeInventory(); - Block targetBlock = e.getWhoClicked().getTargetBlock(null, 7); - if(targetBlock.getType() != XMaterial.ENCHANTING_TABLE.parseMaterial()) { - e.getWhoClicked().sendMessage(ChatColor.RED + "Please target enchanting table to continue!"); - return; - } - - arena.loadSpecialBlock(new SpecialBlock(targetBlock.getLocation(), - SpecialBlock.SpecialBlockType.PRAISE_DEVELOPER)); - List confessionals = new ArrayList<>(config.getStringList("instances." + arena.getId() + ".confessionals")); - confessionals.add(LocationSerializer.locationToString(targetBlock.getLocation())); - config.set("instances." + arena.getId() + ".confessionals", confessionals); - player.sendMessage(chatManager.colorRawMessage("&e✔ Completed | &aAdded Confessional special block!")); - player.sendMessage(chatManager.colorRawMessage("&eInfo | &aRemember to place any lever in radius of 3 near enchant table!")); - ConfigUtils.saveConfig(plugin, config, "arenas"); - }), 2, 3); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/sign/ArenaSign.java b/src/main/java/plugily/projects/murdermystery/handlers/sign/ArenaSign.java deleted file mode 100644 index f58de908..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/sign/ArenaSign.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.sign; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Sign; - -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.murdermystery.arena.Arena; - -import javax.annotation.Nullable; -import java.lang.reflect.InvocationTargetException; - -/** - * Created for 1.14 compatibility purposes, it will cache block behind sign that will be - * accessed via reflection on 1.14 which is expensive - */ -public class ArenaSign { - - private final Sign sign; - private Block behind; - private final Arena arena; - - public ArenaSign(Sign sign, Arena arena) { - this.sign = sign; - this.arena = arena; - setBehindBlock(); - } - - private void setBehindBlock() { - this.behind = null; - if(sign.getBlock().getType() == Material.getMaterial("WALL_SIGN")) { - this.behind = ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_14_R1) ? getBlockBehind() : getBlockBehindLegacy(); - } - } - - private Block getBlockBehind() { - try { - org.bukkit.block.BlockState state = sign.getBlock().getState(); - Object blockData = state.getClass().getMethod("getBlockData").invoke(state); - BlockFace face = (BlockFace) blockData.getClass().getMethod("getFacing").invoke(blockData); - - Location loc = sign.getLocation(); - Location location = new Location(sign.getWorld(), loc.getBlockX() - face.getModX(), loc.getBlockY() - face.getModY(), - loc.getBlockZ() - face.getModZ()); - return location.getBlock(); - } catch(NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - return null; - } - } - - private Block getBlockBehindLegacy() { - return sign.getBlock().getRelative(((org.bukkit.material.Sign) sign.getData()).getAttachedFace()); - } - - public Sign getSign() { - return sign; - } - - @Nullable - public Block getBehind() { - return behind; - } - - public Arena getArena() { - return arena; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/sign/SignManager.java b/src/main/java/plugily/projects/murdermystery/handlers/sign/SignManager.java deleted file mode 100644 index 2af7943c..00000000 --- a/src/main/java/plugily/projects/murdermystery/handlers/sign/SignManager.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.handlers.sign; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.event.player.PlayerInteractEvent; - -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.compat.xseries.XMaterial; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.commonsbox.minecraft.misc.stuff.ComplementAccessor; -import plugily.projects.commonsbox.minecraft.serialization.LocationSerializer; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaManager; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; -import plugily.projects.murdermystery.handlers.ChatManager; -import plugily.projects.murdermystery.handlers.language.LanguageManager; -import plugily.projects.murdermystery.utils.Debugger; - -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class SignManager implements Listener { - - private final List arenaSigns = new ArrayList<>(); - private final Map gameStateToString = new EnumMap<>(ArenaState.class); - private final Main plugin; - private final ChatManager chatManager; - private final List signLines; - - public SignManager(Main plugin) { - this.plugin = plugin; - chatManager = plugin.getChatManager(); - gameStateToString.put(ArenaState.WAITING_FOR_PLAYERS, chatManager.colorMessage("Signs.Game-States.Inactive")); - gameStateToString.put(ArenaState.STARTING, chatManager.colorMessage("Signs.Game-States.Starting")); - gameStateToString.put(ArenaState.IN_GAME, chatManager.colorMessage("Signs.Game-States.In-Game")); - gameStateToString.put(ArenaState.ENDING, chatManager.colorMessage("Signs.Game-States.Ending")); - gameStateToString.put(ArenaState.RESTARTING, chatManager.colorMessage("Signs.Game-States.Restarting")); - signLines = LanguageManager.getLanguageList("Signs.Lines"); - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - @EventHandler - public void onSignChange(SignChangeEvent e) { - if(!e.getPlayer().hasPermission("murdermystery.admin.sign.create") - || !ComplementAccessor.getComplement().getLine(e, 0).equalsIgnoreCase("[murdermystery]")) { - return; - } - String line1 = ComplementAccessor.getComplement().getLine(e, 1); - if(line1.isEmpty()) { - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Signs.Please-Type-Arena-Name")); - return; - } - for(Arena arena : ArenaRegistry.getArenas()) { - if(!arena.getId().equalsIgnoreCase(line1)) { - continue; - } - for(int i = 0; i < signLines.size(); i++) { - ComplementAccessor.getComplement().setLine(e, i, formatSign(signLines.get(i), arena)); - } - arenaSigns.add(new ArenaSign((Sign) e.getBlock().getState(), arena)); - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Signs.Sign-Created")); - String location = e.getBlock().getWorld().getName() + "," + e.getBlock().getX() + "," + e.getBlock().getY() + "," + e.getBlock().getZ() + ",0.0,0.0"; - FileConfiguration config = ConfigUtils.getConfig(plugin, "arenas"); - List locs = config.getStringList("instances." + arena.getId() + ".signs"); - locs.add(location); - config.set("instances." + arena.getId() + ".signs", locs); - ConfigUtils.saveConfig(plugin, config, "arenas"); - return; - } - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Signs.Arena-Doesnt-Exists")); - } - - private String formatSign(String msg, Arena a) { - String formatted = msg; - formatted = StringUtils.replace(formatted, "%mapname%", a.getMapName()); - - int maxPlayers = a.getMaximumPlayers(); - if(a.getPlayers().size() >= maxPlayers) { - formatted = StringUtils.replace(formatted, "%state%", chatManager.colorMessage("Signs.Game-States.Full-Game")); - } else { - formatted = StringUtils.replace(formatted, "%state%", gameStateToString.get(a.getArenaState())); - } - formatted = StringUtils.replace(formatted, "%playersize%", Integer.toString(a.getPlayers().size())); - formatted = StringUtils.replace(formatted, "%maxplayers%", Integer.toString(maxPlayers)); - formatted = chatManager.colorRawMessage(formatted); - return formatted; - } - - @EventHandler - public void onSignDestroy(BlockBreakEvent e) { - if (!e.getPlayer().hasPermission("murdermystery.admin.sign.break")) - return; - - ArenaSign arenaSign = getArenaSignByBlock(e.getBlock()); - if(arenaSign == null) { - return; - } - arenaSigns.remove(arenaSign); - FileConfiguration config = ConfigUtils.getConfig(plugin, "arenas"); - ConfigurationSection section = config.getConfigurationSection("instances"); - if (section == null) - return; - - String location = e.getBlock().getWorld().getName() + "," + e.getBlock().getX() + "," + e.getBlock().getY() + "," + e.getBlock().getZ() + "," + "0.0,0.0"; - for(String arena : section.getKeys(false)) { - for(String sign : section.getStringList(arena + ".signs")) { - if(!sign.equals(location)) { - continue; - } - List signs = section.getStringList(arena + ".signs"); - signs.remove(location); - config.set(arena + ".signs", signs); - ConfigUtils.saveConfig(plugin, config, "arenas"); - e.getPlayer().sendMessage(chatManager.getPrefix() + chatManager.colorMessage("Signs.Sign-Removed")); - return; - } - } - e.getPlayer().sendMessage(chatManager.getPrefix() + ChatColor.RED + "Couldn't remove sign from configuration! Please do this manually!"); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoinAttempt(PlayerInteractEvent e) { - if (e.getAction() != Action.RIGHT_CLICK_BLOCK || e.getClickedBlock() == null || !(e.getClickedBlock().getState() instanceof Sign)) { - return; - } - - ArenaSign arenaSign = getArenaSignByBlock(e.getClickedBlock()); - if(arenaSign != null) { - Arena arena = arenaSign.getArena(); - if(arena != null) { - ArenaManager.joinAttempt(e.getPlayer(), arena); - } - } - } - - @Nullable - private ArenaSign getArenaSignByBlock(Block block) { - if(block == null) { - return null; - } - for(ArenaSign sign : arenaSigns) { - if(sign.getSign().getLocation().equals(block.getLocation())) { - return sign; - } - } - return null; - } - - public void loadSigns() { - Debugger.debug("Signs load event started"); - long start = System.currentTimeMillis(); - - arenaSigns.clear(); - - ConfigurationSection section = ConfigUtils.getConfig(plugin, "arenas").getConfigurationSection("instances"); - if(section == null) { - return; - } - - for(String path : section.getKeys(false)) { - for(String sign : section.getStringList(path + ".signs")) { - Location loc = LocationSerializer.getLocation(sign); - if(loc.getBlock().getState() instanceof Sign) { - arenaSigns.add(new ArenaSign((Sign) loc.getBlock().getState(), ArenaRegistry.getArena(path))); - } else { - Debugger.debug(Level.WARNING, "Block at location {0} for arena {1} not a sign", loc, path); - } - } - } - Debugger.debug("Sign load event finished took {0}ms", System.currentTimeMillis() - start); - } - - public void updateSigns() { - Debugger.performance("SignUpdate", "[PerformanceMonitor] [SignUpdate] Updating signs"); - long start = System.currentTimeMillis(); - - for(ArenaSign arenaSign : arenaSigns) { - Sign sign = arenaSign.getSign(); - for(int i = 0; i < signLines.size(); i++) { - ComplementAccessor.getComplement().setLine(sign, i, formatSign(signLines.get(i), arenaSign.getArena())); - } - if(plugin.getConfig().getBoolean("Signs-Block-States-Enabled", true) && arenaSign.getBehind() != null) { - Block behind = arenaSign.getBehind(); - try { - switch(arenaSign.getArena().getArenaState()) { - case WAITING_FOR_PLAYERS: - behind.setType(XMaterial.WHITE_STAINED_GLASS.parseMaterial()); - if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_13_R1)) { - Block.class.getMethod("setData", byte.class).invoke(behind, (byte) 0); - } - break; - case STARTING: - behind.setType(XMaterial.YELLOW_STAINED_GLASS.parseMaterial()); - if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_13_R1)) { - Block.class.getMethod("setData", byte.class).invoke(behind, (byte) 4); - } - break; - case IN_GAME: - behind.setType(XMaterial.ORANGE_STAINED_GLASS.parseMaterial()); - if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_13_R1)) { - Block.class.getMethod("setData", byte.class).invoke(behind, (byte) 1); - } - break; - case ENDING: - behind.setType(XMaterial.GRAY_STAINED_GLASS.parseMaterial()); - if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_13_R1)) { - Block.class.getMethod("setData", byte.class).invoke(behind, (byte) 7); - } - break; - case RESTARTING: - behind.setType(XMaterial.BLACK_STAINED_GLASS.parseMaterial()); - if(ServerVersion.Version.isCurrentLower(ServerVersion.Version.v1_13_R1)) { - Block.class.getMethod("setData", byte.class).invoke(behind, (byte) 15); - } - break; - default: - break; - } - } catch(Exception ignored) { - } - } - sign.update(); - } - Debugger.performance("SignUpdate", "[PerformanceMonitor] [SignUpdate] Updated signs took {0}ms", System.currentTimeMillis() - start); - } - - public List getArenaSigns() { - return arenaSigns; - } - - public Map getGameStateToString() { - return gameStateToString; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/party/GameParty.java b/src/main/java/plugily/projects/murdermystery/handlers/skins/sword/SwordSkin.java similarity index 53% rename from src/main/java/plugily/projects/murdermystery/handlers/party/GameParty.java rename to src/main/java/plugily/projects/murdermystery/handlers/skins/sword/SwordSkin.java index f7faa075..6c2d324e 100644 --- a/src/main/java/plugily/projects/murdermystery/handlers/party/GameParty.java +++ b/src/main/java/plugily/projects/murdermystery/handlers/skins/sword/SwordSkin.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,33 +15,35 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +package plugily.projects.murdermystery.handlers.skins.sword; -package plugily.projects.murdermystery.handlers.party; - -import org.bukkit.entity.Player; - -import java.util.List; +import org.bukkit.inventory.ItemStack; /** - * @author Plajer + * @author Tigerpanzer_02 *

- * Created at 09.02.2020 + * Created at 03.04.2022 */ -public class GameParty { +public class SwordSkin { - private final List players; - private final Player leader; + private final ItemStack itemStack; + private final String permission; - public GameParty(List players, Player leader) { - this.players = players; - this.leader = leader; + public SwordSkin(ItemStack itemStack, String permission) { + this.itemStack = itemStack; + this.permission = permission; } - public List getPlayers() { - return players; + public ItemStack getItemStack() { + return itemStack; } - public Player getLeader() { - return leader; + public String getPermission() { + return permission; } + + public boolean hasPermission() { + return !permission.isEmpty(); + } + } diff --git a/src/main/java/plugily/projects/murdermystery/handlers/skins/sword/SwordSkinManager.java b/src/main/java/plugily/projects/murdermystery/handlers/skins/sword/SwordSkinManager.java new file mode 100644 index 00000000..cb3fb77b --- /dev/null +++ b/src/main/java/plugily/projects/murdermystery/handlers/skins/sword/SwordSkinManager.java @@ -0,0 +1,106 @@ +/* + * MurderMystery - Find the murderer, kill him and survive! + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package plugily.projects.murdermystery.handlers.skins.sword; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import plugily.projects.minigamesbox.classic.utils.configuration.ConfigUtils; +import plugily.projects.minigamesbox.classic.utils.version.xseries.XMaterial; +import plugily.projects.murdermystery.Main; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +/** + * @author 2Wild4You, Tigerpanzer_02 + *

Created at 19.02.2021 + */ +public class SwordSkinManager { + + private final List registeredSwordSkins = new ArrayList<>(); + private final Map murdererSwords = new HashMap<>(); + + public SwordSkinManager(Main plugin) { + registerSwordSkins(plugin); + } + + public void registerSwordSkins(Main plugin) { + FileConfiguration config = ConfigUtils.getConfig(plugin, "skins"); + ConfigurationSection section = config.getConfigurationSection("Skins.Sword"); + String path = "Skins.Sword."; + for (String id : section.getKeys(false)) { + addSwordSkin( + new SwordSkin( + XMaterial.matchXMaterial(config.getString(path + id + ".Material", "BEDROCK")) + .orElse(XMaterial.BEDROCK) + .parseItem(), + config.getString(path + id + ".Permission", ""))); + } + } + + public List getRegisteredSwordSkins() { + return registeredSwordSkins; + } + + public void addSwordSkin(SwordSkin lastWord) { + registeredSwordSkins.add(lastWord); + } + + public ItemStack getRandomSwordSkin(Player player) { + // check perms + List perms = + registeredSwordSkins.stream() + .filter(swordSkin -> player.hasPermission(swordSkin.getPermission())) + .collect(Collectors.toList()); + if (!perms.isEmpty()) { + ItemStack itemStack = + perms.get(ThreadLocalRandom.current().nextInt(perms.size())).getItemStack(); + murdererSwords.put(player, itemStack); + return itemStack; + } + // check default + List noPerms = + registeredSwordSkins.stream() + .filter(swordSkin -> !swordSkin.hasPermission()) + .collect(Collectors.toList()); + if (!noPerms.isEmpty()) { + ItemStack itemStack = + noPerms.get(ThreadLocalRandom.current().nextInt(noPerms.size())).getItemStack(); + murdererSwords.put(player, itemStack); + return itemStack; + } + // fallback + ItemStack itemStack = registeredSwordSkins.get(0).getItemStack(); + murdererSwords.put(player, itemStack); + return itemStack; + } + + public void removeMurdererSword(Player player) { + murdererSwords.remove(player); + } + + public ItemStack getMurdererSword(Player player) { + return murdererSwords.get(player); + } +} diff --git a/src/main/java/plugily/projects/murdermystery/handlers/trails/BowTrailsHandler.java b/src/main/java/plugily/projects/murdermystery/handlers/trails/BowTrailsHandler.java index 998e005f..96bfc528 100644 --- a/src/main/java/plugily/projects/murdermystery/handlers/trails/BowTrailsHandler.java +++ b/src/main/java/plugily/projects/murdermystery/handlers/trails/BowTrailsHandler.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -25,11 +25,9 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.scheduler.BukkitRunnable; - -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.utils.Debugger; + /** * @author 2Wild4You, Tigerpanzer_02 @@ -50,21 +48,26 @@ public void onArrowShoot(EntityShootBowEvent event) { if(!(event.getEntity() instanceof Player && event.getProjectile() instanceof Arrow)) { return; } - Player player = (Player) event.getEntity(); + Entity projectile = event.getProjectile(); - if(!ArenaRegistry.isInArena(player) || projectile.isDead() || projectile.isOnGround()) { + + if(projectile.isDead() || projectile.isOnGround()) { return; } - if(!plugin.getTrailsManager().gotAnyTrails(player)) { + + Player player = (Player) event.getEntity(); + + if(!plugin.getArenaRegistry().isInArena(player) || !plugin.getTrailsManager().gotAnyTrails(player)) { return; } + Trail trail = plugin.getTrailsManager().getRandomTrail(player); - Debugger.debug("Spawning particle with perm {0} for player {1}", trail.getPermission(), player.getName()); + plugin.getDebugger().debug("Spawning particle with perm {0} for player {1}", trail.getPermission(), player.getName()); new BukkitRunnable() { @Override public void run() { if(projectile.isDead() || projectile.isOnGround()) { - Debugger.debug("Stopped spawning particle with perm {0} for player {1}", trail.getPermission(), player.getName()); + plugin.getDebugger().debug("Stopped spawning particle with perm {0} for player {1}", trail.getPermission(), player.getName()); cancel(); } VersionUtils.sendParticles(trail.getName(), player, projectile.getLocation(), 3); diff --git a/src/main/java/plugily/projects/murdermystery/handlers/trails/Trail.java b/src/main/java/plugily/projects/murdermystery/handlers/trails/Trail.java index 0f4cd710..e38e2972 100644 --- a/src/main/java/plugily/projects/murdermystery/handlers/trails/Trail.java +++ b/src/main/java/plugily/projects/murdermystery/handlers/trails/Trail.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/main/java/plugily/projects/murdermystery/handlers/trails/TrailsManager.java b/src/main/java/plugily/projects/murdermystery/handlers/trails/TrailsManager.java index a35728fc..875726b2 100644 --- a/src/main/java/plugily/projects/murdermystery/handlers/trails/TrailsManager.java +++ b/src/main/java/plugily/projects/murdermystery/handlers/trails/TrailsManager.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,9 +17,11 @@ */ package plugily.projects.murdermystery.handlers.trails; +import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; +import plugily.projects.minigamesbox.classic.utils.configuration.ConfigUtils; +import plugily.projects.minigamesbox.classic.utils.version.VersionUtils; import plugily.projects.murdermystery.Main; import java.util.ArrayList; @@ -28,11 +30,10 @@ import java.util.stream.Collectors; /** - * @author 2Wild4You, Tigerpanzer_02 + * @author Tigerpanzer_02 *

* Created at 19.02.2021 */ - public class TrailsManager { private final List registeredTrails = new ArrayList<>(); @@ -40,13 +41,14 @@ public class TrailsManager { private final List blacklistedTrails; public TrailsManager(Main plugin) { - blacklistedTrails = plugin.getConfig().getStringList("Blacklisted-Trails"); + FileConfiguration config = ConfigUtils.getConfig(plugin, "trails"); + blacklistedTrails = config.getStringList("Blacklisted-Trails"); registerTrails(); } public void registerTrails() { - for(String particle : VersionUtils.getParticleValues()) { - if(blacklistedTrails.contains(particle.toLowerCase())) { + for (String particle : VersionUtils.getParticleValues()) { + if (blacklistedTrails.contains(particle.toLowerCase())) { continue; } addTrail(new Trail(particle, "murdermystery.trails." + particle.toLowerCase())); @@ -66,12 +68,15 @@ public boolean gotAnyTrails(Player player) { } public Trail getRandomTrail(Player player) { - //check perms - List perms = registeredTrails.stream().filter(trail -> player.hasPermission(trail.getPermission())).collect(Collectors.toList()); - if(!perms.isEmpty()) { + // check perms + List perms = + registeredTrails.stream() + .filter(trail -> player.hasPermission(trail.getPermission())) + .collect(Collectors.toList()); + if (!perms.isEmpty()) { return perms.get(perms.size() == 1 ? 0 : ThreadLocalRandom.current().nextInt(perms.size())); } - //fallback + // fallback return registeredTrails.get(0); } } diff --git a/src/main/java/plugily/projects/murdermystery/user/User.java b/src/main/java/plugily/projects/murdermystery/user/User.java deleted file mode 100644 index dfccd16a..00000000 --- a/src/main/java/plugily/projects/murdermystery/user/User.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.user; - -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scoreboard.Scoreboard; - -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.api.events.player.MMPlayerStatisticChangeEvent; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class User { - - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private static long cooldownCounter = 0; - private final Map stats = new EnumMap<>(StatsStorage.StatisticType.class); - private final Map cooldowns = new HashMap<>(); - private final UUID uuid; - private boolean spectator = false; - private boolean permanentSpectator = false; - - public Scoreboard lastBoard; - - @Deprecated - public User(Player player) { - this(player.getUniqueId()); - } - - public User(UUID uuid) { - this.uuid = uuid; - } - - public UUID getUniqueId() { - return uuid; - } - - public static void cooldownHandlerTask() { - plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, () -> cooldownCounter++, 20, 20); - } - - public Arena getArena() { - return ArenaRegistry.getArena(getPlayer()); - } - - public Player getPlayer() { - return plugin.getServer().getPlayer(uuid); - } - - public boolean isSpectator() { - return spectator; - } - - public void setSpectator(boolean b) { - spectator = b; - } - - public boolean isPermanentSpectator() { - return permanentSpectator; - } - - public void setPermanentSpectator(boolean permanentSpectator) { - this.permanentSpectator = permanentSpectator; - } - - public int getStat(StatsStorage.StatisticType stat) { - Integer st = stats.get(stat); - if(st == null) { - stats.put(stat, 0); - return 0; - } - - return st.intValue(); - } - - public void removeScoreboard(Arena arena) { - arena.getScoreboardManager().removeScoreboard(this); - - if (lastBoard != null) { - getPlayer().setScoreboard(lastBoard); - lastBoard = null; - } - } - - public void setStat(StatsStorage.StatisticType stat, int i) { - stats.put(stat, i); - - //statistics manipulation events are called async when using mysql - plugin.getServer().getScheduler().runTask(plugin, () -> { - Player player = getPlayer(); - plugin.getServer().getPluginManager().callEvent(new MMPlayerStatisticChangeEvent( - ArenaRegistry.getArena(player), player, stat, i)); - }); - } - - public void addStat(StatsStorage.StatisticType stat, int i) { - stats.put(stat, getStat(stat) + i); - - //statistics manipulation events are called async when using mysql - plugin.getServer().getScheduler().runTask(plugin, () -> { - Player player = getPlayer(); - plugin.getServer().getPluginManager().callEvent(new MMPlayerStatisticChangeEvent( - ArenaRegistry.getArena(player), player, stat, getStat(stat))); - }); - } - - public void setCooldown(String s, double seconds) { - cooldowns.put(s, seconds + cooldownCounter); - } - - public double getCooldown(String s) { - Double coold = cooldowns.get(s); - return (coold == null || coold.doubleValue() <= cooldownCounter) ? 0 : coold.doubleValue() - cooldownCounter; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/user/UserManager.java b/src/main/java/plugily/projects/murdermystery/user/UserManager.java deleted file mode 100644 index be8494f3..00000000 --- a/src/main/java/plugily/projects/murdermystery/user/UserManager.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.user; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import plugily.projects.murdermystery.ConfigPreferences; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.user.data.FileStats; -import plugily.projects.murdermystery.user.data.MysqlManager; -import plugily.projects.murdermystery.user.data.UserDatabase; -import plugily.projects.murdermystery.utils.Debugger; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class UserManager { - - private final List users = new ArrayList<>(); - private final UserDatabase database; - - public UserManager(Main plugin) { - if(plugin.getConfigPreferences().getOption(ConfigPreferences.Option.DATABASE_ENABLED)) { - database = new MysqlManager(plugin); - Debugger.debug("MySQL Stats enabled"); - } else { - database = new FileStats(plugin); - Debugger.debug("File Stats enabled"); - } - loadStatsForPlayersOnline(); - } - - private void loadStatsForPlayersOnline() { - Bukkit.getServer().getOnlinePlayers().stream().map(this::getUser).forEach(this::loadStatistics); - } - - public User getUser(Player player) { - java.util.UUID playerId = player.getUniqueId(); - - for(User user : users) { - if(user.getUniqueId().equals(playerId)) { - return user; - } - } - - Debugger.debug("Registering new user {0} ({1})", playerId, player.getName()); - User user = new User(playerId); - users.add(user); - return user; - } - - public List getUsers(Arena arena) { - List list = new ArrayList<>(); - - for(Player player : arena.getPlayers()) { - list.add(getUser(player)); - } - - return list; - } - - public void saveStatistic(User user, StatsStorage.StatisticType stat) { - if(!stat.isPersistent()) { - return; - } - //apply before save - fixContributionStat(user); - database.saveStatistic(user, stat); - } - - public void loadStatistics(User user) { - database.loadStatistics(user); - //apply after load to override - fixContributionStat(user); - } - - private void fixContributionStat(User user) { - if(user.getStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE) <= 0) { - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE, 1); - } - if(user.getStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER) <= 0) { - user.setStat(StatsStorage.StatisticType.CONTRIBUTION_MURDERER, 1); - } - } - - public void saveAllStatistic(User user) { - database.saveAllStatistic(user); - } - - public void removeUser(User user) { - users.remove(user); - } - - public UserDatabase getDatabase() { - return database; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/user/data/FileStats.java b/src/main/java/plugily/projects/murdermystery/user/data/FileStats.java deleted file mode 100644 index 3f901000..00000000 --- a/src/main/java/plugily/projects/murdermystery/user/data/FileStats.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.user.data; - -import org.bukkit.configuration.file.FileConfiguration; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.user.User; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class FileStats implements UserDatabase { - - private final Main plugin; - private final FileConfiguration config; - - public FileStats(Main plugin) { - this.plugin = plugin; - config = ConfigUtils.getConfig(plugin, "stats"); - } - - @Override - public void saveStatistic(User user, StatsStorage.StatisticType stat) { - config.set(user.getUniqueId().toString() + "." + stat.getName(), user.getStat(stat)); - ConfigUtils.saveConfig(plugin, config, "stats"); - } - - @Override - public void saveAllStatistic(User user) { - for(StatsStorage.StatisticType stat : StatsStorage.StatisticType.values()) { - if(!stat.isPersistent()) continue; - config.set(user.getUniqueId().toString() + "." + stat.getName(), user.getStat(stat)); - } - ConfigUtils.saveConfig(plugin, config, "stats"); - } - - @Override - public void loadStatistics(User user) { - for(StatsStorage.StatisticType stat : StatsStorage.StatisticType.values()) { - user.setStat(stat, config.getInt(user.getUniqueId().toString() + "." + stat.getName(), 0)); - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/user/data/MysqlManager.java b/src/main/java/plugily/projects/murdermystery/user/data/MysqlManager.java deleted file mode 100644 index dd2c2375..00000000 --- a/src/main/java/plugily/projects/murdermystery/user/data/MysqlManager.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.user.data; - -import org.bukkit.Bukkit; - -import plugily.projects.commonsbox.database.MysqlDatabase; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.user.User; -import plugily.projects.murdermystery.utils.Debugger; -import plugily.projects.murdermystery.utils.MessageUtils; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.logging.Level; - -/** - * @author Plajer - *

- * Created at 03.10.2018 - */ -public class MysqlManager implements UserDatabase { - - private final Main plugin; - private final MysqlDatabase database; - - public MysqlManager(Main plugin) { - this.plugin = plugin; - database = plugin.getMysqlDatabase(); - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - try(Connection connection = database.getConnection()) { - Statement statement = connection.createStatement(); - statement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + getTableName() + "` (\n" - + " `UUID` char(36) NOT NULL PRIMARY KEY,\n" - + " `name` varchar(32) NOT NULL,\n" - + " `kills` int(11) NOT NULL DEFAULT '0',\n" - + " `deaths` int(11) NOT NULL DEFAULT '0',\n" - + " `highestscore` int(11) NOT NULL DEFAULT '0',\n" - + " `gamesplayed` int(11) NOT NULL DEFAULT '0',\n" - + " `wins` int(11) NOT NULL DEFAULT '0',\n" - + " `loses` int(11) NOT NULL DEFAULT '0',\n" - + " `contribmurderer` int(11) NOT NULL DEFAULT '1',\n" - + " `contribdetective` int(11) NOT NULL DEFAULT '1',\n" - + " `murderer_pass` int(11) NOT NULL DEFAULT '0',\n" - + " `detective_pass` int(11) NOT NULL DEFAULT '0'\n" - + ");"); - } catch(SQLException e) { - e.printStackTrace(); - MessageUtils.errorOccurred(); - Debugger.sendConsoleMsg("Cannot save contents to MySQL database!"); - Debugger.sendConsoleMsg("Check configuration of mysql.yml file or disable mysql option in config.yml"); - } - }); - } - - @Override - public void saveStatistic(User user, StatsStorage.StatisticType stat) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - database.executeUpdate("UPDATE " + getTableName() + " SET " + stat.getName() + "=" + user.getStat(stat) + " WHERE UUID='" + user.getUniqueId().toString() + "';"); - Debugger.debug(Level.INFO, "Executed MySQL: " + "UPDATE " + getTableName() + " SET " + stat.getName() + "=" + user.getStat(stat) + " WHERE UUID='" + user.getUniqueId().toString() + "';"); - }); - } - - @Override - public void saveAllStatistic(User user) { - StringBuilder update = new StringBuilder(" SET "); - for(StatsStorage.StatisticType stat : StatsStorage.StatisticType.values()) { - if(!stat.isPersistent()) continue; - if(update.toString().equalsIgnoreCase(" SET ")) { - update.append(stat.getName()).append('=').append(user.getStat(stat)); - } - update.append(", ").append(stat.getName()).append('=').append(user.getStat(stat)); - } - String finalUpdate = update.toString(); - - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> - database.executeUpdate("UPDATE " + getTableName() + finalUpdate + " WHERE UUID='" + user.getUniqueId().toString() + "';")); - } - - @Override - public void loadStatistics(User user) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - String uuid = user.getUniqueId().toString(); - try(Connection connection = database.getConnection()) { - Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery("SELECT * from " + getTableName() + " WHERE UUID='" + uuid + "';"); - if(rs.next()) { - //player already exists - get the stats - Debugger.debug(Level.INFO, "MySQL Stats | Player {0} already exist. Getting Stats...", user.getPlayer().getName()); - for(StatsStorage.StatisticType stat : StatsStorage.StatisticType.values()) { - if(!stat.isPersistent()) continue; - int val = rs.getInt(stat.getName()); - user.setStat(stat, val); - } - } else { - //player doesn't exist - make a new record - Debugger.debug(Level.INFO, "MySQL Stats | Player {0} does not exist. Creating new one...", user.getPlayer().getName()); - statement.executeUpdate("INSERT INTO " + getTableName() + " (UUID,name) VALUES ('" + uuid + "','" + user.getPlayer().getName() + "');"); - for(StatsStorage.StatisticType stat : StatsStorage.StatisticType.values()) { - if(!stat.isPersistent()) continue; - if(stat == StatsStorage.StatisticType.CONTRIBUTION_DETECTIVE || stat == StatsStorage.StatisticType.CONTRIBUTION_MURDERER) { - user.setStat(stat, 1); - } else { - user.setStat(stat, 0); - } - } - } - } catch(SQLException e) { - e.printStackTrace(); - } - }); - } - - public String getTableName() { - return ConfigUtils.getConfig(plugin, "mysql").getString("table", "playerstats"); - } - - public MysqlDatabase getDatabase() { - return database; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/user/data/UserDatabase.java b/src/main/java/plugily/projects/murdermystery/user/data/UserDatabase.java deleted file mode 100644 index 4459cc4f..00000000 --- a/src/main/java/plugily/projects/murdermystery/user/data/UserDatabase.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.user.data; - -import plugily.projects.murdermystery.api.StatsStorage; -import plugily.projects.murdermystery.user.User; - -/** - * @author Plajer - *

- * Created at 23.01.2019 - */ -public interface UserDatabase { - - /** - * Saves player statistic into yaml or MySQL storage based on user choice - * - * @param user user to retrieve statistic from - * @param stat stat to save to storage - */ - void saveStatistic(User user, StatsStorage.StatisticType stat); - - /** - * Saves player statistic into yaml or MySQL storage based on user choice - * - * @param user user to retrieve statistic from - */ - void saveAllStatistic(User user); - - /** - * Loads player statistic from yaml or MySQL storage based on user choice - * - * @param user user to load statistic for - */ - void loadStatistics(User user); - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/Debugger.java b/src/main/java/plugily/projects/murdermystery/utils/Debugger.java deleted file mode 100644 index c4ec24a4..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/Debugger.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; - -import plugily.projects.commonsbox.minecraft.compat.ServerVersion; -import plugily.projects.commonsbox.minecraft.misc.MiscUtils; - -import java.util.HashSet; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author Plajer - *

- * Created at 06.04.2019 - */ -public class Debugger { - - private static final HashSet listenedPerformance = new HashSet<>(); - private static boolean enabled = false; - private static boolean deep = false; - private static final Logger logger = Logger.getLogger("Murder Mystery"); - - public static void setEnabled(boolean enabled) { - Debugger.enabled = enabled; - } - - public static void deepDebug(boolean deep) { - Debugger.deep = deep; - } - - public static void monitorPerformance(String task) { - listenedPerformance.add(task); - } - - public static void sendConsoleMsg(String msg) { - if(ServerVersion.Version.isCurrentEqualOrHigher(ServerVersion.Version.v1_16_R1) && msg.indexOf('#') >= 0) { - msg = MiscUtils.matchColorRegex(msg); - } - - Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); - } - - public static void debug(String msg) { - debug(Level.INFO, msg); - } - - /** - * Prints debug message with selected log level. - * Messages of level INFO or TASK won't be posted if - * debugger is enabled, warnings and errors will be. - * - * @param level level of debugged message - * @param msg debugged message - */ - public static void debug(Level level, String msg) { - if(!enabled && (level != Level.WARNING || level != Level.SEVERE)) { - return; - } - logger.log(level, "[MMDBG] " + msg); - } - - public static void debug(String msg, Object... params) { - debug(Level.INFO, msg, params); - } - - /** - * Prints debug message with selected log level and replaces parameters. - * Messages of level INFO or TASK won't be posted if - * debugger is enabled, warnings and errors will be. - * - * @param level level of debugged message - * @param msg debugged message - */ - public static void debug(Level level, String msg, Object... params) { - if(!enabled && (level != Level.WARNING || level != Level.SEVERE)) { - return; - } - logger.log(level, "[MMDBG] " + msg, params); - } - - /** - * Prints performance debug message with selected log level and replaces parameters. - * - * @param msg debugged message - */ - public static void performance(String monitorName, String msg, Object... params) { - if(!deep || !listenedPerformance.contains(monitorName)) { - return; - } - logger.log(Level.INFO, "[MMDBG] " + msg, params); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/ExceptionLogHandler.java b/src/main/java/plugily/projects/murdermystery/utils/ExceptionLogHandler.java deleted file mode 100644 index f7cba75f..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/ExceptionLogHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils; - -import org.bukkit.Bukkit; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.utils.services.exception.ReportedException; - -import java.util.Arrays; -import java.util.List; -import java.util.logging.Handler; -import java.util.logging.LogRecord; - -/** - * @author Plajer - *

- * Created at 24.03.2019 - */ -public class ExceptionLogHandler extends Handler { - - //these classes if found in stacktraces won't be reported - //to the Error Service - private final List blacklistedClasses = Arrays.asList("plugily.projects.murdermystery.user.data.MysqlManager", "plugily.projects.murdermystery.plajerlair.commonsbox.database.MysqlDatabase"); - private final Main plugin; - - public ExceptionLogHandler(Main plugin) { - this.plugin = plugin; - Bukkit.getLogger().addHandler(this); - } - - @Override - public void close() throws SecurityException { - } - - @Override - public void flush() { - } - - @Override - public void publish(LogRecord record) { - Throwable throwable = record.getThrown(); - if(throwable == null || throwable.getCause() == null) { - return; - } - StackTraceElement[] element = throwable.getCause().getStackTrace(); - if(element.length == 0 || element[0] == null || !element[0].getClassName().contains("plugily.projects.murdermystery")) { - return; - } - if(containsBlacklistedClass(throwable)) { - return; - } - new ReportedException(plugin, throwable); - record.setThrown(null); - record.setMessage("[Murder Mystery] We have found a bug in the code. Contact us at our official discord server (Invite link: https://discordapp.com/invite/UXzUdTP) with the following error given" + - " above!"); - } - - private boolean containsBlacklistedClass(Throwable throwable) { - for(StackTraceElement element : throwable.getStackTrace()) { - for(String blacklist : blacklistedClasses) { - if(element.getClassName().contains(blacklist)) { - return true; - } - } - } - return false; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/ItemPosition.java b/src/main/java/plugily/projects/murdermystery/utils/ItemPosition.java index 82769076..07f976ff 100644 --- a/src/main/java/plugily/projects/murdermystery/utils/ItemPosition.java +++ b/src/main/java/plugily/projects/murdermystery/utils/ItemPosition.java @@ -1,6 +1,6 @@ /* * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors + * Copyright (c) 2022 Plugily Projects - maintained by Tigerpanzer_02 and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,9 +18,9 @@ package plugily.projects.murdermystery.utils; -import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import plugily.projects.minigamesbox.classic.user.User; import plugily.projects.murdermystery.arena.role.Role; /** @@ -45,23 +45,19 @@ public enum ItemPosition { * Adds target item to specified hotbar position sorta different for each role. * Item will be added if there is already set or will be set when no item is set in the position. * - * @param player player to add item to + * @param user player to add item to * @param itemPosition position of item to set/add * @param itemStack itemstack to be added at itemPostion or set at itemPosition */ - public static void addItem(Player player, ItemPosition itemPosition, ItemStack itemStack) { - if(player == null) { - return; - } - - int itemPos = Role.isRole(Role.MURDERER, player) ? itemPosition.getMurdererItemPosition() + public static void addItem(User user, ItemPosition itemPosition, ItemStack itemStack) { + int itemPos = Role.isRole(Role.MURDERER, user) ? itemPosition.getMurdererItemPosition() : itemPosition.getOtherRolesItemPosition(); if (itemPos < 0) { return; } - Inventory inv = player.getInventory(); + Inventory inv = user.getPlayer().getInventory(); ItemStack item = inv.getItem(itemPos); if(item != null) { @@ -76,19 +72,15 @@ public static void addItem(Player player, ItemPosition itemPosition, ItemStack i * Sets target item in specified hotbar position sorta different for each role. * If item there is already set it will be incremented by itemStack amount if possible. * - * @param player player to set item to + * @param user player to set item to * @param itemPosition position of item to set * @param itemStack itemstack to set at itemPosition */ - public static void setItem(Player player, ItemPosition itemPosition, ItemStack itemStack) { - if(player == null) { - return; - } - - if(itemPosition.getMurdererItemPosition() >= 0 && Role.isRole(Role.MURDERER, player)) { - player.getInventory().setItem(itemPosition.getMurdererItemPosition(), itemStack); + public static void setItem(User user, ItemPosition itemPosition, ItemStack itemStack) { + if(itemPosition.getMurdererItemPosition() >= 0 && Role.isRole(Role.MURDERER, user)) { + user.getPlayer().getInventory().setItem(itemPosition.getMurdererItemPosition(), itemStack); } else if (itemPosition.getOtherRolesItemPosition() >= 0) { - player.getInventory().setItem(itemPosition.getOtherRolesItemPosition(), itemStack); + user.getPlayer().getInventory().setItem(itemPosition.getOtherRolesItemPosition(), itemStack); } } diff --git a/src/main/java/plugily/projects/murdermystery/utils/MessageUtils.java b/src/main/java/plugily/projects/murdermystery/utils/MessageUtils.java deleted file mode 100644 index abc9c150..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/MessageUtils.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils; - -/** - * @author Plajer - *

- * Created at 03.08.2018 - */ -public class MessageUtils { - - private MessageUtils() { - } - - public static void thisVersionIsNotSupported() { - Debugger.sendConsoleMsg("&c _ _ _ _ _ "); - Debugger.sendConsoleMsg("&c | \\ | | ___ | |_ ___ _ _ _ __ _ __ ___ _ __ | |_ ___ __| |"); - Debugger.sendConsoleMsg("&c | \\| | / _ \\ | __| / __| | | | | | '_ \\ | '_ \\ / _ \\ | '__| | __| / _ \\ / _` |"); - Debugger.sendConsoleMsg("&c | |\\ | | (_) | | |_ \\__ \\ | |_| | | |_) | | |_) | | (_) | | | | |_ | __/ | (_| |"); - Debugger.sendConsoleMsg("&c |_| \\_| \\___/ \\__| |___/ \\__,_| | .__/ | .__/ \\___/ |_| \\__| \\___| \\__,_|"); - Debugger.sendConsoleMsg("&c |_| |_| "); - } - - public static void errorOccurred() { - Debugger.sendConsoleMsg("&c _____ _ _ "); - Debugger.sendConsoleMsg("&c | ____| _ __ _ __ ___ _ __ ___ ___ ___ _ _ _ __ ___ __| | | |"); - Debugger.sendConsoleMsg("&c | _| | '__| | '__| / _ \\ | '__| / _ \\ / __| / __| | | | | | '__| / _ \\ / _` | | |"); - Debugger.sendConsoleMsg("&c | |___ | | | | | (_) | | | | (_) | | (__ | (__ | |_| | | | | __/ | (_| | |_|"); - Debugger.sendConsoleMsg("&c |_____| |_| |_| \\___/ |_| \\___/ \\___| \\___| \\__,_| |_| \\___| \\__,_| (_)"); - Debugger.sendConsoleMsg("&c "); - } - - public static void updateIsHere() { - Debugger.sendConsoleMsg("&a _ _ _ _ "); - Debugger.sendConsoleMsg("&a | | | | _ __ __| | __ _ | |_ ___ "); - Debugger.sendConsoleMsg("&a | | | | | '_ \\ / _` | / _` | | __| / _ \\"); - Debugger.sendConsoleMsg("&a | |_| | | |_) | | (_| | | (_| | | |_ | __/"); - Debugger.sendConsoleMsg("&a \\___/ | .__/ \\__,_| \\__,_| \\__| \\___|"); - Debugger.sendConsoleMsg("&a |_| "); - } - - public static void info() { - Debugger.sendConsoleMsg("&e _____ __ _ "); - Debugger.sendConsoleMsg("&e |_ _| / _| | |"); - Debugger.sendConsoleMsg("&e | | _ __ | |_ ___ | |"); - Debugger.sendConsoleMsg("&e | | | '_ \\| _/ _ \\ | |"); - Debugger.sendConsoleMsg("&e _| |_| | | | || (_) | |_|"); - Debugger.sendConsoleMsg("&e |_____|_| |_|_| \\___/ (_)"); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/UpdateChecker.java b/src/main/java/plugily/projects/murdermystery/utils/UpdateChecker.java deleted file mode 100644 index 21f43cfc..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/UpdateChecker.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils; - -import com.google.common.base.Preconditions; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import org.apache.commons.lang.math.NumberUtils; -import org.bukkit.plugin.java.JavaPlugin; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.concurrent.CompletableFuture; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * A utility class to assist in checking for updates for plugins uploaded to - * SpigotMC. Before any members of this - * class are accessed, {@link #init(JavaPlugin, int)} must be invoked by the plugin, - * preferrably in its {@link JavaPlugin#onEnable()} method, though that is not a - * requirement. - *

- * This class performs asynchronous queries to SpiGet, - * an REST server which is updated periodically. If the results of {@link #requestUpdateCheck()} - * are inconsistent with what is published on SpigotMC, it may be due to SpiGet's cache. - * Results will be updated in due time. - * - * @author Parker Hawke - 2008Choco - */ -public final class UpdateChecker { - - private static final String USER_AGENT = "CHOCO-update-checker"; - private static final String UPDATE_URL = "https://api.spiget.org/v2/resources/%d/versions?size=1&sort=-releaseDate"; - private static final Pattern DECIMAL_SCHEME_PATTERN = Pattern.compile("\\d+(?:\\.\\d+)*"); - public static final VersionScheme VERSION_SCHEME_DECIMAL = (first, second) -> { - String[] firstSplit = splitVersionInfo(first), secondSplit = splitVersionInfo(second); - if(firstSplit == null || secondSplit == null) { - return null; - } - - for(int i = 0; i < Math.min(firstSplit.length, secondSplit.length); i++) { - int currentValue = NumberUtils.toInt(firstSplit[i]), newestValue = NumberUtils.toInt(secondSplit[i]); - - if(newestValue > currentValue) { - return second; - } else if(newestValue < currentValue) { - return first; - } - } - - return (secondSplit.length > firstSplit.length) ? second : first; - }; - private static UpdateChecker instance; - private final JavaPlugin plugin; - private final int pluginID; - private final VersionScheme versionScheme; - private UpdateResult lastResult = null; - - private UpdateChecker(JavaPlugin plugin, int pluginID, VersionScheme versionScheme) { - this.plugin = plugin; - this.pluginID = pluginID; - this.versionScheme = versionScheme; - } - - private static String[] splitVersionInfo(String version) { - Matcher matcher = DECIMAL_SCHEME_PATTERN.matcher(version); - if(!matcher.find()) { - return null; - } - - return matcher.group().split("\\."); - } - - /** - * Initialize this update checker with the specified values and return its instance. If an instance - * of UpdateChecker has already been initialized, this method will act similarly to {@link #get()} - * (which is recommended after initialization). - * - * @param plugin the plugin for which to check updates. Cannot be null - * @param pluginID the ID of the plugin as identified in the SpigotMC resource link. For example, - * "https://www.spigotmc.org/resources/veinminer.12038/" would expect "12038" as a value. The - * value must be greater than 0 - * @param versionScheme a custom version scheme parser. Cannot be null - * @return the UpdateChecker instance - */ - public static UpdateChecker init(JavaPlugin plugin, int pluginID, VersionScheme versionScheme) { - Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); - Preconditions.checkArgument(pluginID > 0, "Plugin ID must be greater than 0"); - Preconditions.checkArgument(versionScheme != null, "null version schemes are unsupported"); - - return (instance == null) ? instance = new UpdateChecker(plugin, pluginID, versionScheme) : instance; - } - - /** - * Initialize this update checker with the specified values and return its instance. If an instance - * of UpdateChecker has already been initialized, this method will act similarly to {@link #get()} - * (which is recommended after initialization). - * - * @param plugin the plugin for which to check updates. Cannot be null - * @param pluginID the ID of the plugin as identified in the SpigotMC resource link. For example, - * "https://www.spigotmc.org/resources/veinminer.12038/" would expect "12038" as a value. The - * value must be greater than 0 - * @return the UpdateChecker instance - */ - public static UpdateChecker init(JavaPlugin plugin, int pluginID) { - return init(plugin, pluginID, VERSION_SCHEME_DECIMAL); - } - - /** - * Get the initialized instance of UpdateChecker. If {@link #init(JavaPlugin, int)} has not yet been - * invoked, this method will throw an exception. - * - * @return the UpdateChecker instance - */ - public static UpdateChecker get() { - Preconditions.checkState(instance != null, "Instance has not yet been initialized. Be sure #init() has been invoked"); - return instance; - } - - /** - * Check whether the UpdateChecker has been initialized or not (if {@link #init(JavaPlugin, int)} - * has been invoked) and {@link #get()} is safe to use. - * - * @return true if initialized, false otherwise - */ - public static boolean isInitialized() { - return instance != null; - } - - /** - * Request an update check to SpiGet. This request is asynchronous and may not complete - * immediately as an HTTP GET request is published to the SpiGet API. - * - * @return a future update result - */ - public CompletableFuture requestUpdateCheck() { - return CompletableFuture.supplyAsync(() -> { - int responseCode = -1; - try { - URL url = new URL(String.format(UPDATE_URL, pluginID)); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.addRequestProperty("User-Agent", USER_AGENT); - - InputStreamReader reader = new InputStreamReader(connection.getInputStream()); - responseCode = connection.getResponseCode(); - - JsonElement element = new JsonParser().parse(reader); - if(!element.isJsonArray()) { - return new UpdateResult(UpdateReason.INVALID_JSON); - } - - reader.close(); - - JsonObject versionObject = element.getAsJsonArray().get(0).getAsJsonObject(); - String current = plugin.getDescription().getVersion(), newest = versionObject.get("name").getAsString(); - String latest = versionScheme.compareVersions(current, newest); - - if(latest == null) { - return new UpdateResult(UpdateReason.UNSUPPORTED_VERSION_SCHEME); - } else if(latest.equals(current)) { - return new UpdateResult(current.equals(newest) ? UpdateReason.UP_TO_DATE : UpdateReason.UNRELEASED_VERSION); - } else if(latest.equals(newest)) { - return new UpdateResult(UpdateReason.NEW_UPDATE, latest); - } - } catch(IOException e) { - return new UpdateResult(UpdateReason.COULD_NOT_CONNECT); - } catch(JsonSyntaxException e) { - return new UpdateResult(UpdateReason.INVALID_JSON); - } - - return new UpdateResult(responseCode == 401 ? UpdateReason.UNAUTHORIZED_QUERY : UpdateReason.UNKNOWN_ERROR); - }); - } - - /** - * Get the last update result that was queried by {@link #requestUpdateCheck()}. If no update - * check was performed since this class' initialization, this method will return null. - * - * @return the last update check result. null if none. - */ - public UpdateResult getLastResult() { - return lastResult; - } - - - /** - * A constant reason for the result of {@link UpdateResult}. - */ - public enum UpdateReason { - - /** - * A new update is available for download on SpigotMC. - */ - NEW_UPDATE, // The only reason that requires an update - - /** - * A successful connection to the SpiGet API could not be established. - */ - COULD_NOT_CONNECT, - - /** - * The JSON retrieved from SpiGet was invalid or malformed. - */ - INVALID_JSON, - - /** - * A 401 error was returned by the SpiGet API. - */ - UNAUTHORIZED_QUERY, - - /** - * The version of the plugin installed on the server is greater than the one uploaded - * to SpigotMC's resources section. - */ - UNRELEASED_VERSION, - - /** - * An unknown error occurred. - */ - UNKNOWN_ERROR, - - /** - * The plugin uses an unsupported version scheme, therefore a proper comparison between - * versions could not be made. - */ - UNSUPPORTED_VERSION_SCHEME, - - /** - * The plugin is up to date with the version released on SpigotMC's resources section. - */ - UP_TO_DATE - - } - - /** - * A functional interface to compare two version Strings with similar version schemes. - */ - @FunctionalInterface - public interface VersionScheme { - - /** - * Compare two versions and return the higher of the two. If null is returned, it is assumed - * that at least one of the two versions are unsupported by this version scheme parser. - * - * @param first the first version to check - * @param second the second version to check - * @return the greater of the two versions. null if unsupported version schemes - */ - String compareVersions(String first, String second); - - } - - /** - * Represents a result for an update query performed by {@link UpdateChecker#requestUpdateCheck()}. - */ - public final class UpdateResult { - - private final UpdateReason reason; - private final String newestVersion; - - { // An actual use for initializer blocks. This is madness! - UpdateChecker.this.lastResult = this; - } - - private UpdateResult(UpdateReason reason, String newestVersion) { - this.reason = reason; - this.newestVersion = newestVersion; - } - - private UpdateResult(UpdateReason reason) { - Preconditions.checkArgument(reason != UpdateReason.NEW_UPDATE, "Reasons that require updates must also provide the latest version String"); - this.reason = reason; - this.newestVersion = plugin.getDescription().getVersion(); - } - - /** - * Get the constant reason of this result. - * - * @return the reason - */ - public UpdateReason getReason() { - return reason; - } - - /** - * Check whether or not this result requires the user to update. - * - * @return true if requires update, false otherwise - */ - public boolean requiresUpdate() { - return reason == UpdateReason.NEW_UPDATE; - } - - /** - * Get the latest version of the plugin. This may be the currently installed version, it - * may not be. This depends entirely on the result of the update. - * - * @return the newest version of the plugin - */ - public String getNewestVersion() { - return newestVersion; - } - - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/Utils.java b/src/main/java/plugily/projects/murdermystery/utils/Utils.java deleted file mode 100644 index 90d8ed15..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/Utils.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils; - -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import plugily.projects.commonsbox.minecraft.compat.VersionUtils; -import plugily.projects.commonsbox.string.StringFormatUtils; -import plugily.projects.murdermystery.Main; -import plugily.projects.murdermystery.arena.Arena; -import plugily.projects.murdermystery.arena.ArenaRegistry; -import plugily.projects.murdermystery.arena.ArenaState; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Plajer - *

- * Created at 06.10.2018 - */ -public class Utils { - - private static Main plugin; - - private Utils() { - } - - public static void init(Main plugin) { - Utils.plugin = plugin; - } - - /** - * Serialize int to use it in Inventories size - * ex. you have 38 kits and it will serialize it to 45 (9*5) - * because it is valid inventory size - * next ex. you have 55 items and it will serialize it to 63 (9*7) not 54 because it's too less - * - * @param i integer to serialize - * @return serialized number - */ - public static int serializeInt(int i) { - if(i == 0) return 9; //The function bellow doesn't work if i == 0, so return 9 in case that happens. - return (i % 9) == 0 ? i : (i + 9 - 1) / 9 * 9; - } - - public static void applyActionBarCooldown(Player p, int seconds) { - new BukkitRunnable() { - int ticks = 0; - - @Override - public void run() { - Arena arena = ArenaRegistry.getArena(p); - if(arena == null || arena.getArenaState() != ArenaState.IN_GAME) { - cancel(); - } - if(ticks >= seconds * 20) { - cancel(); - } - String progress = StringFormatUtils.getProgressBar(ticks, seconds * 20, 10, "■", ChatColor.COLOR_CHAR + "a", ChatColor.COLOR_CHAR + "c"); - VersionUtils.sendActionBar(p, plugin.getChatManager().colorMessage("In-Game.Cooldown-Format", p) - .replace("%progress%", progress).replace("%time%", Double.toString((double) ((seconds * 20) - ticks) / 20))); - ticks += 10; - } - }.runTaskTimer(plugin, 0, 10); - } - - public static List getNearbyBlocks(Location location, int radius) { - List blocks = new ArrayList<>(); - - org.bukkit.World world = location.getWorld(); - if(world == null) - return blocks; - - int blockX = location.getBlockX(); - int blockY = location.getBlockY(); - int blockZ = location.getBlockZ(); - - for(int x = blockX - radius; x <= blockX + radius; x++) { - for(int y = blockY - radius; y <= blockY + radius; y++) { - for(int z = blockZ - radius; z <= blockZ + radius; z++) { - blocks.add(world.getBlockAt(x, y, z)); - } - } - } - return blocks; - } - - public static Location getBlockCenter(Location location) { - return location.clone().add(0.5, 0, 0.5); - } - - public static boolean checkIsInGameInstance(Player player) { - if(!ArenaRegistry.isInArena(player)) { - player.sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("Commands.Not-Playing", player)); - return false; - } - return true; - } - - public static boolean hasPermission(CommandSender sender, String perm) { - if(sender.hasPermission(perm)) { - return true; - } - sender.sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("Commands.No-Permission")); - return false; - } - - public static boolean hasPermission(Player sender, String perm) { - if(sender.hasPermission(perm)) { - return true; - } - sender.sendMessage(plugin.getChatManager().getPrefix() + plugin.getChatManager().colorMessage("Commands.No-Permission")); - return false; - } - - public static Vector rotateAroundAxisX(Vector v, double angle) { - angle = Math.toRadians(angle); - double cos = Math.cos(angle), - sin = Math.sin(angle), - y = v.getY() * cos - v.getZ() * sin, - z = v.getY() * sin + v.getZ() * cos; - return v.setY(y).setZ(z); - } - - public static Vector rotateAroundAxisY(Vector v, double angle) { - angle = -angle; - angle = Math.toRadians(angle); - double cos = Math.cos(angle), - sin = Math.sin(angle), - x = v.getX() * cos + v.getZ() * sin, - z = v.getX() * -sin + v.getZ() * cos; - return v.setX(x).setZ(z); - } - - /** - * Checks whether itemstack is named (not null, has meta and display name) - * - * @param stack item stack to check - * @return true if named, false otherwise - */ - public static boolean isNamed(ItemStack stack) { - return stack != null && stack.hasItemMeta() && stack.getItemMeta().hasDisplayName(); - } -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/conversation/SimpleConversationBuilder.java b/src/main/java/plugily/projects/murdermystery/utils/conversation/SimpleConversationBuilder.java deleted file mode 100644 index 4aecea1e..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/conversation/SimpleConversationBuilder.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.conversation; - -import org.bukkit.ChatColor; -import org.bukkit.conversations.Conversable; -import org.bukkit.conversations.ConversationFactory; -import org.bukkit.conversations.Prompt; -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.murdermystery.Main; - -/** - * @author Plajer - *

- * Created at 25.05.2019 - */ -public class SimpleConversationBuilder { - - private static final Main plugin = JavaPlugin.getPlugin(Main.class); - private final ConversationFactory conversationFactory; - - public SimpleConversationBuilder() { - conversationFactory = new ConversationFactory(plugin) - .withModality(true) - .withLocalEcho(false) - .withEscapeSequence("cancel") - .withTimeout(30) - .addConversationAbandonedListener(listener -> { - if(listener.gracefulExit()) { - return; - } - listener.getContext().getForWhom().sendRawMessage(plugin.getChatManager().colorRawMessage("&7Operation cancelled!")); - }) - .thatExcludesNonPlayersWithMessage(ChatColor.RED + "Only by players!"); - } - - public SimpleConversationBuilder withPrompt(Prompt prompt) { - conversationFactory.withFirstPrompt(prompt); - return this; - } - - public void buildFor(Conversable conversable) { - conversationFactory.buildConversation(conversable).begin(); - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/services/ServiceRegistry.java b/src/main/java/plugily/projects/murdermystery/utils/services/ServiceRegistry.java deleted file mode 100644 index 16fb1c73..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/services/ServiceRegistry.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.services; - -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.murdermystery.utils.services.locale.LocaleService; -import plugily.projects.murdermystery.utils.services.metrics.MetricsService; - -import javax.net.ssl.HttpsURLConnection; -import java.io.IOException; -import java.net.URL; -import java.util.logging.Level; - -/** - * Class for registering new services - */ -public class ServiceRegistry { - - private static JavaPlugin registeredService; - private static boolean serviceEnabled; - private static long serviceCooldown = 0; - private static LocaleService localeService; - - private ServiceRegistry() { - } - - public static boolean registerService(JavaPlugin plugin) { - if(registeredService != null && registeredService.equals(plugin)) { - return false; - } - plugin.getLogger().log(Level.INFO, "Connecting to services, please wait! Server may freeze a bit!"); - try { - HttpsURLConnection connection = (HttpsURLConnection) new URL("https://api.plugily.xyz/ping.php").openConnection(); - connection.setConnectTimeout(3000); - connection.setReadTimeout(2000); - connection.setRequestMethod("HEAD"); - connection.setRequestProperty("User-Agent", "PLService/1.0"); - int responseCode = connection.getResponseCode(); - if(responseCode != 200) { - plugin.getLogger().log(Level.WARNING, "Plugily Projects services aren't online or inaccessible from your location! Response: " + responseCode + ". Do you think it's site problem? Contact developer! Make sure Cloudflare isn't blocked in your area!"); - serviceEnabled = false; - return false; - } - } catch(IOException ignored) { - plugin.getLogger().log(Level.WARNING, "Plugily Projects services aren't online or inaccessible from your location!"); - serviceEnabled = false; - return false; - } - registeredService = plugin; - serviceEnabled = true; - plugin.getLogger().log(Level.INFO, "Hooked with ServiceRegistry! Initialized services properly!"); - new MetricsService(plugin); - localeService = new LocaleService(plugin); - return true; - } - - public static JavaPlugin getRegisteredService() { - return registeredService; - } - - public static long getServiceCooldown() { - return serviceCooldown; - } - - public static void setServiceCooldown(long serviceCooldown) { - ServiceRegistry.serviceCooldown = serviceCooldown; - } - - public static LocaleService getLocaleService(JavaPlugin plugin) { - return (!serviceEnabled || registeredService == null || !registeredService.equals(plugin)) ? null : localeService; - } - - public static boolean isServiceEnabled() { - return serviceEnabled; - } -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/services/exception/ReportedException.java b/src/main/java/plugily/projects/murdermystery/utils/services/exception/ReportedException.java deleted file mode 100644 index 67c54001..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/services/exception/ReportedException.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.services.exception; - -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; -import plugily.projects.murdermystery.utils.services.ServiceRegistry; - -import java.util.logging.Level; - -/** - * Create reported exception with data sent to plugily.xyz reporter service - */ -public class ReportedException { - - private ReporterService reporterService; - - public ReportedException(JavaPlugin plugin, Throwable e) { - Throwable exception = e.getCause() != null ? e.getCause() : e; - StringBuilder stacktrace = new StringBuilder(exception.getClass().getSimpleName()); - if(exception.getMessage() != null) { - stacktrace.append(" (").append(exception.getMessage()).append(")"); - } - stacktrace.append("\n"); - for(StackTraceElement str : exception.getStackTrace()) { - stacktrace.append(str.toString()).append("\n"); - } - - plugin.getLogger().log(Level.WARNING, "[Reporter service] <<-----------------------------[START]----------------------------->>"); - plugin.getLogger().log(Level.WARNING, stacktrace.toString()); - plugin.getLogger().log(Level.WARNING, "[Reporter service] <<------------------------------[END]------------------------------>>"); - - if(!ServiceRegistry.isServiceEnabled() || System.currentTimeMillis() - ServiceRegistry.getServiceCooldown() < 900000) { - return; - } - ServiceRegistry.setServiceCooldown(System.currentTimeMillis()); - new BukkitRunnable() { - @Override - public void run() { - reporterService = new ReporterService(plugin, plugin.getName(), plugin.getDescription().getVersion(), plugin.getServer().getBukkitVersion() + " " + plugin.getServer().getVersion(), - stacktrace.toString()); - reporterService.reportException(); - } - }.runTaskAsynchronously(plugin); - } -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/services/exception/ReporterService.java b/src/main/java/plugily/projects/murdermystery/utils/services/exception/ReporterService.java deleted file mode 100644 index b410aca1..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/services/exception/ReporterService.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.services.exception; - -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.murdermystery.utils.Debugger; - -import javax.net.ssl.HttpsURLConnection; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.logging.Level; - -/** - * Reporter service for reporting exceptions directly to website reporter panel - */ -public class ReporterService { - - private final JavaPlugin plugin; - private final String pluginName; - private final String pluginVersion; - private final String serverVersion; - private final String error; - - //don't create it outside core - ReporterService(JavaPlugin plugin, String pluginName, String pluginVersion, String serverVersion, String error) { - this.plugin = plugin; - this.pluginName = pluginName; - this.pluginVersion = pluginVersion; - this.serverVersion = serverVersion; - this.error = error; - } - - public void reportException() { - try { - URL url = new URL("https://api.plugily.xyz/error/report.php"); - HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.setRequestProperty("User-Agent", "PLService/1.0"); - conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - conn.setDoOutput(true); - - OutputStream os = conn.getOutputStream(); - os.write(("pass=servicereporter&type=" + pluginName + "&pluginversion=" + pluginVersion + "&serverversion=" + serverVersion + "&error=" + error).getBytes(StandardCharsets.UTF_8)); - os.flush(); - os.close(); - - plugin.getLogger().log(Level.WARNING, "[Reporter service] Error reported!"); - Debugger.debug(Level.INFO, "[Reporter service] Code: {0} ({1})", conn.getResponseCode(), conn.getResponseMessage()); - } catch(IOException ignored) {/*cannot connect or there is a problem*/ - } - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/services/locale/Locale.java b/src/main/java/plugily/projects/murdermystery/utils/services/locale/Locale.java deleted file mode 100644 index 745a33ea..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/services/locale/Locale.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.services.locale; - -import java.util.List; - -/** - * Class for locales - * - * @since 1.2.0 - */ -public class Locale { - - private final String name; - private final String originalName; - private final String prefix; - private final String author; - private final List aliases; - - public Locale(String name, String originalName, String prefix, String author, List aliases) { - this.prefix = prefix; - this.name = name; - this.originalName = originalName; - this.author = author; - this.aliases = aliases; - } - - /** - * Gets name of locale, ex. English or German - * - * @return name of locale - */ - public String getName() { - return name; - } - - /** - * Gets original name of locale ex. for German it will return Deutsch, Polish returns Polski etc. - * - * @return name of locale in its language - */ - public String getOriginalName() { - return originalName; - } - - /** - * @return authors of locale - */ - public String getAuthor() { - return author; - } - - /** - * Language code ex. en_GB, de_DE, pl_PL etc. - * - * @return language code of locale - */ - public String getPrefix() { - return prefix; - } - - /** - * Valid aliases of locale ex. for German - deutsch, de, german; Polish - polski, pl, polish etc. - * - * @return aliases for locale - */ - public List getAliases() { - return aliases; - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/services/locale/LocaleRegistry.java b/src/main/java/plugily/projects/murdermystery/utils/services/locale/LocaleRegistry.java deleted file mode 100644 index 3997dd48..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/services/locale/LocaleRegistry.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.services.locale; - -import java.util.ArrayList; -import java.util.List; - -/** - * Registry class for holding locales - * - * @since 1.2.0 - */ -public class LocaleRegistry { - - private static final List registeredLocales = new ArrayList<>(); - - /** - * Register new locale into registry - * - * @param locale locale to register - * @throws IllegalArgumentException if same locale is registered twice - */ - public static void registerLocale(Locale locale) { - if(registeredLocales.contains(locale)) { - throw new IllegalArgumentException("Cannot register same locale twice!"); - } - registeredLocales.add(locale); - } - - /** - * Get all registered locales - * - * @return all registered locales - */ - public static List getRegisteredLocales() { - return registeredLocales; - } - - /** - * Get locale by its name - * - * @param name name to search - * @return locale by name or locale "Undefined" when not found (null is not returned) - * @since 1.2.2 - */ - public static Locale getByName(String name) { - for(Locale locale : registeredLocales) { - if(locale.getName().equals(name)) { - return locale; - } - } - return new Locale("Undefined", "Undefined", "", "System", new ArrayList<>()); - } -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/services/locale/LocaleService.java b/src/main/java/plugily/projects/murdermystery/utils/services/locale/LocaleService.java deleted file mode 100644 index 00d5ed07..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/services/locale/LocaleService.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.services.locale; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.commonsbox.minecraft.configuration.ConfigUtils; -import plugily.projects.murdermystery.utils.services.ServiceRegistry; - -import javax.net.ssl.HttpsURLConnection; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.Scanner; -import java.util.logging.Level; -import java.util.regex.Pattern; - -/** - * Localization service used for fetching latest locales for minigames - */ -public class LocaleService { - - private JavaPlugin plugin; - private FileConfiguration localeData; - - public LocaleService(JavaPlugin plugin) { - if(ServiceRegistry.getRegisteredService() == null || !ServiceRegistry.getRegisteredService().equals(plugin)) { - throw new IllegalArgumentException("LocaleService cannot be used without registering service via ServiceRegistry first!"); - } - if(!ServiceRegistry.isServiceEnabled()) { - return; - } - this.plugin = plugin; - try(Scanner scanner = new Scanner(requestLocaleFetch(null), "UTF-8").useDelimiter("\\A")) { - String data = scanner.hasNext() ? scanner.next() : ""; - File file = new File(plugin.getDataFolder().getPath() + "/locales/locale_data.yml"); - if(!file.exists()) { - new File(plugin.getDataFolder().getPath() + "/locales").mkdir(); - if(!file.createNewFile()) { - plugin.getLogger().log(Level.WARNING, "Couldn't create locales folder! We must disable locales support."); - return; - } - } - Files.write(file.toPath(), data.getBytes()); - this.localeData = ConfigUtils.getConfig(plugin, "/locales/locale_data"); - plugin.getLogger().log(Level.INFO, "Fetched latest localization file from repository."); - } catch(IOException ignored) { - //ignore exceptions - plugin.getLogger().log(Level.WARNING, "Couldn't access locale fetcher service or there is other problem! You should notify author!"); - } - } - - private static String toReadable(String version) { - String[] split = Pattern.compile(".", Pattern.LITERAL).split(version.replace("v", "")); - StringBuilder versionBuilder = new StringBuilder(); - for(String s : split) { - versionBuilder.append(String.format("%4s", s)); - } - version = versionBuilder.toString(); - return version; - } - - private InputStream requestLocaleFetch(Locale locale) { - try { - URL url = new URL("https://api.plugily.xyz/locale/v2/fetch.php"); - HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.setRequestProperty("User-Agent", "PLLocale/1.0"); - conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - conn.setRequestProperty("Accept-Charset", "UTF-8"); - conn.setDoOutput(true); - - OutputStream os = conn.getOutputStream(); - if(locale == null) { - os.write(("pass=localeservice&type=" + plugin.getName()).getBytes(StandardCharsets.UTF_8)); - } else { - os.write(("pass=localeservice&type=" + plugin.getName() + "&locale=" + locale.getPrefix()).getBytes(StandardCharsets.UTF_8)); - } - os.flush(); - os.close(); - return conn.getInputStream(); - } catch(Exception e) { - e.printStackTrace(); - return new InputStream() { - @Override - public int read() { - return -1; - } - }; - } - } - - /** - * Sends a demand request to download latest locale from Plugily-Projects/locale_storage repository - * Whole repository can be seen here https://github.com/Plugily-Projects/locale_storage - * - * @param locale locale to download - * @return SUCCESS for downloaded locale, FAIL for service fault, LATEST when locale is latest as one in repository - */ - public DownloadStatus demandLocaleDownload(Locale locale) { - //service fault - if(localeData == null) { - return DownloadStatus.FAIL; - } - File localeFile = new File(plugin.getDataFolder() + "/locales/" + locale.getPrefix() + ".properties"); - if(!localeFile.exists() || !isExact(locale, localeFile)) { - return writeFile(locale); - } - return DownloadStatus.LATEST; - } - - private DownloadStatus writeFile(Locale locale) { - try(Scanner scanner = new Scanner(requestLocaleFetch(locale), "UTF-8").useDelimiter("\\A")) { - String data = scanner.hasNext() ? scanner.next() : ""; - try(OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File(plugin.getDataFolder().getPath() + "/locales/" + locale.getPrefix() + ".properties")), StandardCharsets.UTF_8)) { - writer.write(data); - } - return DownloadStatus.SUCCESS; - } catch(IOException ignored) { - plugin.getLogger().log(Level.WARNING, "Demanded locale " + locale.getPrefix() + " cannot be downloaded! You should notify author!"); - return DownloadStatus.FAIL; - } - } - - /** - * Checks if plugin version allows to update locale - * - * @return true if locale can be updated for this version else cannot - */ - public boolean isValidVersion() { - //service fault - if(localeData == null) { - return false; - } - return !checkHigher(plugin.getDescription().getVersion(), localeData.getString("locales.valid-version", plugin.getDescription().getVersion())); - } - - private boolean isExact(Locale locale, File file) { - try(Scanner scanner = new Scanner(requestLocaleFetch(locale), "UTF-8").useDelimiter("\\A")) { - String onlineData = scanner.hasNext() ? scanner.next() : ""; - Scanner localScanner = new Scanner(file, "UTF-8").useDelimiter("\\A"); - String localData = localScanner.hasNext() ? localScanner.next() : ""; - localScanner.close(); - - return onlineData.equals(localData); - } catch(IOException ignored) { - return false; - } - } - - private boolean checkHigher(String currentVersion, String newVersion) { - String current = toReadable(currentVersion); - String newVer = toReadable(newVersion); - return current.compareTo(newVer) < 0; - } - - /** - * Download status enum for locale download demands - */ - public enum DownloadStatus { - SUCCESS, FAIL, LATEST - } - -} diff --git a/src/main/java/plugily/projects/murdermystery/utils/services/metrics/MetricsService.java b/src/main/java/plugily/projects/murdermystery/utils/services/metrics/MetricsService.java deleted file mode 100644 index bfc25851..00000000 --- a/src/main/java/plugily/projects/murdermystery/utils/services/metrics/MetricsService.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * MurderMystery - Find the murderer, kill him and survive! - * Copyright (C) 2020 Plugily Projects - maintained by Tigerpanzer_02, 2Wild4You and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package plugily.projects.murdermystery.utils.services.metrics; - -import org.bukkit.Bukkit; -import org.bukkit.plugin.java.JavaPlugin; -import plugily.projects.murdermystery.utils.services.ServiceRegistry; - -import javax.net.ssl.HttpsURLConnection; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Timer; -import java.util.TimerTask; -import java.util.logging.Level; - -/** - * Metrics service for sending usage data - */ -public class MetricsService { - - private JavaPlugin plugin; - - public MetricsService(JavaPlugin plugin) { - if(ServiceRegistry.getRegisteredService() == null || !ServiceRegistry.getRegisteredService().equals(plugin)) { - throw new IllegalArgumentException("MetricsService cannot be used without registering service via ServiceRegistry first!"); - } - if(!ServiceRegistry.isServiceEnabled()) { - return; - } - this.plugin = plugin; - metricsSchedulerTask(); - } - - private void metricsSchedulerTask() { - Timer timer = new Timer(true); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if(!plugin.isEnabled()) { - timer.cancel(); - return; - } - Bukkit.getScheduler().runTask(plugin, () -> { - try { - final byte[] post = ("pass=metricsservice&type=" + plugin.getName() + "&pluginversion=" + plugin.getDescription().getVersion() + - "&serverversion=" + plugin.getServer().getBukkitVersion() + "&ip=" + InetAddress.getLocalHost().getHostAddress() + ":" + plugin.getServer().getPort() + - "&playersonline=" + Bukkit.getOnlinePlayers().size()).getBytes(StandardCharsets.UTF_8); - new Thread(() -> { - try { - plugin.getLogger().log(Level.FINE, "Metrics data sent!"); - URL url = new URL("https://api.plugily.xyz/metrics/receiver.php"); - HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.setRequestProperty("User-Agent", "PLMetrics/1.0"); - conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - conn.setDoOutput(true); - - OutputStream os = conn.getOutputStream(); - os.write(post); - os.flush(); - os.close(); - StringBuilder content; - - try(BufferedReader in = new BufferedReader( - new InputStreamReader(conn.getInputStream()))) { - - String line; - content = new StringBuilder(); - - while((line = in.readLine()) != null) { - content.append(line); - content.append(System.lineSeparator()); - } - } - - plugin.getLogger().log(Level.FINE, "Metrics response: " + content.toString()); - } catch(IOException ignored) { - } - }).start(); - } catch(IOException ignored) {/*cannot connect or there is a problem*/} - }); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - } - -} diff --git a/src/main/resources/arena_selector.yml b/src/main/resources/arena_selector.yml new file mode 100644 index 00000000..b08570ed --- /dev/null +++ b/src/main/resources/arena_selector.yml @@ -0,0 +1,6 @@ +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/arenas.yml b/src/main/resources/arenas.yml index 23ee01d7..72cc2d41 100644 --- a/src/main/resources/arenas.yml +++ b/src/main/resources/arenas.yml @@ -1,12 +1,13 @@ instances: default: lobbylocation: world,364.0,63.0,-72.0,0.0,0.0 - Endlocation: world,364.0,63.0,-72.0,0.0,0.0 + startlocation: world,364.0,63.0,-72.0,0.0,0.0 + endlocation: world,364.0,63.0,-72.0,0.0,0.0 minimumplayers: 2 maximumplayers: 10 mapname: mapname world: worldname - signs: [] + signs: [ ] isdone: false playerspawnpoints: - world,364.0,63.0,-72.0,0.0,0.0 @@ -16,4 +17,11 @@ instances: - world,364.0,63.0,-72.0,0.0,0.0 playerpermurderer: 5 playerperdetective: 7 - goldvisuals: false \ No newline at end of file + goldvisuals: false + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/bungee.yml b/src/main/resources/bungee.yml index 6e83e1d4..b4a4a8f4 100644 --- a/src/main/resources/bungee.yml +++ b/src/main/resources/bungee.yml @@ -1,7 +1,7 @@ # Configuration for Bungeecord support. -# Remember to enable it in config.yml (BungeeActivated option) +# Remember to enable it in config.yml (Bungee-Mode: true) -# Your bungeecord server name where player will be teleported after game (main lobby with signs etc.) +# Your bungeecord server name where players will be teleported after game (main lobby with signs etc.) Hub: lobby # Should game server be closed after game? @@ -17,11 +17,18 @@ End-Location-Hub: true # %state% - Game state will be visible at MOTD. MOTD: Manager: false - Message: "The actual game state of mm is %state%" + Message: "The actual game state of the minigame is %state%" Game-States: Inactive: "&lInactive..." In-Game: "&lIn-game" Starting: "&e&lStarting" Full-Game: "&4&lFULL" Ending: "&lEnding" - Restarting: "&c&lRestarting" \ No newline at end of file + Restarting: "&c&lRestarting" + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 56944520..d4661ee3 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,188 +1,182 @@ -# Murder Mystery configuration file +## Thanks for using our plugins! ~Tigerpanzer_02 from Plugily Projects +# murdermystery configuration file # -# You can edit here the basic things of MM +# You can edit here the basic things of murdermystery # Please read everything CAREFULLY! # You don't want to break anything, do you? # + # Select locale of MurderMystery, default it's English. # Available locales: # default - English language. Uses 'language.yml'. -# de - Deutsche sprache pl - Język polski -# fr - Langue française cn - 简体中文 -# zh_tw - 中文(繁體) kr - 한국어 -# id - Bhasa Indonesia hu - Magyar nyelv -# cs - Český jazyk ro - Limba română -# vn - Tiếng Việt it - Lingua italiana -# ru - Русский язык es - Idioma español -# nl - Nederlandse taal pt_br - Português (Brasil) -# tr - Türk dili sk - Slovenský jazyk -# ja - Japanese af - Afrikaans -# dk - Danish th - Thai -# uk - Ukrainian +# See https://github.com/Plugily-Projects/locale_storage/tree/master/plugins/minecraft/murdermystery +# Use filename of the language e.g. de_DE.yml -> locale: de_DE locale: default -# Enable bossbar support? -Bossbar-Enabled: true - -# How many seconds game should take to start. -Starting-Waiting-Time: 60 -# Lobby waiting time set when lobby max players number is reached, used to start game quicker. -Start-Time-On-Full-Lobby: 15 +# Should we display a boss bar with additional arena information? +Bossbar: + Display: true + # Interval in seconds between messages + Interval: 10 -# How many seconds classic game should play. -Classic-Gameplay-Time: 270 -# Should we hook into bungee cord? (If you wanna use arena per server option) +# Should we hook into bungeecord? (If you wanna use arena per server option) +# This option will let you access bungee.yml and its options. # You STILL need to use external addon for HUB server game signs -# Murder Mystery doesn't offer that addon. -# Check here for more info: https://wiki.plugily.xyz/murdermystery/support/servertips#bungeecord-lobby-signs -BungeeActivated: false +# Check here for more info: https://wiki.plugily.xyz/ +Bungee-Mode: false -# Enable this option when you're using MySQL, otherwise it won't work. -# Be careful when changing this because there is NO migrator between -# flat file and MySQL for player stats. -DatabaseActivated: false # Enable Inventory Manager for your games? (VERY USEFUL feature for MULTI ARENA) # This saves inventory of players and restores it after player leaves arena. -# Saved elements: max health, health, food, experience, full inventory, armor contents, fire ticks, active potions, gamemode -InventoryManager: true - -# Should in-game chat format be enabled? -# You can edit the formatting in language.yml -ChatFormat-Enabled: true - -# Should we disable all chat related stuff? -# It will disable the separated chat, for example -Disable-Separate-Chat: false - -# Should we disable death messages, so the player dies without other recognizes it -# It will not broadcast the death message to all ;) -Hide-Death: false +# Saved elements: max health, health, food, experience, full inventory, armor contents, fire ticks, active potions +Inventory-Manager: true + + +Commands: + # Commands which can be used in game, remove all of them to disable (only works if Block.In-Game.Commands = true) + Whitelist: + - me + - help + # Enable and Disable predefined shortened commands or add your own + Shorter: + '1': + Short: "start" + Executes: "murdermysteryadmin forcestart" + Enabled: true + '2': + Short: "leave" + Executes: "murdermystery leave" + Enabled: true + '3': + Short: "kit" + Executes: "murdermystery selectkit" + Enabled: false + '4': + Short: "stats" + Executes: "murdermystery stats" + Enabled: false + '5': + Short: "top" + Executes: "murdermystery top" + Enabled: true + + +# Block some functions of your players +Block: + In-Game: + # Should we block every not plugin associated commands in game? + Commands: true + # Should the leave command be blocked inside arena? + Leave: false + # Cancels Item Movement into player crafting, enchantment tables, anvils ... + Item-Move: true -# Should we override corpses spawn from CorpsesReborn plugin? -# When player will die outside game corpse won't be spawned! -# Disable this if you don't want this! -# WARNING: If disabled, two corpses will be spawned when player in-game dies -Override-Corpses-Spawn: true -# Which item should be your Murderer sword? -Murderer-Sword-Material: IRON_SWORD - -# How many blocks per tick sword thrown by murderer should fly -# Please avoid high values as it might look like the sword is -# blinking each tick -Murderer-Sword-Speed: 0.65 +# Enable this option when you're using MySQL, otherwise it won't work. +# Be careful when changing this because there is NO migrator between +# flat file and MySQL for player stats. +# If this option is disabled it means all stats will be saved as flat file! +Database: false -# How many blocks should the sword fly -Murderer-Sword-Fly-Range: 20 -# In what radius should we hit the players -Murderer-Sword-Fly-Hit-Range: 0.5 +# Should we enable in game rewards? See rewards.yml for more... +# You should also check out our script engine tutorial for rewards! https://tutorial.plugily.xyz +Rewards: true -#How long should be the sword attack after throw cooldown in seconds? -#Its normal lower than Murderer-Sword-Fly-Cooldown! -Murderer-Sword-Attack-Cooldown: 1 -#How long should be the sword fly cooldown in seconds? -Murderer-Sword-Fly-Cooldown: 5 +# Enable in game (eg. '[KIT][LEVEL] Tigerpanzer_02: hey') special formatting? +# Formatting is configurable in language.yml +# You can use PlaceholderAPI placeholders in chat format! +Plugin-Chat-Format: true -#Should we change spawner mode to spawn on all spawners instant of random one -Change-Gold-Spawner-Mode-To-All: false -#Should we disable the gold spawn limit (It does not spawn more gold than spawner locations) -Disable-Gold-Limiter: false +# Should we enable a separate arena chat for players inside a arena +# Useful on multi arena servers that don't want the same chat for all players on the server +Separate-Arena-Chat: true -#How much arrows should a player with bow gets when he pick up a gold ingot? -Detective-Gold-Pick-Up-Arrows: 1 -#How much gold should a player need to get a bow -Gold-For-Bow: 10 +# Should we fire some cool fireworks at locations of every player at special events such as the game end? +Firework: true -#How much arrows should the player get? (Cause: Bow because enough gold collected) -Gold-Bow-Arrows: 3 -#How much arrows should the detective gets on game start or when a player get a bow? -Detective-Default-Arrows: 3 +# Should blocks behind game signs change their color based on game state? +# They will change color to: +# - white (waiting for players) stained glass +# - yellow (starting) stained glass +# - orange (in game) stained glass +# - gray (ending) stained glass +# - black (restarting) stained glass +# or define your own at signs.yml! +Sign-Block-States: true -#How much arrows should the fake detective get? (Cause: Player pick up bow after detective died) -Detective-Fake-Arrows: 3 -#How much arrows should the player get when the prayer gives a bow to him? -Detective-Prayer-Arrows: 2 +# Should holiday events for the plugin be enabled? +# Eg. 4 days before and 4 days after Halloween special effects +# for death, spooky! There are more holiday events! Check wiki! +# Wiki: - +Holidays: true -#How long should be the bow shoot cooldown in seconds? -Detective-Bow-Cooldown: 5 -#Should Detectives be killed if they kill a innocent? -Enable-Kill-Detective-If-Innocent-Killed: true +# Should the plugin enable special powerups which can be found in powerups.yml +Powerups: false -#Should there be a innocent locator -Enable-Innocent-Locator: true -#Should the murderer get speed effect? -Speed-Effect-Murderer: - Enabled: true - #Enter a multiplier (min 2, max 10) - Speed: 3 +# Should we create leaderboards out of the stats? +Leaderboard: true -# Play sound when a user gets score. -# https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Sound.html -AddScore-Sound: "" -# Basic permissions for game, permissions explained here: https://wiki.plugily.xyz/murdermystery/setup/cmdsandperms#basic-permissions -Basic-Permissions: - Full-Games-Permission: "murdermystery.fullgames" - # represents arena name (NOT MAP NAME!), for example: 'murdermystery.join.MM02' - # use 'murdermystery.join.*' to enable access to all arenas - Join-Permission: "murdermystery.join." +Parties: + # Should we try to hook into your current party plugin? (Supports well know party plugins, see wiki!) + # It will group up all players with the party leader. The party leader can join with the whole party! + External: true + # Should we enable our own party system that can be only used for this plugin? + # Check the wiki for commands + Own: false -# Should we enable short commands such as /start and /leave -Enable-Short-Commands: false -# Should /mm leave command be blocked? -Disable-Leave-Command: false +Damage: + # Should players get fall damage? + Fall: false + # Should players get drowning damage? + Drowning: false + # Should players get fire damage? + Fire: false + # Should players lose food ingame? + Food: false -# Should players get no fall damage? -Disable-Fall-Damage: false -# Commands which can be used in game, remove all of them to disable -Whitelisted-Commands: - - me - - help +Option: + Player: + # Disable player drops ingame? + Drop: true -# Enable in game rewards? See rewards.yml for more... -Rewards-Enabled: false -# Should we block every not Murder Mystery associated commands in game? -Block-Commands-In-Game: true +Cycle: + # Should we make permanent clear weather on all worlds where our arenas are? + Weather: false + # Should the time on the world your arenas are modified to stay at the same time? + Daylight: + Enable: false + Time: 10000 -# Should we fire some cool fireworks at location of every player after the game ends? -Firework-When-Game-Ends: true -# Should players' name tags in game be hidden? -Nametags-Hidden: true +# How many seconds game should take to start. +Time-Manager: + Waiting: 20 + Starting: 60 + Shorten-Waiting-Full: 15 + Shorten-Waiting-Force: 5 + In-Game: 270 + Ending: 10 + Restarting: 5 -# Should blocks behind game signs change their color based on game state? -# They will change color to: -# - white (waiting for players) stained glass -# - yellow (starting) stained glass -# - orange (in game) stained glass -# - gray (ending) stained glass -# - black (restarting) stained glass -Signs-Block-States-Enabled: true +# Allow spectators on arena instances +Spectators: true -Arena-Selector: - # Change items of arena selector - State-Item: - Waiting: LIME_wool - Starting: YELLOW_wool - In-Game: RED_wool - Ending: RED_wool - Restarting: RED_wool Update-Notifier: # Should we check for updates on plugin start/after admin join? @@ -192,17 +186,82 @@ Update-Notifier: # BETA IS NOT ALWAYS AS STABLE AS NORMAL RELEASE! Notify-Beta-Versions: true -#Disable Party features of external party plugins (such as PAF, Parties ...) -Disable-Parties: true - -#Add trails that you want to blacklist from all trails(particles) -Blacklisted-Trails: - - "elder_guardian" - - "block_crack" - - "item_crack" - - "block_dust" - -# Don't modify. -Version: 23 - -# No way! You've reached the end! But... where's the dragon!? \ No newline at end of file +Corpses: + # Should we override corpses spawn from CorpsesReborn plugin? + # When player will die outside game corpse won't be spawned! + # Disable this if you don't want this! + # WARNING: If disabled, two corpses will be spawned when player in-game dies + Integration-Overwrite: true + + +Gold: + #Should we change spawner mode to spawn on all spawners instant of random one + Spawner-Mode: false + #Should we disable the gold spawn limit (It does not spawn more gold than spawner locations) + Limiter: false + Amount: + #How much gold should a player need to get a bow + Bow: 10 + #How much arrows should the player get? (Cause: Bow because enough gold collected) + Arrows: 3 + #How much arrows should a player with bow gets when he pick up a gold ingot? + Pick-Up: 1 + + +Bow: + #Should Detectives be killed if they kill a innocent? + Kill-Detective: true + Amount: + Arrows: + #How much arrows should the detective gets on game start or when a player get a bow? + Detective: 10 + #How much arrows should the fake detective get? (Cause: Player pick up bow after detective died) + Fake: 3 + #How much arrows should the player get when the prayer gives a bow to him? + Prayer: 2 + #How much arrows should the player get after x picked up gold + Gold: 3 + #How long should be the bow shoot cooldown in seconds? + Cooldown: 5 + + +Hide: + # Should we disable death messages, so the player dies without other recognizes it + # It will not broadcast the death message to all ;) + Death: false + # Should players' name tags in game be hidden? + Nametags: true + + +Murderer: + # Should the murderer get speed effect? + # Enter a multiplier (min 2, max 10, 1 is normal speed) + Speed: 3 + # Should the Murderer get a locator with Innocent location information + # gets the locator if arena time lower 30 and only one innocent left + Locator: true + + +Sword: + # How many blocks per tick sword thrown by murderer should fly + # Please avoid high values as it might look like the sword is + # blinking each tick + Speed: 0.65 + Fly: + # How many blocks should the sword fly + Range: 20 + # In what radius should we hit the players + Radius: 0.5 + Cooldown: + #How long should be the sword attack after throw cooldown in seconds? + #Its normal lower than Murderer-Sword-Fly-Cooldown! + Attack: 1 + #How long should be the sword fly cooldown in seconds? + Fly: 5 + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/internal/data.yml b/src/main/resources/internal/data.yml new file mode 100644 index 00000000..c7e43c47 --- /dev/null +++ b/src/main/resources/internal/data.yml @@ -0,0 +1,29 @@ +###############################[IMPORTANT]############################### +# +# Leave this file as it is! It is kinda an internal file! +# +### !!!Do not change anything here!!! +# +### THIS FILE AUTOMATICALLY REGENERATES ON SERVER RESTART +# +###############################[IMPORTANT]############################### +Plugin: + Name: + Short: mm + Long: murdermystery + Id: + Spigot: 66614 + BStats: 3038 + Compatibility: + Spigot: + - "1.8" + - "1.9" + - "1.10" + - "1.11" + - "1.12" + - "1.13" + - "1.14" + - "1.15" + - "1.16" + - "1.17" + - "1.18" \ No newline at end of file diff --git a/src/main/resources/internal/leaderboards_data.yml b/src/main/resources/internal/leaderboards_data.yml new file mode 100644 index 00000000..cec96167 --- /dev/null +++ b/src/main/resources/internal/leaderboards_data.yml @@ -0,0 +1 @@ +holograms: {} \ No newline at end of file diff --git a/src/main/resources/language.yml b/src/main/resources/language.yml index d55d7121..6366c9db 100644 --- a/src/main/resources/language.yml +++ b/src/main/resources/language.yml @@ -1,337 +1,454 @@ -# You can translate Murder Mystery messages here. +# You can translate MurderMystery messages here. # Color codes (&) supported. # -# Use \n to make new line -# Some messages like kit and kit items +# Use \n to make new line +# Some messages like item # descriptions don't support new lines # they are wrapped every 40 characters automatically # # Some messages support their own placeholders -# like %player% +# like %player%, %kit% etc. -# Murder Mystery commands messages +# +# Color scheme +# +Color: + Placeholder: + Value: "&4" + Number: "&4" + Player: "&b" + Other: "&4" + Chat: + Issue: "&c" + Messages: "&7" + Special-Char: + Contains: "[,],(,),{,},■,/,|,▸" + Before: "&8" + + +# +# Command messages +# Commands: - Did-You-Mean: "&6Did you mean &e/%command%&6?" - Teleported-To-The-Lobby: "Teleported to the lobby!" - Removed-Game-Instance: "&cSuccessfully removed game instance!" - No-Arena-Like-That: "&cNo arena with that ID!" - Look-Sign: "&cYou have to look at a sign to perform this command!" - Type-Arena-Name: "&cPlease type arena ID!" - No-Free-Arenas: "&cThere are no free arenas!" - Statistics: - Type-Name: "&cPlease type statistic name to view!" - Invalid-Name: "&cName of statistic is invalid! Type: kills, deaths, games_played, wins, loses, highest_score" - Header: "&8&m-------------------[&6 Top 10 &8&m]-------------------" - Format: "&e#%position% %name% - %value% &7%statistic%" - Only-By-Player: "&cYou can execute this command only as player!" - Not-Playing: "&cYou must play to execute this command!" - No-Permission: "&cYou don't have permission to use this command!" - Admin-Commands: - Teleported-To-Player: "&aTeleported to player!" - Player-Not-Found: "&cPlayer not found!" - Success-Reload: "&aArenas reloaded!" - List-Command: - Header: "&aMurder Mystery &6arenas:" - Format: "&a%arena% &e%status% &6%players%/%maxplayers%" - No-Arenas: "&cThere are no game instances!" - Stats-Command: - Header: "&l-----YOUR STATS-----" - Header-Other: "&l-----STATS FOR %player%-----" - Footer: "&l--------------------" - Kills: "&aKills: &e" - Deaths: "&aDeaths: &e" - Wins: "&aWins: &e" - Loses: "&aLoses: &e" - Highest-Score: "&aHighest score: &e" - Games-Played: "&aGames played: &e" - Main-Command: - Header: "&6----------------{Murder Mystery commands}----------" - Description: "&aGame commands:\n - &b/mm stats: &7Shows your stats!\n - &b/mm leave: &7Quits current arena!\n - &b/mm join : &7Joins specified arena!\n - &b/mm top : &7Shows top 10 players!\n - &b/mm randomjoin: &7Join random arena!" - Admin-Bonus-Description: "\n&b/mma: &7Shows all the admin commands" + Did-You-Mean: "%plugin_prefix% Did you mean /%value%?" + Command-Executed: "%plugin_prefix% Command successfully executed!" + Teleported-To-Lobby: "%plugin_prefix% Teleported to lobby!" + Removed-Game-Instance: "%color_chat_issue%%plugin_prefix% Successfully removed game instance!" + No-Arena-Like-That: "%color_chat_issue%%plugin_prefix% No arena with that ID!" + Look-At-Sign: "%color_chat_issue%%plugin_prefix% You have to look at a sign to perform this command!" + Type-Arena-Name: "%color_chat_issue%%plugin_prefix% Please type arena ID!" + Hold-Any-Item: "%color_chat_issue%%plugin_prefix% You must hold any item!" + No-Free-Arenas: "%color_chat_issue%%plugin_prefix% There are no free arenas!" + Only-By-Player: "%color_chat_issue%%plugin_prefix% You can execute this command only as player!" + Not-Playing: "%color_chat_issue%%plugin_prefix% You must play to execute this command!" + No-Permission: "%color_chat_issue%%plugin_prefix% You don't have permission to use this command!" + Player-Not-Found: "%color_chat_issue%%plugin_prefix% Target player %player% doesn't exist!" + Invalid-Location-Teleport: "%color_chat_issue%%plugin_prefix% Location to teleport is invalid!" + Wrong-Usage: "%color_chat_issue%%plugin_prefix% Wrong usage. Do %value%" + Admin: + Adjust-Statistic: "%plugin_prefix% Statistic %value% of %player% is now %number%!" + Reload-Success: "%plugin_prefix% Arenas reloaded!" + List: + Header: "%plugin_name% arenas: Name State Players" + Format: "%arena_name% %arena_state_placeholder% %arena_players_size%/%arena_max_players%" + No-Arenas: "%color_chat_issue%%plugin_prefix% There are no game instances!" + Spychat: + Toggled: "%plugin_prefix% Game spy chat toggled to %value%" + Main: + Header: "&6----------------{%plugin_name% commands}----------" + Description: + - "&aGame commands:" + - "&b/%plugin_short_command% stats: Shows your stats!" + - "&b/%plugin_short_command% leave: Quits current arena!" + - "&b/%plugin_short_command% join : Joins specified arena!" + - "&b/%plugin_short_command% top : Shows top 10 players!" + - "&b/%plugin_short_command% randomjoin: Join random arena!" + Admin-Bonus-Description: "&b/%plugin_short_command%: Shows all the admin commands" Footer: "&6-------------------------------------------------" -# In-game scoreboard messages. -# Please do not use more than 48 chars here! COLOR CODES INCLUDED. + +# +# In-Game scoreboard messages +# +# Please do not use more chars than the scoreboard can handle! +# Scoreboard supports up to 122 chars for 1.14+ and 48 chars for 1.13- (COLOR CODES INCLUDED.) +# Placeholders: +# https://wiki.plugily.xyz/REPLACEWITHPROJECTNAME/placeholders/language Scoreboard: - Title: "&4&lMurder Mystery" - Detective-Status-Normal: "&fDetective: &eAlive" - Detective-Died-No-Bow: "&cBow Dropped" - Detective-Died-Bow: "&aBow Not Dropped" + Title: "&a&l%plugin_name%" Roles: Detective: "&bDetective" Murderer: "&cMurderer" Innocent: "&eInnocent" - Dead: "&7Dead" + Dead: "Dead" + Detective: + Alive: "Detective &aAlive" + Bow: + Dropped: "%color_chat_issue%Bow Dropped" + Picked: "Bow Not Dropped" Content: - # Contents of scoreboard for innocents and detective - Playing: - - "&fRole: %ROLE%" + Waiting: - "" - - "&fInnocents Left: &e%INNOCENTS%" - - "&fTime Left: &e%FORMATTED_TIME%" + - "■ Players | %arena_players_size%" - "" - - "%DETECTIVE_STATUS%" + - "■ Minimum Players | %arena_min_players%" - "" - - "&fScore: &e%SCORE%" + - " www.plugily.xyz" + Starting: - "" - - "&ewww.plugily.xyz" - # Contents of scoreboard for murderer - Playing-Murderer: - - "&fRole: %ROLE%" + - "■ Starting In | %arena_time%" - "" - - "&fInnocents Left: &e%INNOCENTS%" - - "&fTime Left: &e%FORMATTED_TIME%" + - "■ Players | %arena_players_size%" - "" - - "%DETECTIVE_STATUS%" + - "■ Minimum Players | %arena_min_players%" - "" - - "&fKills: &e%KILLS%" + - " www.plugily.xyz" + # Contents of scoreboard while ingame + In-Game: - "" - - "&fScore: &e%SCORE%" + - "■ Role | %arena_player_role%" + - "&f" + - "■ Innocents | %arena_innocent_size%" + - "&f" + - "■ Time | %arena_time%" - "" - - "&ewww.plugily.xyz" - Waiting: - - "&fPlayers: &e%PLAYERS%" + - "■ %arena_detective_status%" - "" - - "&fMinimum Players: &e%MIN_PLAYERS%" + - "■ Score | %user_statistic_local_score%" - "" - - "&ewww.plugily.xyz" - Starting: - - "&fStarting In: &e%TIME%" + - " www.plugily.xyz" + In-Game-Murderer: + - "" + - "■ Role | %arena_player_role%" + - "&f" + - "■ Innocents | %arena_innocent_size%" + - "&f" + - "■ Time | %arena_time%" - "" - - "&fPlayers: &e%PLAYERS%" + - "■ %arena_detective_status%" - "" - - "&fMinimum Players: &e%MIN_PLAYERS%" + - "■ Kills | %user_statistic_local_kills%" - "" - - "&ewww.plugily.xyz" + - "■ Score | %user_statistic_local_score%" + - "" + - " www.plugily.xyz" + # Contents of scoreboard while state is ending + Ending: + - "&f" + - "&f" + - "&cGAME ENDED" + - "" + - "&f" + - "&f" + - "" + - " www.plugily.xyz" + # Contents of scoreboard while state is restarting + Restarting: + - "&f" + - "&f" + - "&cRESTARTING GAME" + - "" + - "&f" + - "&f" + - "" + - " www.plugily.xyz" -# Has usage only when bossbar is enabled in config.yml +# +# Bossbar messages +# +# Bossbar needs to be enabled on config.yml Bossbar: - Main-Title: "&a&lMurder Mystery &6- www.plugily.xyz" - Starting-In: "&f&lStarting in: &e&l%time%" - Waiting-For-Players: "&4&lWaiting for more players..." - In-Game-Info: "&e&lPlaying &f&lMURDER MYSTERY &e&lon &b&lPLUGILY.XYZ" - Game-Ended: "&c&lGame has ended! You were playing on &b&lPLUGILY.XYZ" + Title: "%plugin_name% - www.plugily.xyz" + Content: + Waiting: + - "Waiting for more players..." + Starting: + - "Starting in: %arena_time%" + In-Game: + - "Playing %plugin_name_uppercase% on PLUGILY.XYZ" + - "Check the plugin creator out on PLUGILY.XYZ" + - "Your role %arena_player_role%" + Ending: + - "Game has ended! You were playing on PLUGILY.XYZ" + Restarting: + - "Restarting the arena. You will be moved soon!" +# +# In-Game Messages +# In-Game: #Used in most game messages. - Plugin-Prefix: "&4[Murder Mystery] " - Already-Playing: "&cYou are already queued for a game! You can leave a game with /mm leave." - Join-No-Permission: "&cYou don't have &6%permission% &cpermission to join this arena!" - Full-Game-No-Permission: "&cYou don't have the permission to join full games!" - No-Slots-For-Premium: "&cThis game is already full of premium players! Sorry" - You-Are-Spectator: "&cYou're now a spectator! You can fly now!" - Only-Command-Ingame-Is-Leave: "&cYou have to leave the game first to perform commands. The only command that works is /mm leave!" - # Join cancelled via external plugin that uses MM api. - Join-Cancelled-Via-API: "&cYou can't join this game!" - Join-As-Party-Member: "&cYou joined %ARENANAME% because the party leader joined it!" - Arena-Not-Configured: "&cArena is not configured yet! Contact staff!" - Game-Chat-Format: "&7%player%: &f%message%" - Game-Death-Format: "&7[&4☠&7] &r" - Cooldown-Format: "&8&l[%progress%&8&l] &6%time% seconds" - Bow-Locator-Item-Name: "&6Bow locator" - Innocent-Locator-Item-Name: "&6Innocent locator" - Watch-Out-Title: "&cWatch out!" - Watch-Out-Subtitle: "&eThe Murderer can now find survivors easily" - Role-Pass: - Menu-Name: "Role pass menu" - Role: - Murderer: - Name: "Be murderer" - Lore: - - "Cost 1 murderer pass" - - "You got %amount%" - Detective: - Name: "Be detective" - Lore: - - "Cost 1 detective pass" - - "You got %amount%" - Fail: "You do not got enough passes for %role% role" - Success: "You will be %role% next round!" - Change: "You now got %amount% %role% passes!" + Plugin-Prefix: "(%plugin_name%)" + Game-Chat-Format: "[%user_statistic_level%] %player% | %message%" + You-Leveled-Up: "%plugin_prefix% You leveled up! You're now level %number%!" + Commands-Blocked: "%color_chat_issue%%plugin_prefix% You have to leave the game first to perform commands. The only command that works is /%plugin_short_command% leave!" + Join: + Already-Playing: "%color_chat_issue%%plugin_prefix% You are already queued for a game! You can leave a game with /%plugin_short_command% leave." + No-Permission: "%color_chat_issue%%plugin_prefix% You don't have %value% permission to join this arena!" + Full-Game: "%color_chat_issue%%plugin_prefix% You don't have the permission to join full games!" + No-Slots-For-Premium: "%color_chat_issue%%plugin_prefix% This game is already full of premium players! Sorry" + # Join cancelled via external plugin that uses the API of our plugin. + Cancelled-Via-API: "%color_chat_issue%%plugin_prefix% You can't join this game!" + As-Party-Member: "%color_chat_issue%%plugin_prefix% You joined %arena_name% because the party leader joined it!" + Arena-Not-Configured: "%color_chat_issue%%plugin_prefix% Arena is not configured yet! Contact staff!" + Title: "20,30,20;%arena_name%;%arena_players_size%/%arena_max_players%" + Death: + Tag: "&8Dead" + Screen: "%color_chat_issue%You died!" Spectator: - Spectator-Menu-Name: "Alive players list" - Target-Player-Role: "&7Role: %role%" - Target-Player-Health: "&cHealth: &7%health%" - Settings-Menu: - Inventory-Name: "&7Spectator settings" - Speed-Name: "&aSpeed" + Blocked: "%color_chat_issue%%plugin_prefix% Spectators are disabled for this arena" + You-Are-Spectator: "%plugin_prefix% You're now a spectator! You can fly now!" + Spectator-Menu-Name: "%color_chat_issue%Alive players list" + Target-Player-Health: "%color_chat_issue%Health: %number% | Role: %arena_player_role%" + Spectator-Warning: "%plugin_prefix% You are a spectator!" + Teleport: "%plugin_prefix% Teleported to %player%" + Menu: + Settings: + Status: + Enabled: "Enabled" + Disabled: "Disabled" + Changed-Speed: "Changed Speed to %number%" + Auto-Teleport: "%value% auto teleport" + Target-Player: + Action-Bar: "%number% blocks away | Target %player%" + Night-Vision: "%value% night vision" + First-Person-Mode: + Action-Bar: "&eSNEAK &cto leave! | Target %player%" + Title: "&eSNEAK &cto leave!" + Visibility: "%value% other spectator players" Messages: - Lobby-Messages: - Start-In: "&7The game starts in &b%TIME%&7 seconds!" - Waiting-For-Players: "&7Waiting for players... We need at least &b%MINPLAYERS%&7 players to start." - Enough-Players-To-Start: "&7We now have enough players. The game is starting soon!" - Game-Started: "&7The game has started! Survive till the end!" - Kicked-For-Premium-Slot: "&c%PLAYER% got removed from the game to make a place for premium players!" - You-Were-Kicked-For-Premium-Slot: "&cYou got kicked out of the game to make a place for a premium player!" - Role-Chances-Action-Bar: "&cMurderer Chance: %murderer_chance% &a- &bDetective Chance: %detective_chance%" - Not-Enough-Space-For-Party: "&cYour party is bigger than free places on the arena %ARENANAME%" - Join: "&b%PLAYER%&7 joined the game (%PLAYERSIZE%/%MAXPLAYERS%)!" - Leave: "&b%PLAYER% &7left the game (%PLAYERSIZE%/%MAXPLAYERS%)!" - Death: "&b%PLAYER% &7died!" - Seconds-Left-Title: "&c%time% &eseconds left!" - Seconds-Left-Subtitle: "&eAfter %time%s the Murderer will lose" - Role-Set: - Murderer-Title: "&cROLE: MURDERER" - Murderer-Subtitle: "&eKill all players!" - Detective-Title: "&bROLE: DETECTIVE" - Detective-Subtitle: "&eFind and kill the murderer!" - Innocent-Title: "&eROLE: INNOCENT" - Innocent-Subtitle: "&eStay alive as long as possible!" - Bonus-Score: "&e+%score% score (%action%)" - Score-Actions: - Kill-Player: "for killing player" - Kill-Murderer: "for killing murderer" - Gold-Pickup: "for gold pickup" - Survive: "for surviving 30 seconds" - #for innocents - Survive-Till-End: "for surviving till end" - #for murderer or detective - Win-Game: "for winning the game" - Detective-Reward: "for %amount% innocents survived" - Innocent-Kill: "for killing innocent" - Picked-Up-Gold: "&ePicked up gold!" - Previous-Role-Left-Title: "&cPrevious %role% has left!" - Previous-Role-Left-Subtitle: "&cSelecting new %role%!" - Corpse-Last-Words: "&7%player%&e's last words:" - Murderer-Get-Sword: "&eThe Murderer gets their sword in &c%time% &eseconds!" - Special-Blocks: - Cauldron-Drink-Potion: "&cPlease drink your current potion!" - Not-Enough-Gold: "&cYou need %amount% gold for this!" - Cauldron-Hologram: "&fMystery Potion - 1 &eGold" - Praise-Hologram: "&eClick to give gift;&ePull lever to pray" - Prayed-Message: "&aYou prayed to the developer! Hope he will hear that!" - No-Money-No-Pray: "&cPay to pray!" - Praises: - Message: - - "" - - "&7Developer hears your prayer." - - "%feeling%" - - "%praise%" - Feelings: - Blessed: "&aYou feel blessed." - Cursed: "&cYou feel cursed." - Gifts: - Detective-Revelation: "&aYou know that &bCurrent detective &ais %detective%" - Gold-Rush: "&aYou received power of ancients. For each gold you collect, you will receive 3 gold now." - Single-Compensation: "&aDeveloper is proud of you! He rewarded you with 5 gold ingots!" - Bow-Time: "&aYou received bow from pleased developer!" - Curses: - Slowness-Curse: "&cYour legs are much heavier than before." - Blindness-Curse: "&cYour eyes can't see that well anymore." - Gold-Ban: "&cDeveloper cursed you with gold ban! You cannot longer pickup any gold!" - Incoming-Death: "&cYou feel overpowering force of death. You know that you'll be dead in a minute!" - Bow-Messages: - Bow-Dropped-Title: "&6The Bow has been dropped!" - Bow-Dropped-Subtitle: "&eFind the Bow for a chance to kill the Murderer." - Pickup-Bow-Message: "&eA player has picked up the Bow!" - Bow-Shot-For-Gold: "&a+1 Bow Shot!" - Bow-Shot-Subtitle: "&eYou collected 10 gold and got an arrow!" - Last-Words: - 'default': - Message: "&fPlease respawn :(" - 'meme': - Message: "&fDespacito 2 is confirmed by God" - Permission: "murdermystery.lastwords.meme" - 'rage': - Message: "&fWHY YOU KILLED ME?!!?" - Permission: "murdermystery.lastwords.rage" - 'pro': - Message: "&fIt was lagging..." - Permission: "murdermystery.lastwords.pro" - 'hacker': - Message: "Turn off your hacks..." - Permission: "murdermystery.lastwords.hacker" - Game-End-Messages: - Titles: - Win: "&aYOU WIN!" - Lose: "&cYOU LOSE!" - Died: "&cYOU DIED!" - Subtitles: - Murderer-Stopped: "&6The Murderer has been stopped!" - Murderer-Kill-Everyone: "&6The Murderer has killed everyone." - Murderer-Killed-You: "&eThe murderer killed you!" - Player-Killed-You: "&cA player killed you with a Bow!" - Killed-Innocent: "&eYou killed an innocent player!" - Winners: - Players: "&ePLAYERS" - Murderer: "&cMURDERER" - Nobody: "&7Nobody" - Summary-Message: - - "&a&m------------------------------------------------------------------" - - "&f&lMurder Mystery" + Join: "%plugin_prefix% %player% joined the game (%arena_players_size%/%arena_max_players%)!" + Leave: "%plugin_prefix% %player% left the game (%arena_players_size%/%arena_max_players%)!" + Death: "%plugin_prefix% %player% died!" + Lobby: + Start-In: "%plugin_prefix% The game starts in %arena_time% seconds!" + Waiting-For-Players: "%plugin_prefix% Waiting for players... We need at least %arena_min_players% players to start." + Enough-Players-To-Start: "%plugin_prefix% We now have enough players. The game is starting soon!" + Reduced-Time: "%plugin_prefix% The time got reduced to %number% seconds" + Max-Players: "%plugin_prefix% We reached max players for this round. Let's shorten the time!" + Game-Started: "%plugin_prefix% The game has started!" + Kicked-For-Premium-Slot: "%color_chat_issue%%plugin_prefix% %player% got removed from the game to make a place for premium players!" + You-Were-Kicked-For-Premium-Slot: "%color_chat_issue%%plugin_prefix% You got kicked out of the game to make a place for a premium player!" + Not-Enough-Space-For-Party: "%color_chat_issue%%plugin_prefix% Your party is bigger than free places on the arena %arena_name%" + Game-End: + Summary: + - "&a&m--------------------------------------------------" + - "%plugin_name%" - "" - - "&f&lWINNER: %winner%" + - "%arena_summary%" + - "%arena_summary_player%" - "" - - "&7Detective: %detective%" - - "&7Murderer: %murderer% (%murderer_kills%)" - - "&7Hero: %hero%" + - "&7Detective: %arena_detective_list%" + - "&7Murderer: %arena_murderer_list% (%arena_murderer_kills%)" + - "&7Hero: %arena_hero%" - "" - - "&a&m------------------------------------------------------------------" - Admin-Messages: - Set-Starting-In-To-0: "&bAn admin set waiting time to 0. The game starts now!" + - "&a&m--------------------------------------------------" + Placeholders: + Win: "&aYou won the game" + Lose: "%color_chat_issue%You lost the game" + Players: "&cThere are not enough players anymore. Arena got force stopped!" + Murderer: + Stopped: "The Murderer has been stopped!" + Killed: + You: "The murderer killed you!" + All: "The Murderer has killed everyone." + Innocent: + Killed: + You: "A player killed you with a Bow!" + Wrongly: "You killed an innocent player!" + Nobody: "Nobody" + Admin: + Set-Starting-In-To-0: "%plugin_prefix% An admin set waiting time to 0. The game starts now!" + Arena: + Chances: + Action-Bar: "&cMurderer Chance: %arena_murderer_chance% &a- &bDetective Chance: %arena_detective_chance%" + Cooldown: "&8&l[%value%&8&l] &6%number% seconds" + Locator: + Bow: "Bow locator" + Innocent: "Innocent locator" + Watch-Out: "5,20,5;Watch out!;The Murderer can now find survivors easily" + Pass: + Name: "Role pass menu" + Role: + Murderer: + Name: "&cBe murderer" + Lore: + - "Cost 1 murderer pass" + - "You got %number%" + Detective: + Name: "&bBe detective" + Lore: + - "Cost 1 detective pass" + - "You got %number%" + Fail: "%plugin_prefix% You do not got enough passes for %value% role" + Success: "%plugin_prefix% You will be %value% next round!" + Change: "%plugin_prefix% You now got %number% %value% passes!" + Playing: + Time-Left: "5,20,5;%arena_time% seconds left!;After %arena_time%s the Murderer will lose" + Role: + Change: "5,20,5;Previous %arena_player_role% has left!" + Murderer: "5,20,5;ROLE | MURDERER; Kill all players!" + Detective: "5,20,5;ROLE | DETECTIVE;Find and kill the murderer!" + Innocent: "5,20,5;ROLE | INNOCENT;Stay alive as long as possible!" + Score: + Bonus: "+%number% score (%value%)" + Gold: "Picked up gold!" + Action: + Kill: + Player: "for killing players" + Murderer: "for killing murderer" + Innocent: "for killing innocent" + Pickup: + Gold: "for gold pickup" + Surviving: + Time: "for surviving 30 seconds" + End: "for surviving till end" + Win: "for winning the game" + Detective: "for %number% innocents survived" + Sword: + Soon: "The Murderer gets their sword in %number% seconds!" + Special-Blocks: + Cauldron: + Potion: "Please drink your current potion!" + Hologram: "Mystery Potion - &e1 Gold" + Not-Enough-Gold: "You need %number% gold for this!" + Pray: + Hologram: "Click to give gift;Pull lever to pray" + Chat: "You prayed to the developer! Hope he will hear that!" + Pay: "%color_chat_issue%Pay to pray!" + Praise: + Heard: + - "" + - "&7Developer hears your prayer." + - "%feeling%" + - "%praise%" + Feeling: + Blessed: "&aYou feel blessed." + Cursed: "&cYou feel cursed." + Gifts: + Detective-Revelation: "&aYou know that &bCurrent detective &ais %detective%" + Gold-Rush: "&aYou received power of ancients. For each gold you collect, you will receive 3 gold now." + Single-Compensation: "&aDeveloper is proud of you! He rewarded you with 5 gold ingots!" + Bow: "&aYou received bow from pleased developer!" + Curses: + Slowness: "%color_chat_issue%Your legs are much heavier than before." + Blindness: "%color_chat_issue%Your eyes can't see that well anymore." + Gold: "%color_chat_issue%Developer cursed you with gold ban! You cannot longer pickup any gold!" + Death: "%color_chat_issue%You feel overpowering force of death. You know that you'll be dead in a minute!" + Bow: + Dropped: "5,20,5;The Bow has been dropped!;Find the Bow for a chance to kill the Murderer." + Pickup: "A player has picked up the Bow!" + Shot: + Gold: "&a+1 Bow Shot!" + Title: "5,20,5;;You collected 10 gold and got an arrow!" + + + + + + +# +# Sign messages +# Signs: - Please-Type-Arena-Name: "&cPlease type arena name in second line!" - Arena-Doesnt-Exists: "&cArena with that name doesn't exists!" - Sign-Created: "&aSign created successfully!" - Sign-Removed: "&aSign successfully removed!" - Game-States: - Inactive: "&lInactive..." - In-Game: "&lIn-game" - Starting: "&e&lStarting" - Full-Game: "&4&lFULL" - Ending: "&lEnding" - Restarting: "&c&lRestarting" + Please-Type-Arena-Name: "%color_chat_issue%%plugin_prefix% Please type arena name in second line!" + Arena-Doesnt-Exists: "%color_chat_issue%%plugin_prefix% Arena with that name doesn't exists!" + Created: "%plugin_prefix% Sign created successfully!" + Removed: "%plugin_prefix% Sign successfully removed!" Lines: - - "&4&lMurder Mystery" - - "%state%" - - "%mapname%" - - "&5[%playersize%/%maxplayers%]" + - "%plugin_prefix%" + - "%arena_state_placeholder%" + - "%arena_name%" + - "[%arena_players_size%/%arena_max_players%]" + +# +# Arena Selector messages +# Arena-Selector: - Inv-Title: "Arena selector" + Inventory-Title: "%plugin_short_command% ▸ Arena selector" Item: - Name: "&f%mapname%" + Name: "%arena_name%" Lore: - - "&4Murder Mystery &f- &e%mapname%" + - "%plugin_name% - %arena_name%" - " " - " " - - " &fOnline: %playersize%/%maxplayers%" - - " &fState: %state%" + - " Online: %arena_players_size%/%arena_max_players%" + - " State: %arena_state_placeholder%" - " " - " " - - "&eClick to join this arena" - -Leaderheads: - #top command from leaderheads ex. mmtopkills - Top-Command-Name: "mmtop%stat%" - Top-Command-Inv-Title: "&bTop users" - Leaderboard-Value: - Kills: "&e{amount} kills" - Deaths: "&e{amount} deaths" - Games-Played: "&e{amount} games played" - Highest-Score: "&e{amount} highest score" - Wins: "&e{amount} wins" - Loses: "&e{amount} loses" + - "&aClick to join this arena" +# +# Validator messages +# Validator: - Invalid-Arena-Configuration: "[Murder Mystery] Arena %arena% has invalid configuration! Missing node: %error%" - Instance-Started: "[Murder Mystery] Arena %arena% instance successfully started!" - No-Instances-Created: "[Murder Mystery] There are no arena instances created in configuration!" + Invalid-Arena-Configuration: "Arena %arena_name% has invalid configuration! Missing node: %value%" + Instance-Started: "Arena %arena_name% instance successfully started!" + No-Instances-Created: "There are no arena instances created in configuration!" + +# +# Placeholder messages inside plugin +# Placeholders: Game-States: Waiting: "&lWaiting for players..." Starting: "&e&lStarting" + Full-Game: "&4&lFULL" In-Game: "&lIn-game" Ending: "&lEnding" Restarting: "&c&lRestarting" + Motd: + Waiting: "&lYou can join this game..." + Starting: "&e&lStarting" + Full-Game: "&4&lFULL | Use another Server" + In-Game: "&lIn-game | Click to spectate" + Ending: "&lEnding | Server is closing" + Restarting: "&c&lRestarting" + + +# +# Leaderboard messages +# +# Hologram function need to be enabled on config.yml +Leaderboard: + Type: + Hologram: + Header: "&6&lTop %number% in %value%" + Format: "&e%number%. %player% (%value%)" + Empty-Format: "&e%number%. Empty (0)" + Chat: + Header: "&8+-------+ &a&lYOUR STATS &8+-------+" + Header-Other: "&8+---------+ &aSTATS FOR &b%player% &8+---------+" + Footer: "&8+-----------------------------+" + Format: "%value% ▸ &a%number%" + Top: + Type-Name: "%color_chat_issue%Please type statistic name to view!" + Header: "&8&m+----------------+ [&6 Top 10 &8&m] +----------------+" + Format: "&e#%number% %player% - %value% %user_statistic%" + Statistics: + Wins: "Wins ▸ %number%" + Loses: "Loses ▸ %number%" + Games-Played: "Games Played ▸ %number%" + Level: "Level ▸ %number%" + Exp: "Experience ▸ %number%" + Next-Level-Exp: "Exp to Level Up ▸ %number%" + Kills: "Kills ▸ %number%" + Deaths: "Deaths ▸ %number%" + Highest-Score: "Highest score ▸ %number%" + Murderer-Pass: "Murderer passes ▸ %number%" + Detective-Pass: "Detective passes ▸ %number%" + Murderer-Contribution: "Murderer contribution ▸ %number%" + Detective-Contribution: "Detective contribution ▸ %number%" + Invalid-Name: "%color_chat_issue%Name of statistic is invalid! Type: %value%" + Unknown-Player: "%color_chat_issue%Unknown Player" + # Don't edit it. But who's stopping you? It's your server! # Really, don't edit ;p -File-Version-Do-Not-Edit: 8 +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 diff --git a/src/main/resources/lastwords.yml b/src/main/resources/lastwords.yml new file mode 100644 index 00000000..0c1bc870 --- /dev/null +++ b/src/main/resources/lastwords.yml @@ -0,0 +1,18 @@ +Last-Words: + Hologram: + Title: "%player%'s last words:" + Content: + 'default': + Message: "&fPlease respawn :(" + 'meme': + Message: "&fDespacito 2 is confirmed by God" + Permission: "murdermystery.lastwords.meme" + 'rage': + Message: "&fWHY YOU KILLED ME?!!?" + Permission: "murdermystery.lastwords.rage" + 'pro': + Message: "&fIt was lagging..." + Permission: "murdermystery.lastwords.pro" + 'hacker': + Message: "Turn off your hacks..." + Permission: "murdermystery.lastwords.hacker" \ No newline at end of file diff --git a/src/main/resources/leaderboards.yml b/src/main/resources/leaderboards.yml new file mode 100644 index 00000000..b08570ed --- /dev/null +++ b/src/main/resources/leaderboards.yml @@ -0,0 +1,6 @@ +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/locales/language_default.yml b/src/main/resources/locales/language_default.yml index 3f0c4602..c8a798a7 100644 --- a/src/main/resources/locales/language_default.yml +++ b/src/main/resources/locales/language_default.yml @@ -1,333 +1,465 @@ -# Leave this file as it is! +###############################[IMPORTANT]############################### +# +# Leave this file as it is! It is kinda an internal backup file! # ### !!!Do not change anything here!!! # ### THIS FILE AUTOMATICALLY REGENERATES ON SERVER RESTART # -# Needed as it can be possible that the api is not working +# Needed when the external api isn't working +# +###############################[IMPORTANT]############################### +# You can translate MurderMystery messages here. +# Color codes (&) supported. +# +# Use \n to make new line +# Some messages like item +# descriptions don't support new lines +# they are wrapped every 40 characters automatically +# +# Some messages support their own placeholders +# like %player%, %kit% etc. + +# +# Color scheme +# +Color: + Placeholder: + Value: "&4" + Number: "&4" + Player: "&b" + Other: "&4" + Chat: + Issue: "&c" + Messages: "&7" + Special-Char: + Contains: "[,],(,),{,},■,/,|,▸" + Before: "&8" + + +# +# Command messages +# Commands: - Did-You-Mean: "&6Did you mean &e/%command%&6?" - Teleported-To-The-Lobby: "Teleported to the lobby!" - Removed-Game-Instance: "&cSuccessfully removed game instance!" - No-Arena-Like-That: "&cNo arena with that ID!" - Look-Sign: "&cYou have to look at a sign to perform this command!" - Type-Arena-Name: "&cPlease type arena ID!" - No-Free-Arenas: "&cThere are no free arenas!" - Statistics: - Type-Name: "&cPlease type statistic name to view!" - Invalid-Name: "&cName of statistic is invalid! Type: kills, deaths, games_played, wins, loses, highest_score" - Header: "&8&m-------------------[&6 Top 10 &8&m]-------------------" - Format: "&e#%position% %name% - %value% &7%statistic%" - Only-By-Player: "&cYou can execute this command only as player!" - Not-Playing: "&cYou must play to execute this command!" - No-Permission: "&cYou don't have permission to use this command!" - Admin-Commands: - Teleported-To-Player: "&aTeleported to player!" - Player-Not-Found: "&cPlayer not found!" - Success-Reload: "&aArenas reloaded!" - List-Command: - Header: "&aMurder Mystery &6arenas:" - Format: "&a%arena% &e%status% &6%players%/%maxplayers%" - No-Arenas: "&cThere are no game instances!" - Stats-Command: - Header: "&l-----YOUR STATS-----" - Header-Other: "&l-----STATS FOR %player%-----" - Footer: "&l--------------------" - Kills: "&aKills: &e" - Deaths: "&aDeaths: &e" - Wins: "&aWins: &e" - Loses: "&aLoses: &e" - Highest-Score: "&aHighest score: &e" - Games-Played: "&aGames played: &e" - Main-Command: - Header: "&6----------------{Murder Mystery commands}----------" - Description: "&aGame commands:\n - &b/mm stats: &7Shows your stats!\n - &b/mm leave: &7Quits current arena!\n - &b/mm join : &7Joins specified arena!\n - &b/mm top : &7Shows top 10 players!\n - &b/mm randomjoin: &7Join random arena!" - Admin-Bonus-Description: "\n&b/mma: &7Shows all the admin commands" + Did-You-Mean: "%plugin_prefix% Did you mean /%value%?" + Command-Executed: "%plugin_prefix% Command successfully executed!" + Teleported-To-Lobby: "%plugin_prefix% Teleported to lobby!" + Removed-Game-Instance: "%color_chat_issue%%plugin_prefix% Successfully removed game instance!" + No-Arena-Like-That: "%color_chat_issue%%plugin_prefix% No arena with that ID!" + Look-At-Sign: "%color_chat_issue%%plugin_prefix% You have to look at a sign to perform this command!" + Type-Arena-Name: "%color_chat_issue%%plugin_prefix% Please type arena ID!" + Hold-Any-Item: "%color_chat_issue%%plugin_prefix% You must hold any item!" + No-Free-Arenas: "%color_chat_issue%%plugin_prefix% There are no free arenas!" + Only-By-Player: "%color_chat_issue%%plugin_prefix% You can execute this command only as player!" + Not-Playing: "%color_chat_issue%%plugin_prefix% You must play to execute this command!" + No-Permission: "%color_chat_issue%%plugin_prefix% You don't have permission to use this command!" + Player-Not-Found: "%color_chat_issue%%plugin_prefix% Target player %player% doesn't exist!" + Invalid-Location-Teleport: "%color_chat_issue%%plugin_prefix% Location to teleport is invalid!" + Wrong-Usage: "%color_chat_issue%%plugin_prefix% Wrong usage. Do %value%" + Admin: + Adjust-Statistic: "%plugin_prefix% Statistic %value% of %player% is now %number%!" + Reload-Success: "%plugin_prefix% Arenas reloaded!" + List: + Header: "%plugin_name% arenas: Name State Players" + Format: "%arena_name% %arena_state_placeholder% %arena_players_size%/%arena_max_players%" + No-Arenas: "%color_chat_issue%%plugin_prefix% There are no game instances!" + Spychat: + Toggled: "%plugin_prefix% Game spy chat toggled to %value%" + Main: + Header: "&6----------------{%plugin_name% commands}----------" + Description: + - "&aGame commands:" + - "&b/%plugin_short_command% stats: Shows your stats!" + - "&b/%plugin_short_command% leave: Quits current arena!" + - "&b/%plugin_short_command% join : Joins specified arena!" + - "&b/%plugin_short_command% top : Shows top 10 players!" + - "&b/%plugin_short_command% randomjoin: Join random arena!" + Admin-Bonus-Description: "&b/%plugin_short_command%: Shows all the admin commands" Footer: "&6-------------------------------------------------" -# In-game scoreboard messages. -# Please do not use more than 48 chars here! COLOR CODES INCLUDED. + +# +# In-Game scoreboard messages +# +# Please do not use more chars than the scoreboard can handle! +# Scoreboard supports up to 122 chars for 1.14+ and 48 chars for 1.13- (COLOR CODES INCLUDED.) +# Placeholders: +# https://wiki.plugily.xyz/REPLACEWITHPROJECTNAME/placeholders/language Scoreboard: - Title: "&4&lMurder Mystery" - Detective-Status-Normal: "&fDetective: &eAlive" - Detective-Died-No-Bow: "&cBow Dropped" - Detective-Died-Bow: "&aBow Not Dropped" + Title: "&a&l%plugin_name%" Roles: Detective: "&bDetective" Murderer: "&cMurderer" Innocent: "&eInnocent" - Dead: "&7Dead" + Dead: "Dead" + Detective: + Alive: "Detective &aAlive" + Bow: + Dropped: "%color_chat_issue%Bow Dropped" + Picked: "Bow Not Dropped" Content: - # Contents of scoreboard for innocents and detective - Playing: - - "&fRole: %ROLE%" + Waiting: - "" - - "&fInnocents Left: &e%INNOCENTS%" - - "&fTime Left: &e%FORMATTED_TIME%" + - "■ Players | %arena_players_size%" - "" - - "%DETECTIVE_STATUS%" + - "■ Minimum Players | %arena_min_players%" - "" - - "&fScore: &e%SCORE%" + - " www.plugily.xyz" + Starting: - "" - - "&ewww.plugily.xyz" - # Contents of scoreboard for murderer - Playing-Murderer: - - "&fRole: %ROLE%" + - "■ Starting In | %arena_time%" - "" - - "&fInnocents Left: &e%INNOCENTS%" - - "&fTime Left: &e%FORMATTED_TIME%" + - "■ Players | %arena_players_size%" - "" - - "%DETECTIVE_STATUS%" + - "■ Minimum Players | %arena_min_players%" - "" - - "&fKills: &e%KILLS%" + - " www.plugily.xyz" + # Contents of scoreboard while ingame + In-Game: - "" - - "&fScore: &e%SCORE%" + - "■ Role | %arena_player_role%" + - "&f" + - "■ Innocents | %arena_innocent_size%" + - "&f" + - "■ Time | %arena_time%" - "" - - "&ewww.plugily.xyz" - Waiting: - - "&fPlayers: &e%PLAYERS%" + - "■ %arena_detective_status%" - "" - - "&fMinimum Players: &e%MIN_PLAYERS%" + - "■ Score | %user_statistic_local_score%" - "" - - "&ewww.plugily.xyz" - Starting: - - "&fStarting In: &e%TIME%" + - " www.plugily.xyz" + In-Game-Murderer: + - "" + - "■ Role | %arena_player_role%" + - "&f" + - "■ Innocents | %arena_innocent_size%" + - "&f" + - "■ Time | %arena_time%" + - "" + - "■ %arena_detective_status%" + - "" + - "■ Kills | %user_statistic_local_kills%" + - "" + - "■ Score | %user_statistic_local_score%" + - "" + - " www.plugily.xyz" + # Contents of scoreboard while state is ending + Ending: + - "&f" + - "&f" + - "&cGAME ENDED" + - "" + - "&f" + - "&f" - "" - - "&fPlayers: &e%PLAYERS%" + - " www.plugily.xyz" + # Contents of scoreboard while state is restarting + Restarting: + - "&f" + - "&f" + - "&cRESTARTING GAME" - "" - - "&fMinimum Players: &e%MIN_PLAYERS%" + - "&f" + - "&f" - "" - - "&ewww.plugily.xyz" + - " www.plugily.xyz" -# Has usage only when bossbar is enabled in config.yml +# +# Bossbar messages +# +# Bossbar needs to be enabled on config.yml Bossbar: - Main-Title: "&a&lMurder Mystery &6- www.plugily.xyz" - Starting-In: "&f&lStarting in: &e&l%time%" - Waiting-For-Players: "&4&lWaiting for more players..." - In-Game-Info: "&e&lPlaying &f&lMURDER MYSTERY &e&lon &b&lPLUGILY.XYZ" - Game-Ended: "&c&lGame has ended! You were playing on &b&lPLUGILY.XYZ" + Title: "%plugin_name% - www.plugily.xyz" + Content: + Waiting: + - "Waiting for more players..." + Starting: + - "Starting in: %arena_time%" + In-Game: + - "Playing %plugin_name_uppercase% on PLUGILY.XYZ" + - "Check the plugin creator out on PLUGILY.XYZ" + - "Your role %arena_player_role%" + Ending: + - "Game has ended! You were playing on PLUGILY.XYZ" + Restarting: + - "Restarting the arena. You will be moved soon!" +# +# In-Game Messages +# In-Game: #Used in most game messages. - Plugin-Prefix: "&4[Murder Mystery] " - Already-Playing: "&cYou are already queued for a game! You can leave a game with /mm leave." - Join-No-Permission: "&cYou don't have &6%permission% &cpermission to join this arena!" - Full-Game-No-Permission: "&cYou don't have the permission to join full games!" - No-Slots-For-Premium: "&cThis game is already full of premium players! Sorry" - You-Are-Spectator: "&cYou're now a spectator! You can fly now!" - Only-Command-Ingame-Is-Leave: "&cYou have to leave the game first to perform commands. The only command that works is /mm leave!" - # Join cancelled via external plugin that uses MM api. - Join-Cancelled-Via-API: "&cYou can't join this game!" - Join-As-Party-Member: "&cYou joined %ARENANAME% because the party leader joined it!" - Arena-Not-Configured: "&cArena is not configured yet! Contact staff!" - Game-Chat-Format: "&7%player%: &f%message%" - Game-Death-Format: "&7[&4☠&7] &r" - Cooldown-Format: "&8&l[%progress%&8&l] &6%time% seconds" - Bow-Locator-Item-Name: "&6Bow locator" - Innocent-Locator-Item-Name: "&6Innocent locator" - Watch-Out-Title: "&cWatch out!" - Watch-Out-Subtitle: "&eThe Murderer can now find survivors easily" - Role-Pass: - Menu-Name: "Role pass menu" - Role: - Murderer: - Name: "Be murderer" - Lore: - - "Cost 1 murderer pass" - - "You got %amount%" - Detective: - Name: "Be detective" - Lore: - - "Cost 1 detective pass" - - "You got %amount%" - Fail: "You do not got enough passes for %role% role" - Success: "You will be %role% next round!" - Change: "You now got %amount% %role% passes!" + Plugin-Prefix: "(%plugin_name%)" + Game-Chat-Format: "[%user_statistic_level%] %player% | %message%" + You-Leveled-Up: "%plugin_prefix% You leveled up! You're now level %number%!" + Commands-Blocked: "%color_chat_issue%%plugin_prefix% You have to leave the game first to perform commands. The only command that works is /%plugin_short_command% leave!" + Join: + Already-Playing: "%color_chat_issue%%plugin_prefix% You are already queued for a game! You can leave a game with /%plugin_short_command% leave." + No-Permission: "%color_chat_issue%%plugin_prefix% You don't have %value% permission to join this arena!" + Full-Game: "%color_chat_issue%%plugin_prefix% You don't have the permission to join full games!" + No-Slots-For-Premium: "%color_chat_issue%%plugin_prefix% This game is already full of premium players! Sorry" + # Join cancelled via external plugin that uses the API of our plugin. + Cancelled-Via-API: "%color_chat_issue%%plugin_prefix% You can't join this game!" + As-Party-Member: "%color_chat_issue%%plugin_prefix% You joined %arena_name% because the party leader joined it!" + Arena-Not-Configured: "%color_chat_issue%%plugin_prefix% Arena is not configured yet! Contact staff!" + Title: "20,30,20;%arena_name%;%arena_players_size%/%arena_max_players%" + Death: + Tag: "&8Dead" + Screen: "%color_chat_issue%You died!" Spectator: - Spectator-Menu-Name: "Alive players list" - Target-Player-Role: "&7Role: %role%" - Target-Player-Health: "&cHealth: &7%health%" - Settings-Menu: - Inventory-Name: "&7Spectator settings" - Speed-Name: "&aSpeed" + Blocked: "%color_chat_issue%%plugin_prefix% Spectators are disabled for this arena" + You-Are-Spectator: "%plugin_prefix% You're now a spectator! You can fly now!" + Spectator-Menu-Name: "%color_chat_issue%Alive players list" + Target-Player-Health: "%color_chat_issue%Health: %number% | Role: %arena_player_role%" + Spectator-Warning: "%plugin_prefix% You are a spectator!" + Teleport: "%plugin_prefix% Teleported to %player%" + Menu: + Settings: + Status: + Enabled: "Enabled" + Disabled: "Disabled" + Changed-Speed: "Changed Speed to %number%" + Auto-Teleport: "%value% auto teleport" + Target-Player: + Action-Bar: "%number% blocks away | Target %player%" + Night-Vision: "%value% night vision" + First-Person-Mode: + Action-Bar: "&eSNEAK &cto leave! | Target %player%" + Title: "&eSNEAK &cto leave!" + Visibility: "%value% other spectator players" Messages: - Lobby-Messages: - Start-In: "&7The game starts in &b%TIME%&7 seconds!" - Waiting-For-Players: "&7Waiting for players... We need at least &b%MINPLAYERS%&7 players to start." - Enough-Players-To-Start: "&7We now have enough players. The game is starting soon!" - Game-Started: "&7The game has started! Survive till the end!" - Kicked-For-Premium-Slot: "&c%PLAYER% got removed from the game to make a place for premium players!" - You-Were-Kicked-For-Premium-Slot: "&cYou got kicked out of the game to make a place for a premium player!" - Role-Chances-Action-Bar: "&cMurderer Chance: %murderer_chance% &a- &bDetective Chance: %detective_chance%" - Not-Enough-Space-For-Party: "&cYour party is bigger than free places on the arena %ARENANAME%" - Join: "&b%PLAYER%&7 joined the game (%PLAYERSIZE%/%MAXPLAYERS%)!" - Leave: "&b%PLAYER% &7left the game (%PLAYERSIZE%/%MAXPLAYERS%)!" - Death: "&b%PLAYER% &7died!" - Seconds-Left-Title: "&c%time% &eseconds left!" - Seconds-Left-Subtitle: "&eAfter %time%s the Murderer will lose" - Role-Set: - Murderer-Title: "&cROLE: MURDERER" - Murderer-Subtitle: "&eKill all players!" - Detective-Title: "&bROLE: DETECTIVE" - Detective-Subtitle: "&eFind and kill the murderer!" - Innocent-Title: "&eROLE: INNOCENT" - Innocent-Subtitle: "&eStay alive as long as possible!" - Bonus-Score: "&e+%score% score (%action%)" - Score-Actions: - Kill-Player: "for killing player" - Kill-Murderer: "for killing murderer" - Gold-Pickup: "for gold pickup" - Survive: "for surviving 30 seconds" - #for innocents - Survive-Till-End: "for surviving till end" - #for murderer or detective - Win-Game: "for winning the game" - Detective-Reward: "for %amount% innocents survived" - Innocent-Kill: "for killing innocent" - Picked-Up-Gold: "&ePicked up gold!" - Previous-Role-Left-Title: "&cPrevious %role% has left!" - Previous-Role-Left-Subtitle: "&cSelecting new %role%!" - Corpse-Last-Words: "&7%player%&e's last words:" - Murderer-Get-Sword: "&eThe Murderer gets their sword in &c%time% &eseconds!" - Special-Blocks: - Cauldron-Drink-Potion: "&cPlease drink your current potion!" - Not-Enough-Gold: "&cYou need %amount% gold for this!" - Cauldron-Hologram: "&fMystery Potion - 1 &eGold" - Praise-Hologram: "&eClick to give gift;&ePull lever to pray" - Prayed-Message: "&aYou prayed to the developer! Hope he will hear that!" - No-Money-No-Pray: "&cPay to pray!" - Praises: - Message: - - "" - - "&7Developer hears your prayer." - - "%feeling%" - - "%praise%" - Feelings: - Blessed: "&aYou feel blessed." - Cursed: "&cYou feel cursed." - Gifts: - Detective-Revelation: "&aYou know that &bCurrent detective &ais %detective%" - Gold-Rush: "&aYou received power of ancients. For each gold you collect, you will receive 3 gold now." - Single-Compensation: "&aDeveloper is proud of you! He rewarded you with 5 gold ingots!" - Bow-Time: "&aYou received bow from pleased developer!" - Curses: - Slowness-Curse: "&cYour legs are much heavier than before." - Blindness-Curse: "&cYour eyes can't see that well anymore." - Gold-Ban: "&cDeveloper cursed you with gold ban! You cannot longer pickup any gold!" - Incoming-Death: "&cYou feel overpowering force of death. You know that you'll be dead in a minute!" - Bow-Messages: - Bow-Dropped-Title: "&6The Bow has been dropped!" - Bow-Dropped-Subtitle: "&eFind the Bow for a chance to kill the Murderer." - Pickup-Bow-Message: "&eA player has picked up the Bow!" - Bow-Shot-For-Gold: "&a+1 Bow Shot!" - Bow-Shot-Subtitle: "&eYou collected 10 gold and got an arrow!" - Last-Words: - 'default': - Message: "&fPlease respawn :(" - 'meme': - Message: "&fDespacito 2 is confirmed by God" - Permission: "murdermystery.lastwords.meme" - 'rage': - Message: "&fWHY YOU KILLED ME?!!?" - Permission: "murdermystery.lastwords.rage" - 'pro': - Message: "&fIt was lagging..." - Permission: "murdermystery.lastwords.pro" - 'hacker': - Message: "Turn off your hacks..." - Permission: "murdermystery.lastwords.hacker" - - Game-End-Messages: - Titles: - Win: "&aYOU WIN!" - Lose: "&cYOU LOSE!" - Died: "&cYOU DIED!" - Subtitles: - Murderer-Stopped: "&6The Murderer has been stopped!" - Murderer-Kill-Everyone: "&6The Murderer has killed everyone." - Murderer-Killed-You: "&eThe murderer killed you!" - Player-Killed-You: "&cA player killed you with a Bow!" - Killed-Innocent: "&eYou killed an innocent player!" - Winners: - Players: "&ePLAYERS" - Murderer: "&cMURDERER" - Nobody: "&7Nobody" - Summary-Message: - - "&a&m------------------------------------------------------------------" - - "&f&lMurder Mystery" + Join: "%plugin_prefix% %player% joined the game (%arena_players_size%/%arena_max_players%)!" + Leave: "%plugin_prefix% %player% left the game (%arena_players_size%/%arena_max_players%)!" + Death: "%plugin_prefix% %player% died!" + Lobby: + Start-In: "%plugin_prefix% The game starts in %arena_time% seconds!" + Waiting-For-Players: "%plugin_prefix% Waiting for players... We need at least %arena_min_players% players to start." + Enough-Players-To-Start: "%plugin_prefix% We now have enough players. The game is starting soon!" + Reduced-Time: "%plugin_prefix% The time got reduced to %number% seconds" + Max-Players: "%plugin_prefix% We reached max players for this round. Let's shorten the time!" + Game-Started: "%plugin_prefix% The game has started!" + Kicked-For-Premium-Slot: "%color_chat_issue%%plugin_prefix% %player% got removed from the game to make a place for premium players!" + You-Were-Kicked-For-Premium-Slot: "%color_chat_issue%%plugin_prefix% You got kicked out of the game to make a place for a premium player!" + Not-Enough-Space-For-Party: "%color_chat_issue%%plugin_prefix% Your party is bigger than free places on the arena %arena_name%" + Game-End: + Summary: + - "&a&m--------------------------------------------------" + - "%plugin_name%" - "" - - "&f&lWINNER: %winner%" + - "%arena_summary%" + - "%arena_summary_player%" - "" - - "&7Detective: %detective%" - - "&7Murderer: %murderer% (%murderer_kills%)" - - "&7Hero: %hero%" + - "&7Detective: %arena_detective_list%" + - "&7Murderer: %arena_murderer_list% (%arena_murderer_kills%)" + - "&7Hero: %arena_hero%" - "" - - "&a&m------------------------------------------------------------------" - Admin-Messages: - Set-Starting-In-To-0: "&bAn admin set waiting time to 0. The game starts now!" + - "&a&m--------------------------------------------------" + Placeholders: + Win: "&aYou won the game" + Lose: "%color_chat_issue%You lost the game" + Players: "&cThere are not enough players anymore. Arena got force stopped!" + Murderer: + Stopped: "The Murderer has been stopped!" + Killed: + You: "The murderer killed you!" + All: "The Murderer has killed everyone." + Innocent: + Killed: + You: "A player killed you with a Bow!" + Wrongly: "You killed an innocent player!" + Nobody: "Nobody" + Admin: + Set-Starting-In-To-0: "%plugin_prefix% An admin set waiting time to 0. The game starts now!" + Arena: + Chances: + Action-Bar: "&cMurderer Chance: %arena_murderer_chance% &a- &bDetective Chance: %arena_detective_chance%" + Cooldown: "&8&l[%value%&8&l] &6%number% seconds" + Locator: + Bow: "Bow locator" + Innocent: "Innocent locator" + Watch-Out: "5,20,5;Watch out!;The Murderer can now find survivors easily" + Pass: + Name: "Role pass menu" + Role: + Murderer: + Name: "&cBe murderer" + Lore: + - "Cost 1 murderer pass" + - "You got %number%" + Detective: + Name: "&bBe detective" + Lore: + - "Cost 1 detective pass" + - "You got %number%" + Fail: "You do not got enough passes for %value% role" + Success: "You will be %value% next round!" + Change: "You now got %number% %value% passes!" + Playing: + Time-Left: "5,20,5;%arena_time% seconds left!;After %arena_time%s the Murderer will lose" + Role: + Change: "5,20,5;Previous %arena_player_role% has left!" + Murderer: "5,20,5;ROLE | MURDERER; Kill all players!" + Detective: "5,20,5;ROLE | DETECTIVE;Find and kill the murderer!" + Innocent: "5,20,5;ROLE | INNOCENT;Stay alive as long as possible!" + Score: + Bonus: "+%number% score (%value%)" + Gold: "Picked up gold!" + Action: + Kill: + Player: "for killing players" + Murderer: "for killing murderer" + Innocent: "for killing innocent" + Pickup: + Gold: "for gold pickup" + Surviving: + Time: "for surviving 30 seconds" + End: "for surviving till end" + Win: "for winning the game" + Detective: "for %number% innocents survived" + Sword: + Soon: "The Murderer gets their sword in %number% seconds!" + Special-Blocks: + Cauldron: + Potion: "Please drink your current potion!" + Hologram: "Mystery Potion - &e1 Gold" + Not-Enough-Gold: "You need %number% gold for this!" + Pray: + Hologram: "Click to give gift;Pull lever to pray" + Chat: "You prayed to the developer! Hope he will hear that!" + Pay: "%color_chat_issue%Pay to pray!" + Praise: + Heard: + - "" + - "&7Developer hears your prayer." + - "%feeling%" + - "%praise%" + Feeling: + Blessed: "&aYou feel blessed." + Cursed: "&cYou feel cursed." + Gifts: + Detective-Revelation: "&aYou know that &bCurrent detective &ais %detective%" + Gold-Rush: "&aYou received power of ancients. For each gold you collect, you will receive 3 gold now." + Single-Compensation: "&aDeveloper is proud of you! He rewarded you with 5 gold ingots!" + Bow: "&aYou received bow from pleased developer!" + Curses: + Slowness: "%color_chat_issue%Your legs are much heavier than before." + Blindness: "%color_chat_issue%Your eyes can't see that well anymore." + Gold: "%color_chat_issue%Developer cursed you with gold ban! You cannot longer pickup any gold!" + Death: "%color_chat_issue%You feel overpowering force of death. You know that you'll be dead in a minute!" + Bow: + Dropped: "5,20,5;The Bow has been dropped!;Find the Bow for a chance to kill the Murderer." + Pickup: "A player has picked up the Bow!" + Shot: + Gold: "&a+1 Bow Shot!" + Title: "5,20,5;;You collected 10 gold and got an arrow!" + + + + + + +# +# Sign messages +# Signs: - Please-Type-Arena-Name: "&cPlease type arena name in second line!" - Arena-Doesnt-Exists: "&cArena with that name doesn't exists!" - Sign-Created: "&aSign created successfully!" - Sign-Removed: "&aSign successfully removed!" - Game-States: - Inactive: "&lInactive..." - In-Game: "&lIn-game" - Starting: "&e&lStarting" - Full-Game: "&4&lFULL" - Ending: "&lEnding" - Restarting: "&c&lRestarting" + Please-Type-Arena-Name: "%color_chat_issue%%plugin_prefix% Please type arena name in second line!" + Arena-Doesnt-Exists: "%color_chat_issue%%plugin_prefix% Arena with that name doesn't exists!" + Created: "%plugin_prefix% Sign created successfully!" + Removed: "%plugin_prefix% Sign successfully removed!" Lines: - - "&4&lMurder Mystery" - - "%state%" - - "%mapname%" - - "&5[%playersize%/%maxplayers%]" + - "%plugin_prefix%" + - "%arena_state_placeholder%" + - "%arena_name%" + - "[%arena_players_size%/%arena_max_players%]" + +# +# Arena Selector messages +# Arena-Selector: - Inv-Title: "Arena selector" + Inventory-Title: "%plugin_short_command% ▸ Arena selector" Item: - Name: "&f%mapname%" + Name: "%arena_name%" Lore: - - "&4Murder Mystery &f- &e%mapname%" + - "%plugin_name% - %arena_name%" - " " - " " - - " &fOnline: %playersize%/%maxplayers%" - - " &fState: %state%" + - " Online: %arena_players_size%/%arena_max_players%" + - " State: %arena_state_placeholder%" - " " - " " - - "&eClick to join this arena" - -Leaderheads: - #top command from leaderheads ex. mmtopkills - Top-Command-Name: "mmtop%stat%" - Top-Command-Inv-Title: "&bTop users" - Leaderboard-Value: - Kills: "&e{amount} kills" - Deaths: "&e{amount} deaths" - Games-Played: "&e{amount} games played" - Highest-Score: "&e{amount} highest score" - Wins: "&e{amount} wins" - Loses: "&e{amount} loses" + - "&aClick to join this arena" +# +# Validator messages +# Validator: - Invalid-Arena-Configuration: "[Murder Mystery] Arena %arena% has invalid configuration! Missing node: %error%" - Instance-Started: "[Murder Mystery] Arena %arena% instance successfully started!" - No-Instances-Created: "[Murder Mystery] There are no arena instances created in configuration!" + Invalid-Arena-Configuration: "Arena %arena_name% has invalid configuration! Missing node: %value%" + Instance-Started: "Arena %arena_name% instance successfully started!" + No-Instances-Created: "There are no arena instances created in configuration!" + +# +# Placeholder messages inside plugin +# Placeholders: Game-States: Waiting: "&lWaiting for players..." Starting: "&e&lStarting" + Full-Game: "&4&lFULL" In-Game: "&lIn-game" Ending: "&lEnding" Restarting: "&c&lRestarting" + Motd: + Waiting: "&lYou can join this game..." + Starting: "&e&lStarting" + Full-Game: "&4&lFULL | Use another Server" + In-Game: "&lIn-game | Click to spectate" + Ending: "&lEnding | Server is closing" + Restarting: "&c&lRestarting" + + +# +# Leaderboard messages +# +# Hologram function need to be enabled on config.yml +Leaderboard: + Type: + Hologram: + Header: "&6&lTop %number% in %value%" + Format: "&e%number%. %player% (%value%)" + Empty-Format: "&e%number%. Empty (0)" + Chat: + Header: "&8+-------+ &a&lYOUR STATS &8+-------+" + Header-Other: "&8+---------+ &aSTATS FOR &b%player% &8+---------+" + Footer: "&8+-----------------------------+" + Format: "%value% ▸ &a%number%" + Top: + Type-Name: "%color_chat_issue%Please type statistic name to view!" + Header: "&8&m+----------------+ [&6 Top 10 &8&m] +----------------+" + Format: "&e#%number% %player% - %value% %user_statistic%" + Statistics: + Wins: "Wins ▸ %number%" + Loses: "Loses ▸ %number%" + Games-Played: "Games Played ▸ %number%" + Level: "Level ▸ %number%" + Exp: "Experience ▸ %number%" + Next-Level-Exp: "Exp to Level Up ▸ %number%" + Kills: "Kills ▸ %number%" + Deaths: "Deaths ▸ %number%" + Highest-Score: "Highest score ▸ %number%" + Murderer-Pass: "Murderer passes ▸ %number%" + Detective-Pass: "Detective passes ▸ %number%" + Murderer-Contribution: "Murderer contribution ▸ %number%" + Detective-Contribution: "Detective contribution ▸ %number%" + Invalid-Name: "%color_chat_issue%Name of statistic is invalid! Type: %value%" + Unknown-Player: "%color_chat_issue%Unknown Player" + # Don't edit it. But who's stopping you? It's your server! # Really, don't edit ;p -File-Version-Do-Not-Edit: 8 +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 diff --git a/src/main/resources/mysql.yml b/src/main/resources/mysql.yml index 548ba14f..6ecb0fd6 100644 --- a/src/main/resources/mysql.yml +++ b/src/main/resources/mysql.yml @@ -1,5 +1,5 @@ -# MySQL database configuration, you no need to touch this unless you enabled MySQL support. -# To enable MySQL support go to > config.yml and set 'DatabaseEnabled' to true +# MySQL database configuration, you don't need to touch this unless you enabled MySQL support. +# To enable MySQL support go to > config.yml and set 'Database' to true # Replace with your database address: jdbc:mysql://localhost:3306/?useSSL=false&autoReConnect=true @@ -11,9 +11,16 @@ user: password: # MySQL tablename -table: playerstats +table: mm_playerstats # Maximum life time for HikariCP database. # For documentation, see https://github.com/brettwooldridge/HikariCP#frequently-used # Default 1800000 = 30 minute -maxLifeTime: 1800000 \ No newline at end of file +maxLifeTime: 1800000 + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/permissions.yml b/src/main/resources/permissions.yml new file mode 100644 index 00000000..630ea708 --- /dev/null +++ b/src/main/resources/permissions.yml @@ -0,0 +1,54 @@ +# You can create custom players permissions here. +# Player with your custom permission will get int + +# All chances include murderer and detective +Chances-Boost: + # Do not use dots (.), they won't work. + # Increase chance by 10 times + chances-boost-5: 10 + chances-boost-50: 50 + # Increase chance by 100 times + admin-boost: 100 + + +Murderer-Boost: + # Do not use dots (.), they won't work. + # Increase murderer chance by 10 + murderer-boost-5: 10 + murderer-boost-50: 50 + # Increase murderer chance by 100 + admin-boost: 100 + + +Detective-Boost: + # Do not use dots (.), they won't work. + # Increase detective chance by 10 + detective-boost-5: 10 + detective-boost-50: 50 + # Increase detective chance by 100 + admin-boost: 100 + + +# Create custom exp boost permissions +Exp-Boost: + # Do not use dots (.), they won't work. + # Increase exp by 10 percent + exp-boost-10: 10 + exp-boost-50: 50 + # Increase exp by 300 percent + admin-boost: 300 + +# Basic permissions for game, permissions explained here: https://wiki.plugily.xyz/ +Basic: + Full-Games: "plugilyprojects.fullgames" + # represents arena name (NOT MAP NAME!), for example: 'plugilyprojects.join.ARENAnice' + # use 'plugilyprojects.join.*' to enable access to all arenas + Join: "plugilyprojects.join." + Forcestart: "plugilyprojects.admin.forcestart" + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 3c151d8d..4f3de8ef 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,18 +1,18 @@ name: MurderMystery main: plugily.projects.murdermystery.Main -authors: [2Wild4You, Tigerpanzer, Plajer, montlikadani] +authors: [ PlugilyProjects, Tigerpanzer_02 ] version: ${project.version} +softdepend: [CorpseReborn, PlaceholderAPI, Parties, Spigot-Party-API-PAF, PartyAndFriends, ViaVersion, ProtocolSupport] api-version: 1.13 -softdepend: [CorpseReborn, PlaceholderAPI, Parties, Spigot-Party-API-PAF, PartyAndFriends] commands: MurderMystery: - description: Murder mystery commands - usage: "\u00A76Correct usage: /mm [stats/leave/join]" + description: MurderMystery Commands + usage: "\u00A76Correct usage: /murdermystery [option]" aliases: [mm, murder] MurderMysteryAdmin: - description: Murder mystery admin commands - usage: "\u00A76Correct usage: /mma [option]" + description: MurderMysteryAdmin commands + usage: "\u00A76Correct usage: /murdermysterya [option]" aliases: [mma, murderadmin] permissions: @@ -20,14 +20,16 @@ permissions: default: op children: murdermystery.updatenotify: true - murdermystery.command.override: true murdermystery.admin: true murdermystery.admin.setup: true - murdermystery.admin.create: true murdermystery.admin.delete: true murdermystery.admin.list: true + murdermystery.admin.spychat: true murdermystery.admin.stopgame: true murdermystery.admin.forcestart: true murdermystery.admin.addsign: true + murdermystery.admin.clear: true murdermystery.admin.sign.create: true - murdermystery.admin.sign.break: true \ No newline at end of file + murdermystery.admin.sign.break: true + murdermystery.admin.reload: true + murdermystery.command.override: true \ No newline at end of file diff --git a/src/main/resources/powerups.yml b/src/main/resources/powerups.yml new file mode 100644 index 00000000..e95ca51b --- /dev/null +++ b/src/main/resources/powerups.yml @@ -0,0 +1,47 @@ +## Murder Mystery powerups.yml +# +Powerups: + Pickup: + Chat: "&a%player% picked the &4Powerup %value% up" + Ended: + Title: "&4Powerup %value% from %player%" + Subtitle: "&chas ended" + Chat: "&4Powerup %value% from %player% has ended%" + Drop: + Chance: 1 + Content: + Speed: + active: true + name: "&a&lSPEED BOOSTER" + description: "&7Double speed for %number% seconds!" + material: FEATHER + # Add as many potion effects as you want + # Format: PotionName, Duration, Amplifier + potion-effect: + - "SPEED, 15, 1" + # PLAYER for pickup player | ALL for all arena players + potion-type: PLAYER + # like rewards + execute: + - "" + Speed-All: + active: true + name: "&a&lSPEED BOOSTER FOR ALL" + description: "&7Double speed for all players in the next %number% seconds!" + material: FEATHER + # Add as many potion effects as you want + # Format: PotionName, Duration, Amplifier + potion-effect: + - "SPEED, 15, 1" + # PLAYER for pickup player | ALL for all arena players + potion-type: ALL + # like rewards + execute: + - "" + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/rewards.yml b/src/main/resources/rewards.yml index 59e4fe74..b9f3462f 100644 --- a/src/main/resources/rewards.yml +++ b/src/main/resources/rewards.yml @@ -1,14 +1,15 @@ # -# Murder Mystery rewards configuration +# Plugily Projects rewards configuration # -# Placeholders list: -# %PLAYER% - Current player name -# %MAPNAME% - Name of map -# %ARENA-ID% - Arena Identifier +# Placeholders list: +# %PLAYER% - Current player name +# %WAVE% - Current wave number +# %MAPNAME% - Name of map +# %ARENA-ID% - Arena Identifier # %PLAYERAMOUNT% - Number of players in game # # Commands are executed by default BY CONSOLE, use "p:" to preform command by player -# You can use chance to execute command adding "chance(NUMBER):" (ex chance(10):) at the beginning of command +# Since 3.6.3 you can use chance to execute command adding "chance(NUMBER):" (ex chance(10):) at the beginning of command # # Commands examples: # - p:say Hello everyone in %MAPNAME%! # Player will say "Hello everyone in " @@ -18,33 +19,39 @@ # ^ YOU CAN EVEN SWAP CHANCE WITH PLAYER! # - chance(50):eco give %PLAYER% 10 # Console has 10% chance to give player 10$ # +# Performed rewards: +# game-end +# # You can unlock full potential of rewards using our script engine! (since 4.0.0) # Just add example reward: # - script:player.sendMessage("oh, hi %PLAYER%"); # It will send "oh, hi " to player! 100% plain java! -# - script:arena.setWave(1); # Sets the wave to 1! # - script:server.broadcastMessage("hello everyone"); # Broadcasts "hello everyone" to whole server # - script:player.getInventory().addItem(new org.bukkit.inventory.ItemStack(org.bukkit.Material.DIRT)); # ^ Gives player dirt item (you must always use direct package names for not provided objects) # # All script provided objects: # player - Player object (API methods https://hub.spigotmc.org/javadocs/spigot/org/bukkit/entity/Player.html) -# arena - Murder Mystery arena (API methods https://jd.plugily.xyz/apidocs/minecraft/murdermystery/plugily/projects/murdermystery/arena/Arena.html) +# arena - Plugin arena (API methods https://jd.plugily.xyz/apidocs/minecraft/PLUGILYPROJECTS/plugily/projects/PLUGILYPROJECTS/arena/Arena.html) # server - Bukkit server object (API methods https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Server.html) # # Whole documentation of scripts soon! # Rewards must be enabled via config.yml first! rewards: + # Commands performed when game is started + game-start: + - say %arena_name% has started + - say Ooh and there are playing %arena_players_size% players # Commands performed when game is finished - endgame: - - say %MAPNAME% has ended! - - say Ooh and there were playing %PLAYERAMOUNT% players + game-end: + - say %arena_name% has ended + - say Ooh and there were playing %arena_players_size% players # Commands executed when detective is killed - detectivekill: + detective-kill: - eco give %PLAYER% 2 - chance(10):eco give %PLAYER% 8 # Commands executed when murderer is killed - murdererkill: + murderer-kill: - eco give %PLAYER% 2 - chance(10):eco give %PLAYER% 8 # Commands executed when player wins the game @@ -53,7 +60,14 @@ rewards: # Commands executed when player loses the game lose: - say I lost the game! - death: + player-death: - say I died! - gold_pickup: - - say You picked up gold! \ No newline at end of file + gold-pickup: + - say You picked up gold! + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/signs.yml b/src/main/resources/signs.yml new file mode 100644 index 00000000..b08570ed --- /dev/null +++ b/src/main/resources/signs.yml @@ -0,0 +1,6 @@ +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/skins.yml b/src/main/resources/skins.yml new file mode 100644 index 00000000..af8290ac --- /dev/null +++ b/src/main/resources/skins.yml @@ -0,0 +1,7 @@ +Skins: + Sword: + 'default': + Material: IRON_SWORD + 'Stone': + Material: STONE_SWORD + Permission: "murdermystery.skins.sword.stone" \ No newline at end of file diff --git a/src/main/resources/specialblocks.yml b/src/main/resources/special_blocks.yml similarity index 67% rename from src/main/resources/specialblocks.yml rename to src/main/resources/special_blocks.yml index 9891f924..b0fc62e0 100644 --- a/src/main/resources/specialblocks.yml +++ b/src/main/resources/special_blocks.yml @@ -25,14 +25,26 @@ Special-Blocks: Duration: 10 Amplifier: 1 # Beware that we use '&f' at the end to make it different from above! - # Otherwise it will count as Mystery-I potion! + # Otherwise, it will count as Mystery-I potion! Name: "&7Mystery potion &8(???)&f" - Subtitle: "&a10S of Slowness" + Subtitle: "&c10S of Slowness" Mystery-III: Type: INVISIBILITY Duration: 10 Amplifier: 1 # Beware that we use '&a' at the end to make it different from above! - # Otherwise it will count as Mystery-I potion! + # Otherwise, it will count as Mystery-I potion! Name: "&7Mystery potion &8(???)&a" - Subtitle: "&a10S of Invisibility" \ No newline at end of file + Subtitle: "&a10S of Invisibility" + Mystery-IV: + Type: BLINDNESS + Duration: 5 + Amplifier: 1 + Name: "&7Mystery potion &8(???)&b" + Subtitle: "&c5S of Blindness" + Mystery-V: + Type: NIGHT_VISION + Duration: 25 + Amplifier: 1 + Name: "&7Mystery potion &8(???)&c" + Subtitle: "&a25S of Night Vision" \ No newline at end of file diff --git a/src/main/resources/special_items.yml b/src/main/resources/special_items.yml index c2138bf1..a7c39efa 100644 --- a/src/main/resources/special_items.yml +++ b/src/main/resources/special_items.yml @@ -1,57 +1,140 @@ -# Custom in-game items. -# Probably you will only translate displayname and lore so don't mess with it. +# Custom special items. +# You can also add your own special items! # -# Please don't modify 'Leave-Lobby', 'Leave-Spectator', 'Player-List' and 'Spectator-Options' +# Stage: SERVER_JOIN, WAITING_FOR_PLAYERS, ENOUGH_PLAYERS_TO_START, LOBBY, IN_GAME, SPECTATOR, ENDING +# +# Please don't modify 'Kit-Menu', 'Leave-Lobby', 'Leave-Spectator', 'Player-List' and 'Spectator-Options', 'Forcestart' # nodes as they are hardcoded in code! - -Forcestart: - displayname: "&c&lClick to start the game &7(Right Click)" - lore: - - "&7You need the following permission for it" - - "&7murdermystery.admin.forcestart" - material-name: EMERALD - slot: 0 - stage: lobby +# +# Also see the wiki for further reference! Role-Pass: + permission: "" + execute: + - "p:mm roleselector" displayname: "&c&lClick to open role pass menu &7(Right Click)" lore: - "&7Enjoy one round of guaranteed role with pass" - material-name: CHEST + material: CHEST slot: 4 stage: lobby + force: true + move: false -Leave-Lobby: +# Uses bungee.yml configuration - if enabled it tries to connect to your hub +Lobby-Leave: + permission: "" + execute: + - "" displayname: "&c&lReturn to Lobby &7(Right Click)" lore: - "&7Right-click to leave to the lobby" - material-name: BED + material: BED slot: 8 - stage: lobby + stage: LOBBY + force: true + move: false -Leave-Spectator: +# Uses bungee.yml configuration - if enabled it tries to connect to your hub +Spectator-Leave: + permission: "" + execute: + - "" displayname: "&c&lLeave the Game &7(Right Click)" lore: - "&7Right-click to leave to the lobby" - material-name: BED + material: BED slot: 8 - stage: spectator + stage: SPECTATOR + force: true + move: false Player-List: + permission: "" + execute: + - "" displayname: "&a&lAlive Players &7(Right Click)" lore: - "&7Right-click to see alive players list" - material-name: PLAYER_HEAD + material: PLAYER_HEAD slot: 0 - stage: spectator + stage: SPECTATOR + force: true + move: false -Spectator-Options: +Spectator-Settings: + permission: "" + execute: + - "" displayname: "&b&lSpectator Settings &7(Right Click)" lore: - "&7Right-click to adjust spectator settings" - material-name: COMPARATOR + material: COMPASS + slot: 4 + stage: SPECTATOR + force: true + move: false + +Forcestart: + permission: "plugily.projects.forcestart" + execute: + - "" + displayname: "&c&lStart the game &7(Right Click)" + lore: + - "&7You need the following permission for it" + - "&7plugily.projects.forcestart" + material: EMERALD + slot: 2 + stage: ENOUGH_PLAYERS_TO_START + force: true + move: false + +Arena-Selector: + disabled: true # disabled by default + permission: "" + execute: + - "p:mm arenas" + displayname: "&c&lArena selector &7(Right Click)" + lore: + - "&7Right-click to see all arenas" + material: CHEST slot: 4 - stage: spectator + stage: SERVER_JOIN + force: false + move: false + +Stats: + disabled: true # disabled by default + permission: "" + execute: + - "p:mm stats" + displayname: "&c&lStats &7(Right Click)" + lore: + - "&7Right-click to see your Stats" + material: PLAYER_HEAD + slot: 0 + stage: SERVER_JOIN + force: false + move: false + +# Uses bungee.yml configuration - if enabled it tries to connect to your hub +Back-To-Hub: + disabled: true # disabled by default + permission: "" + execute: + - "p:hub" + displayname: "&c&lBack to Hub &7(Right Click)" + lore: + - "&7Right-click to return to lobby" + material: Bed + slot: 8 + stage: SERVER_JOIN + force: false + move: false -# Don't touch this -Version: 1 \ No newline at end of file +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/spectator.yml b/src/main/resources/spectator.yml new file mode 100644 index 00000000..7f3e828d --- /dev/null +++ b/src/main/resources/spectator.yml @@ -0,0 +1,97 @@ +# Make sure to read the wiki for further reference! +# section keys with DEFAULT_SPEED, SPEED1, SPEED2, SPEED3, SPEED4, AUTO_TELEPORT, NIGHT_VISION, FIRST_PERSON_MODE, SPECTATORS_VISIBILITY have a defined function + +Settings-Menu: + Inventory-name: "&7Spectator settings" + Content: + 'DEFAULT_SPEED': + material: LEATHER_BOOTS + # slot at the inventory, 0 is first slot + slot: 11 + name: "Default Speed" + description: + - "Sets the default minecraft speed" + permission: "" + execute: + # You could also add a potion effect by console command + - "" + 'SPEED1': + material: CHAINMAIL_BOOTS + slot: 12 + name: "Speed I" + description: + - "Adds a speed 1 potion" + permission: "" + execute: + - "" + 'SPEED2': + material: IRON_BOOTS + slot: 13 + name: "Speed II" + description: + - "Adds a speed 2 potion" + permission: "" + execute: + - "" + 'SPEED3': + material: GOLDEN_BOOTS + slot: 14 + name: "Speed III" + description: + - "Adds a speed 3 potion" + permission: "" + execute: + - "" + 'SPEED4': + material: DIAMOND_BOOTS + slot: 15 + name: "Speed IV" + description: + - "Adds a speed 4 potion" + permission: "" + execute: + - "" + 'AUTO_TELEPORT': + material: COMPASS + slot: 20 + name: "Automatically teleport" + description: + - "Automatically teleports you to your targeted player" + permission: "" + execute: + - "" + 'NIGHT_VISION': + material: ENDER_PEARL + slot: 21 + name: "Night vision" + description: + - "With nigh vision you will be able to see ghosts" + permission: "" + execute: + - "" + 'FIRST_PERSON_MODE': + material: CLOCK + slot: 23 + name: "First person mode" + description: + - "When in first person mode you will spectate like you would play yourself" + permission: "" + execute: + - "" + 'SPECTATORS_VISIBILITY': + material: REDSTONE + slot: 24 + name: "Spectators visibility" + description: + - "Its a good choice if you hate other players" + permission: "" + execute: + - "" + + +# Don't edit it. But who's stopping you? It's your server! +# Really, don't edit ;p +# You edited it, huh? Next time hurt yourself! +Do-Not-Edit: + File-Version: 1 + Core-Version: 1 \ No newline at end of file diff --git a/src/main/resources/stats.yml b/src/main/resources/stats.yml index e69de29b..37408612 100644 --- a/src/main/resources/stats.yml +++ b/src/main/resources/stats.yml @@ -0,0 +1 @@ +data-version: 1 \ No newline at end of file diff --git a/src/main/resources/trails.yml b/src/main/resources/trails.yml new file mode 100644 index 00000000..a6436263 --- /dev/null +++ b/src/main/resources/trails.yml @@ -0,0 +1,6 @@ +#Add trails that you want to blacklist from all trails(particles) +Blacklisted-Trails: + - "elder_guardian" + - "block_crack" + - "item_crack" + - "block_dust"