diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0882495 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +max_line_length = 120 +tab_width = 4 +trim_trailing_whitespace = true +ij_continuation_indent_size = 4 +[*.yml] +indent_size = 2 diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 0000000..9efa6f4 --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,61 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle + +name: Java CI with Gradle + +on: + push: + branches: + - master + - 'dev/**' + - 'update/**' + pull_request: + +permissions: + contents: read + +jobs: + build_plugin: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v4.2.1 + with: + java-version: '21' + distribution: 'temurin' + - name: Build with Gradle + uses: gradle/actions/setup-gradle@v3 + with: + arguments: build + - name: Upload a Build Artifact + uses: actions/upload-artifact@master + with: + # Artifact name + name: SurvivalPlus-Plugin + # A file, directory or wildcard pattern that describes what to upload + path: build/libs/SurvivalPlus-*.jar + build_resource_pack: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v4.2.1 + with: + java-version: '21' + distribution: 'temurin' + - name: Build with Gradle + uses: gradle/actions/setup-gradle@v3 + with: + arguments: resourcepack + - name: Upload a Build Artifact + uses: actions/upload-artifact@master + with: + # Artifact name + name: SurvivalPlus-ResourcePack + # A file, directory or wildcard pattern that describes what to upload + path: build/libs/SurvivalPlusResourcePack-*.zip diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml deleted file mode 100644 index 70ea463..0000000 --- a/.github/workflows/maven.yml +++ /dev/null @@ -1,31 +0,0 @@ -# This workflow will build a Java project with Maven -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven - -name: Java CI with Maven - -on: - push: - branches: '**' - pull_request: - branches: '**' - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build with Maven - run: mvn -B package --file pom.xml - - name: Upload a Build Artifact - uses: actions/upload-artifact@v2.1.4 - with: - # Artifact name - name: SurvivalPlus-Artifact - # A file, directory or wildcard pattern that describes what to upload - path: target/SurvivalPlus*.jar diff --git a/.gitignore b/.gitignore index 7be156d..db3f172 100644 --- a/.gitignore +++ b/.gitignore @@ -1,34 +1,42 @@ -# Compiled class file -*.class +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.ear -*.tar.gz -*.rar - -# IntelliJ Files # +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws *.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Custom # +### Eclipse ### +.apt_generated .classpath -.settings +.factorypath .project -bin -JavaDocs/ -out/ -.idea/ -/target/ +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store diff --git a/README.md b/README.md index bc85993..b291c72 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,7 @@ # SurvivalPlus ![GitHub issues](https://img.shields.io/github/issues/ShaneBeeStudios/SurvivalPlus.svg) [![Discord](https://img.shields.io/discord/425192525091831808.svg)](https://discordapp.com/invite/km3UF8Q) -![Java CI with Maven](https://github.com/ShaneBeeStudios/SurvivalPlus/workflows/Java%20CI%20with%20Maven/badge.svg) - -![https://docs.google.com/uc?id=0B8D0KMKK7musWTBQaWozV0dxN2c](https://docs.google.com/uc?id=0B8D0KMKK7musWTBQaWozV0dxN2c) +![Java CI with Maven](https://github.com/ShaneBeeStudios/SurvivalPlus/workflows/Java%20CI%20with%20Gradle/badge.svg) ## Welcome to SurvivalPlus @@ -11,4 +9,9 @@ SurvivalPlus is a Minecraft mod that adds new contents and experience to Minecra All info can be found on the [**WIKI**](https://github.com/ShaneBeeStudios/SurvivalPlus/wiki) -Plugin downloads can be found on [**SpigotMC**](https://www.spigotmc.org/resources/survival-plus.67351/) +Plugin downloads can be found on (TBD) + +### BUILDING: +- To build the plugin run `./gradlew build` (This includes the datapack internally) +- To build the datapack run `./gradlew datapack` +- To build the resource pack run `./gradlew resourcepack` diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..ad4204c --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,104 @@ +plugins { + id("java") + id("io.github.goooler.shadow") version "8.1.7" +} + +// Where this builds on the server +val serverLocation = "Skript/1-21-4" +// Version of SurvivalPlus +val projectVersion = "1.0.0" +// Minecraft version to build against +val minecraftVersion = "1.21.4" + +java.sourceCompatibility = JavaVersion.VERSION_21 + +repositories { + mavenCentral() + mavenLocal() + + // Paper + maven("https://repo.papermc.io/repository/maven-public/") + + // Command Api Snapshots + maven("https://s01.oss.sonatype.org/content/repositories") + + // JitPack repo + maven("https://jitpack.io") + + // Papi + maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") +} + +dependencies { + // Paper + compileOnly("io.papermc.paper:paper-api:${minecraftVersion}-R0.1-SNAPSHOT") + + // FastBoard + implementation("fr.mrmicky:fastboard:2.1.3") + + // Command Api + implementation("dev.jorel:commandapi-bukkit-shade-mojang-mapped:9.7.0") + + // Papi + compileOnly("me.clip:placeholderapi:2.11.6") + + // bStats + implementation("org.bstats:bstats-bukkit:3.0.2") + +} + +tasks { + register("server", Copy::class) { + dependsOn("shadowJar") + from("build/libs") { + include("SurvivalPlus-*.jar") + destinationDir = file("/Users/ShaneBee/Desktop/Server/${serverLocation}/plugins/") + } + + } + register("resourcepack", Zip::class) { + archiveFileName = "SurvivalPlusResourcePack-${projectVersion}.zip" + from("src/main/resources/resource-pack") { + exclude("**/.DS_Store") + destinationDirectory = file("build/libs/") + } + } + register("datapack", Zip::class) { + archiveFileName = "SurvivalPlusDataPack-${projectVersion}.zip" + from("src/main/resources/datapack") { + exclude("**/.DS_Store") + destinationDirectory = file("build/libs/") + } + } + processResources { + expand("version" to projectVersion) + exclude("resource-pack/*") + } + compileJava { + options.release = 21 + options.compilerArgs.add("-Xlint:unchecked") + options.compilerArgs.add("-Xlint:deprecation") + } + javadoc { + options.encoding = Charsets.UTF_8.name() + exclude("com/shanebeestudios/survival/plugin/SurvivalBootstrap.java") + exclude("com/shanebeestudios/survival/plugin/commands") + exclude("com/shanebeestudios/survival/plugin/listeners") + exclude("com/shanebeestudios/survival/plugin/tasks") + (options as CoreJavadocOptions).addBooleanOption("Xdoclint:none", true) + (options as StandardJavadocDocletOptions).links( + "https://jd.papermc.io/paper/${minecraftVersion}/", + "https://jd.advntr.dev/api/4.18.0/" + ) + } + shadowJar { + relocate("fr.mrmicky.fastboard", "com.shanebeestudios.survival.api.fastboard") + relocate("dev.jorel.commandapi", "com.shanebeestudios.survival.api.commandapi") + relocate("org.bstats", "com.shanebeestudios.survival.api.metrics") + archiveFileName = "SurvivalPlus-${projectVersion}.jar" + } + jar { + dependsOn(shadowJar) + archiveFileName.set("SurvivalPlus.jar") + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 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 0000000..cea7a79 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# 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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +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 + if ! command -v java >/dev/null 2>&1 + then + 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 +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=SC2039,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=SC2039,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, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +: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/pom.xml b/pom.xml deleted file mode 100644 index 4fef8a1..0000000 --- a/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - 4.0.0 - - tk.shanebee - SurvivalPlus - 3.15.0 - - - 1.8 - 1.8 - UTF-8 - - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - placeholderapi - http://repo.extendedclip.com/content/repositories/placeholderapi/ - - - - - - org.spigotmc - spigot-api - 1.16.4-R0.1-SNAPSHOT - provided - - - me.clip - placeholderapi - 2.10.4 - provided - - - org.jetbrains - annotations - 16.0.3 - - - - - - server - - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.0 - - - /Users/ShaneBee/Desktop/Server/1-16-SP-TEST/plugins - - - - - - - - - src/main/java - ${project.name}-${project.version} - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - 3.8.1 - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.1.1 - - 11 - - https://hub.spigotmc.org/javadocs/spigot/ - https://commons.apache.org/proper/commons-lang/javadocs/api-2.6 - - *.listeners.*:*.listeners;*.tasks.*:*.tasks;*.commands:*.metrics - - - - - - - src/main/resources - true - . - - plugin.yml - config.yml - items.yml - data.yml - lang_CN.yml - lang_EN.yml - - - - - - diff --git a/resource_pack/SP-1.14-3.0.0.zip b/resource_pack/SP-1.14-3.0.0.zip deleted file mode 100644 index ef55520..0000000 Binary files a/resource_pack/SP-1.14-3.0.0.zip and /dev/null differ diff --git a/resource_pack/SR-1.14-Beta5.zip b/resource_pack/SR-1.14-Beta5.zip deleted file mode 100644 index 3a58e66..0000000 Binary files a/resource_pack/SR-1.14-Beta5.zip and /dev/null differ diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..8dcf26c --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "SurvivalPlus" diff --git a/src/main/java/com/shanebeestudios/survival/api/data/HealthBoard.java b/src/main/java/com/shanebeestudios/survival/api/data/HealthBoard.java new file mode 100644 index 0000000..01d18a0 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/data/HealthBoard.java @@ -0,0 +1,146 @@ +package com.shanebeestudios.survival.api.data; + +import com.google.common.base.Preconditions; +import fr.mrmicky.fastboard.adventure.FastBoard; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Scoreboard; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a scoreboard for player data + *

Uses {@link FastBoard} for packet based scoreboards

+ */ +@SuppressWarnings("unused") +public class HealthBoard { + + // STATIC STUFF + private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage(); + private static final Scoreboard MAIN = Bukkit.getScoreboardManager().getMainScoreboard(); + private static final Scoreboard DUMMY = Bukkit.getScoreboardManager().getNewScoreboard(); + + // OBJECT STUFF + private final Player player; + private FastBoard fastBoard; + private final Component[] lines = new Component[15]; + private final Component[] formats = new Component[15]; + private Component title; + private boolean on; + + public HealthBoard(Player player) { + this.player = player; + this.on = false; + } + + /** + * Set the title of this Board + * + * @param title Title to set + */ + public void setTitle(String title) { + this.title = MINI_MESSAGE.deserialize(title); + } + + /** + * Set a specific line for this Board + *

Lines 1 - 15

+ * + * @param line Line to set (1 - 15) + * @param text Text to put in line + */ + public void setLine(int line, @Nullable String text) { + setLine(line, text, null); + } + + public void setLine(int line, @Nullable String text, String format) { + Preconditions.checkArgument(line >= 1 && line <= 15, "Line number must be between 1 and 15, found: " + line); + if (text != null) { + Component component = MINI_MESSAGE.deserialize(text); + this.lines[line - 1] = component; + } else { + this.lines[line - 1] = null; + } + if (format != null) { + Component component = MINI_MESSAGE.deserialize(format); + this.formats[line - 1] = component; + } else { + this.formats[line - 1] = null; + } + } + + /** + * Delete a line in this Board + *

Lines 1 - 15

+ * + * @param line Line to delete (1 - 15) + */ + public void deleteLine(int line) { + setLine(line, null); + } + + /** + * Clear all lines of this Board + */ + public void clearBoard() { + for (int i = 1; i < 16; i++) { + deleteLine(i); + } + } + + public void update() { + if (this.fastBoard != null) { + this.fastBoard.updateTitle(this.title); + List lines = new ArrayList<>(); + List formats = new ArrayList<>(); + for (int i = 0; i < this.lines.length; i++) { + if (this.lines[i] != null) { + lines.add(this.lines[i]); + if (this.formats[i] != null) { + formats.add(this.formats[i]); + } else { + formats.add(Component.empty()); + } + } + } + this.fastBoard.updateLines(lines, formats); + } + } + + /** + * Toggle this Board on or off + *
+ * When off, will not be visible to player, but can still update + * + * @param on Whether on or off + */ + public void toggle(boolean on) { + if (on) { + this.fastBoard = new FastBoard(this.player); + this.on = true; + } else { + if (this.fastBoard != null) { + this.fastBoard.delete(); + this.fastBoard = null; + } + this.on = false; + // Force resends the vanilla scoreboard + this.player.setScoreboard(DUMMY); + this.player.setScoreboard(MAIN); + } + } + + /** + * Check if this Board is on or off + * + * @return True if on else false + */ + public boolean isOn() { + return this.on; + } + +} diff --git a/src/main/java/tk/shanebee/survival/data/Info.java b/src/main/java/com/shanebeestudios/survival/api/data/Info.java similarity index 68% rename from src/main/java/tk/shanebee/survival/data/Info.java rename to src/main/java/com/shanebeestudios/survival/api/data/Info.java index 226f51e..dcfdc3e 100644 --- a/src/main/java/tk/shanebee/survival/data/Info.java +++ b/src/main/java/com/shanebeestudios/survival/api/data/Info.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.data; +package com.shanebeestudios.survival.api.data; /** * Info for player scoreboards diff --git a/src/main/java/tk/shanebee/survival/data/Nutrient.java b/src/main/java/com/shanebeestudios/survival/api/data/Nutrient.java similarity index 76% rename from src/main/java/tk/shanebee/survival/data/Nutrient.java rename to src/main/java/com/shanebeestudios/survival/api/data/Nutrient.java index 782b5d6..3f6fc8a 100644 --- a/src/main/java/tk/shanebee/survival/data/Nutrient.java +++ b/src/main/java/com/shanebeestudios/survival/api/data/Nutrient.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.data; +package com.shanebeestudios.survival.api.data; /** * Player nutrient types @@ -7,7 +7,7 @@ public enum Nutrient { CARBS("Carbs"), PROTEIN("Protein"), - SALTS("Salts"); + VITAMINS("Vitamins"); private final String name; diff --git a/src/main/java/com/shanebeestudios/survival/api/data/Permissions.java b/src/main/java/com/shanebeestudios/survival/api/data/Permissions.java new file mode 100644 index 0000000..f2c2c20 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/data/Permissions.java @@ -0,0 +1,70 @@ +package com.shanebeestudios.survival.api.data; + +import com.shanebeestudios.survival.api.util.Utils; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.util.permissions.DefaultPermissions; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class Permissions { + + public record Permission(String permission, org.bukkit.permissions.Permission bukkitPermission) { + + public boolean has(CommandSender sender) { + return sender.hasPermission(this.bukkitPermission.getName()); + } + } + + static final Map PERMISSIONS = new LinkedHashMap<>(); + + // Command permissions + public static final Permission COMMAND_CHAT = getCommand("chat", "Toggle global/local chat", PermissionDefault.TRUE); + public static final Permission COMMAND_DATA_GEN = getCommand("datagen", "Generate stuff for configs, should not be used", PermissionDefault.OP); + public static final Permission COMMAND_DEBUG = getCommand("debug", "Debug some internal things", PermissionDefault.OP); + public static final Permission COMMAND_GIVEITEM = getCommand("giveitem", "Give a custom item", PermissionDefault.OP); + public static final Permission COMMAND_HEAL = getCommand("heal", "Heal self", PermissionDefault.OP); + public static final Permission COMMAND_HEAL_OTHERS = getCommand("heal.others", "Heal others", PermissionDefault.OP); + public static final Permission COMMAND_NUTRITION = getCommand("nutrition", "Open nutrition GUI", PermissionDefault.TRUE); + public static final Permission COMMAND_PLAYERDATA = getCommand("playerdata", "Adjust player data", PermissionDefault.OP); + public static final Permission COMMAND_RELOAD = getCommand("reload", "Reload config files", PermissionDefault.OP); + public static final Permission COMMAND_STATS = getCommand("stats", "Toggle stats", PermissionDefault.TRUE); + + // Bypass permissions + public static final Permission BYPASS_STAT_ENERGY = getBypass("stat.energy", "Bypass energy stats"); + public static final Permission BYPASS_STAT_NUTRITION = getBypass("stat.nutrition", "Bypass nutrition stats"); + public static final Permission BYPASS_REQUIRED_TOOLS = getBypass("required_tools", "Bypass required tools"); + public static final Permission BYPASS_STAT_THIRST = getBypass("stat.thirst", "Bypass thirst stats"); + public static final Permission BYPASS_WEATHER = getBypass("weather", "Bypass weather effects"); + + private static Permission getCommand(String perm, String description, PermissionDefault defaultPermission) { + return getBase("command", perm, description, defaultPermission); + } + + private static Permission getBypass(String perm, String description) { + return getBase("bypass", perm, description, PermissionDefault.FALSE); + } + + private static Permission getBase(String base, String perm, String description, PermissionDefault defaultPermission) { + String stringPerm = "survivalplus." + base + "." + perm; + org.bukkit.permissions.Permission bukkitPermission = DefaultPermissions.registerPermission(stringPerm, description, defaultPermission); + PERMISSIONS.put(stringPerm, bukkitPermission); + return new Permission(stringPerm, bukkitPermission); + } + + public static void debug() { + Utils.logMini("Permissions:"); + for (Map.Entry entry : PERMISSIONS.entrySet()) { + String color = switch (entry.getValue().getDefault()) { + case OP -> "yellow"; + case TRUE, NOT_OP -> "green"; + case FALSE -> "red"; + }; + Utils.logMini(" '<#F09616>%s':", entry.getKey()); + Utils.logMini(" Description: %s", entry.getValue().getDescription()); + Utils.logMini(" Default: <%s>%s", color, entry.getValue().getDefault().toString()); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/data/Placeholders.java b/src/main/java/com/shanebeestudios/survival/api/data/Placeholders.java new file mode 100644 index 0000000..daaeabd --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/data/Placeholders.java @@ -0,0 +1,44 @@ +package com.shanebeestudios.survival.api.data; + +import com.shanebeestudios.survival.api.util.Utils; + +public enum Placeholders { + PLAYER_HEALTH("player_health", "Player's health"), + PLAYER_HUNGER("player_hunger", "Player's hunger"), + PLAYER_SATURATION("player_saturation", "Player's saturation"), + PLAYER_HUNGER_TOTAL("player_hunger_total", "Player's total hunger (including saturation)"), + PLAYER_HUNGER_BAR_1("player_hunger_bar_1", "Shows player's hunger bar (hunger part)"), + PLAYER_HUNGER_BAR_2("player_hunger_bar_2", "Shows player's hunger bar (saturation part)"), + PLAYER_THIRST("player_thirst", "Player's thirst"), + PLAYER_THIRST_BAR_1("player_thirst_bar_1", "Shows player's thirst bar (top part - first half out of 40)"), + PLAYER_THIRST_BAR_2("player_thirst_bar_2", "Shows player's thirst bar (bottom part - second half out of 40)"), + PLAYER_ENERGY("player_energy", "Player's energy"), + PLAYER_ENERGY_BAR("player_energy_bar", "Shows player's energy bar"), + PLAYER_NUTRIENTS_CARBS("player_nutrients_carbs", "Player's nutrients carbs"), + PLAYER_NUTRIENTS_PROTEINS("player_nutrients_proteins", "Player's nutrients proteins"), + PLAYER_NUTRIENTS_VITAMINS("player_nutrients_vitamins", "Player's nutrients vitamins"), + PLAYER_NUTRIENTS_CARBS_BAR("player_nutrients_carbs_bar", "Shows player's nutrients carbs bar"), + PLAYER_NUTRIENTS_PROTEINS_BAR("player_nutrients_proteins_bar", "Shows player's nutrients proteins bar"), + PLAYER_NUTRIENTS_VITAMINS_BAR("player_nutrients_vitamins_bar", "Shows player's nutrients vitamins bar"), + ; + + private final String key; + private final String description; + + Placeholders(String key, String description) { + this.key = key; + this.description = description; + } + + public boolean is(String identifier) { + return identifier.equalsIgnoreCase(this.key); + } + + public static void debug() { + Utils.logMini("PAPI Placeholders:"); + for (Placeholders value : Placeholders.values()) { + Utils.logMini(" - 'survival_plus_%s' = '%s'", value.key, value.description); + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/data/PlayerData.java b/src/main/java/com/shanebeestudios/survival/api/data/PlayerData.java similarity index 61% rename from src/main/java/tk/shanebee/survival/data/PlayerData.java rename to src/main/java/com/shanebeestudios/survival/api/data/PlayerData.java index 954651a..36eebd0 100644 --- a/src/main/java/tk/shanebee/survival/data/PlayerData.java +++ b/src/main/java/com/shanebeestudios/survival/api/data/PlayerData.java @@ -1,15 +1,19 @@ -package tk.shanebee.survival.data; - +package com.shanebeestudios.survival.api.data; + +import com.shanebeestudios.survival.api.events.EnergyLevelChangeEvent; +import com.shanebeestudios.survival.api.events.ThirstLevelChangeEvent; +import com.shanebeestudios.survival.api.util.Math; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.OfflinePlayer; +import org.bukkit.Statistic; import org.bukkit.World; import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.util.Math; +import org.jetbrains.annotations.ApiStatus; import java.util.HashMap; import java.util.LinkedHashMap; @@ -19,27 +23,23 @@ /** * Holder of data for player - *

You can get an instance of PlayerData from {@link tk.shanebee.survival.managers.PlayerManager}

+ *

You can get an instance of PlayerData from {@link PlayerManager}

*/ @SuppressWarnings({"unused", "FieldCanBeLocal", "SameParameterValue"}) +@SerializableAs("PlayerData") public class PlayerData implements ConfigurationSerializable { - private final Config config = Survival.getInstance().getSurvivalConfig(); - private final int max_carbs = config.MECHANICS_FOOD_MAX_CARBS; - private final int max_proteins = config.MECHANICS_FOOD_MAX_PROTEINS; - private final int max_salts = config.MECHANICS_FOOD_MAX_SALTS; + private final Config config = SurvivalPlugin.getInstance().getSurvivalConfig(); + private final Player player; private final UUID uuid; - private int thirst; private Map compassMap = new HashMap<>(); // Nutrients - private int proteins; private int carbs; - private int salts; + private int proteins; + private int vitamins; private double energy; - - // Dunno yet - private boolean localChat = false; + private double thirst; // Stats private int charge = 0; @@ -51,6 +51,7 @@ public class PlayerData implements ConfigurationSerializable { private int healTimes = 0; private int recurveFiring = 0; private int recurveCooldown = 0; + private boolean localChat = false; // Scoreboard info private boolean score_hunger = true; @@ -58,17 +59,24 @@ public class PlayerData implements ConfigurationSerializable { private boolean score_energy = true; private boolean score_nutrients = true; - public PlayerData(OfflinePlayer player, int thirst, int proteins, int carbs, int salts, double energy) { - this(player.getUniqueId(), thirst, proteins, carbs, salts, energy); - } + // Bypasses + private final Map bypasses = new HashMap<>(); - public PlayerData(UUID uuid, int thirst, int proteins, int carbs, int salts, double energy) { - this.uuid = uuid; - this.thirst = thirst; + /** + * @hidden Shouldn't be using this constructor outside the plugin + */ + @ApiStatus.Internal + public PlayerData(Player player, double thirst, int proteins, int carbs, int vitamins, double energy) { + this.player = player; + this.uuid = player.getUniqueId(); + this.thirst = Math.clamp(thirst, 0, 40); this.proteins = proteins; this.carbs = carbs; - this.salts = salts; - this.energy = energy; + this.vitamins = vitamins; + this.energy = Math.clamp(energy, 0, 20); + this.bypasses.put(Info.ENERGY, Permissions.BYPASS_STAT_ENERGY.has(player)); + this.bypasses.put(Info.THIRST, Permissions.BYPASS_STAT_THIRST.has(player)); + this.bypasses.put(Info.NUTRIENTS, Permissions.BYPASS_STAT_NUTRITION.has(player)); } /** @@ -77,7 +85,7 @@ public PlayerData(UUID uuid, int thirst, int proteins, int carbs, int salts, dou * @return Player from this data */ public Player getPlayer() { - return Bukkit.getPlayer(uuid); + return this.player; } /** @@ -86,7 +94,7 @@ public Player getPlayer() { * @return UUID of player from this data */ public UUID getUuid() { - return uuid; + return this.uuid; } /** @@ -94,8 +102,8 @@ public UUID getUuid() { * * @return Thirst of this data */ - public int getThirst() { - return thirst; + public double getThirst() { + return this.thirst; } /** @@ -103,17 +111,28 @@ public int getThirst() { * * @param thirst Level of thirst to set */ - public void setThirst(int thirst) { + public void setThirst(double thirst) { this.thirst = Math.clamp(thirst, 0, 40); } /** * Increase the thirst for this data * - * @param thirst Level of thirst to add + * @param change Level of thirst to add */ - public void increaseThirst(int thirst) { - this.thirst = Math.clamp(this.thirst + thirst, 0, 40); + public void increaseThirst(double change) { + if (change < 0) { + int immunityMinutes = this.config.mechanics_thirst_immunity_minutes; + if (this.bypasses.get(Info.THIRST)) { + return; + } else if (immunityMinutes > 0) { + int secondsPlayed = this.player.getStatistic(Statistic.PLAY_ONE_MINUTE) / 20 / 60; + if (immunityMinutes > secondsPlayed) return; + } + } + ThirstLevelChangeEvent thirstEvent = new ThirstLevelChangeEvent(this.player, change, getThirst() + change); + if (!thirstEvent.callEvent()) return; + setThirst(this.thirst + change); } /** @@ -123,16 +142,11 @@ public void increaseThirst(int thirst) { * @return Level of the nutrient */ public int getNutrient(Nutrient nutrient) { - switch (nutrient) { - case PROTEIN: - return proteins; - case CARBS: - return carbs; - case SALTS: - return salts; - default: - throw new IllegalArgumentException("Unexpected value: " + nutrient); - } + return switch (nutrient) { + case PROTEIN -> proteins; + case CARBS -> carbs; + case VITAMINS -> vitamins; + }; } /** @@ -144,13 +158,13 @@ public int getNutrient(Nutrient nutrient) { public void setNutrient(Nutrient nutrient, int value) { switch (nutrient) { case PROTEIN: - this.proteins = Math.clamp(value, 0, this.max_proteins); + this.proteins = Math.clamp(value, 0, this.config.mechanics_food_max_level); break; case CARBS: - this.carbs = Math.clamp(value, 0, this.max_carbs); + this.carbs = Math.clamp(value, 0, this.config.mechanics_food_max_level); break; - case SALTS: - this.salts = Math.clamp(value, 0, this.max_salts); + case VITAMINS: + this.vitamins = Math.clamp(value, 0, this.config.mechanics_food_max_level); break; default: throw new IllegalArgumentException("Unexpected value: " + nutrient); @@ -162,30 +176,39 @@ public void setNutrient(Nutrient nutrient, int value) { * * @param carbs Level of carbs to set * @param proteins Level of proteins to set - * @param salts Level of salts to set + * @param vitamins Level of vitamins to set */ - public void setNutrients(int carbs, int proteins, int salts) { + public void setNutrients(int carbs, int proteins, int vitamins) { setNutrient(Nutrient.CARBS, carbs); setNutrient(Nutrient.PROTEIN, proteins); - setNutrient(Nutrient.SALTS, salts); + setNutrient(Nutrient.VITAMINS, vitamins); } /** * Increase a nutrient for this data * * @param nutrient Nutrient to increase - * @param value Level of increase + * @param change Level of increase */ - public void increaseNutrient(Nutrient nutrient, int value) { + public void increaseNutrient(Nutrient nutrient, int change) { + if (change < 0) { + int immunityMinutes = this.config.mechanics_food_immunity_minutes; + if (this.bypasses.get(Info.NUTRIENTS)) { + return; + } else if (immunityMinutes > 0) { + int secondsPlayed = this.player.getStatistic(Statistic.PLAY_ONE_MINUTE) / 20 / 60; + if (immunityMinutes > secondsPlayed) return; + } + } switch (nutrient) { case PROTEIN: - this.proteins = Math.clamp(this.proteins + value, 0, this.max_proteins); + this.proteins = Math.clamp(this.proteins + change, 0, this.config.mechanics_food_max_level); break; case CARBS: - this.carbs = Math.clamp(this.carbs + value, 0, this.max_carbs); + this.carbs = Math.clamp(this.carbs + change, 0, this.config.mechanics_food_max_level); break; - case SALTS: - this.salts = Math.clamp(this.salts + value, 0, this.max_salts); + case VITAMINS: + this.vitamins = Math.clamp(this.vitamins + change, 0, this.config.mechanics_food_max_level); break; default: throw new IllegalArgumentException("Unexpected value: " + nutrient); @@ -214,10 +237,21 @@ public void setEnergy(double energy) { /** * Increase the energy level for this data * - * @param energy Energy amount to increase + * @param change Energy amount to increase */ - public void increaseEnergy(double energy) { - setEnergy(this.energy + energy); + public void increaseEnergy(double change) { + if (change < 0) { + int immunityMinutes = this.config.mechanics_energy_immunity_minutes; + if (this.bypasses.get(Info.ENERGY)) { + return; + } else if (immunityMinutes > 0) { + int secondsPlayed = this.player.getStatistic(Statistic.PLAY_ONE_MINUTE) / 20 / 60; + if (immunityMinutes > secondsPlayed) return; + } + } + EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, change, getEnergy() + change); + if (!energyEvent.callEvent()) return; + setEnergy(this.energy + change); } /** @@ -261,26 +295,17 @@ public void setStat(Stat stat, int value) { * @return Value of stat */ public int getStat(Stat stat) { - switch (stat) { - case CHARGE: - return this.charge; - case CHARGING: - return this.charging; - case SPIN: - return this.spin; - case DUAL_WIELD: - return this.dualWield; - case HEALING: - return this.healing; - case HEAL_TIMES: - return this.healTimes; - case RECURVE_FIRING: - return this.recurveFiring; - case RECURVE_COOLDOWN: - return this.recurveCooldown; - default: - throw new IllegalArgumentException("Unexpected value: " + stat); - } + return switch (stat) { + case CHARGE -> this.charge; + case CHARGING -> this.charging; + case SPIN -> this.spin; + case DUAL_WIELD -> this.dualWield; + case HEALING -> this.healing; + case HEAL_TIMES -> this.healTimes; + case RECURVE_FIRING -> this.recurveFiring; + case RECURVE_COOLDOWN -> this.recurveCooldown; + default -> throw new IllegalArgumentException("Unexpected value: " + stat); + }; } /** @@ -308,18 +333,12 @@ public boolean isLocalChat() { * @return True if this info is displayed on the player's scoreboard */ public boolean isInfoDisplayed(Info info) { - switch (info) { - case HUNGER: - return score_hunger; - case THIRST: - return score_thirst; - case ENERGY: - return score_energy; - case NUTRIENTS: - return score_nutrients; - default: - throw new IllegalArgumentException("Unexpected value: " + info); - } + return switch (info) { + case HUNGER -> this.score_hunger; + case THIRST -> this.score_thirst; + case ENERGY -> this.score_energy; + case NUTRIENTS -> this.score_nutrients; + }; } /** @@ -372,11 +391,11 @@ public void setInfoDisplayed(boolean hunger, boolean thirst, boolean energy, boo public void setCompassWaypoint(Location location) { World world = location.getWorld(); if (world == null) return; - if (!config.MECHANICS_COMPASS_WAYPOINT_WORLDS) { + if (!this.config.mechanics_compass_waypoint_worlds) { this.compassMap.clear(); } this.compassMap.put(world.getName(), location); - getPlayer().setCompassTarget(location); + this.player.setCompassTarget(location); } /** @@ -385,53 +404,53 @@ public void setCompassWaypoint(Location location) { * @param world World to grab waypoint from * @return Location of waypoint */ - @NotNull public Location getCompassWaypoint(World world) { if (this.compassMap.containsKey(world.getName())) { return this.compassMap.get(world.getName()); } - return world.getSpawnLocation(); + return null; } /** - * Internal serializer for yaml config - * - * @return Map for config + * @hidden */ @SuppressWarnings("NullableProblems") @Override public Map serialize() { Map result = new LinkedHashMap<>(); - result.put("uuid", uuid.toString()); - result.put("thirst", thirst); - result.put("energy", energy); - result.put("nutrients.proteins", proteins); - result.put("nutrients.carbs", carbs); - result.put("nutrients.salts", salts); - result.put("local-chat", localChat); - result.put("score.hunger", score_hunger); - result.put("score.thirst", score_thirst); - result.put("score.energy", score_energy); - result.put("score.nutrients", score_nutrients); - result.put("compass", compassMap); + result.put("uuid", this.uuid.toString()); + result.put("thirst", this.thirst); + result.put("energy", this.energy); + result.put("nutrients.proteins", this.proteins); + result.put("nutrients.carbs", this.carbs); + result.put("nutrients.vitamins", this.vitamins); + result.put("local-chat", this.localChat); + result.put("score.hunger", this.score_hunger); + result.put("score.thirst", this.score_thirst); + result.put("score.energy", this.score_energy); + result.put("score.nutrients", this.score_nutrients); + result.put("compass", this.compassMap); return result; } /** - * Internal deserializer for yaml config - * - * @param args Args from yaml config - * @return New PlayerData loaded from config + * @hidden */ + @SuppressWarnings("unchecked") public static PlayerData deserialize(Map args) { UUID uuid = UUID.fromString(args.get("uuid").toString()); - int thirst = ((Integer) args.get("thirst")); + double thirst = getDouble(args, "thirst", 20.0); double energy = getDouble(args, "energy", 20.0); - int proteins = ((Integer) args.get("nutrients.proteins")); - int carbs = ((Integer) args.get("nutrients.carbs")); - int salts = ((Integer) args.get("nutrients.salts")); + int proteins = getInt(args, "nutrients.proteins", 500); + int carbs = getInt(args, "nutrients.carbs", 500); + int vitamins = getInt(args, "nutrients.vitamins", 500); + + Player player = Bukkit.getPlayer(uuid); + if (player == null) { + throw new IllegalArgumentException("Player not found for uuid: " + uuid); + } - PlayerData data = new PlayerData(uuid, thirst, proteins, carbs, salts, energy); + PlayerData data = new PlayerData(player, thirst, proteins, carbs, vitamins, energy); boolean localChat = getBool(args, "local-chat", false); data.setLocalChat(localChat); @@ -443,7 +462,6 @@ public static PlayerData deserialize(Map args) { data.setInfoDisplayed(score_hunger, score_thirst, score_energy, score_nutrients); if (args.containsKey("compass")) { - //noinspection unchecked data.compassMap = (Map) args.get("compass"); } @@ -476,8 +494,7 @@ private static boolean getBool(Map args, String val, boolean def * @return Hunger level from this player data */ public double getHunger() { - Player player = getPlayer(); - return player.getFoodLevel() + player.getSaturation(); + return this.player.getFoodLevel() + this.player.getSaturation(); } /** @@ -498,9 +515,8 @@ public void setHunger(double hunger) { } else if (hunger >= 0) { hun = hunger; } - Player player = getPlayer(); - player.setFoodLevel((int) hun); - player.setSaturation((float) sat); + this.player.setFoodLevel((int) hun); + this.player.setSaturation((float) sat); } /** @@ -523,8 +539,8 @@ public void setData(DataType type, Number value) { case CARBS: setNutrient(Nutrient.CARBS, value.intValue()); break; - case SALTS: - setNutrient(Nutrient.SALTS, value.intValue()); + case VITAMINS: + setNutrient(Nutrient.VITAMINS, value.intValue()); break; case HUNGER: setHunger(value.doubleValue()); @@ -541,29 +557,21 @@ public void setData(DataType type, Number value) { * @return Value from this player data */ public double getData(DataType type) { - switch (type) { - case THIRST: - return getThirst(); - case ENERGY: - return getEnergy(); - case PROTEINS: - return getNutrient(Nutrient.PROTEIN); - case CARBS: - return getNutrient(Nutrient.CARBS); - case SALTS: - return getNutrient(Nutrient.SALTS); - case HUNGER: - return getHunger(); - default: - throw new IllegalArgumentException("Unknown type: " + type); - } + return switch (type) { + case THIRST -> getThirst(); + case ENERGY -> getEnergy(); + case PROTEINS -> getNutrient(Nutrient.PROTEIN); + case CARBS -> getNutrient(Nutrient.CARBS); + case VITAMINS -> getNutrient(Nutrient.VITAMINS); + case HUNGER -> getHunger(); + }; } public enum DataType { THIRST, ENERGY, PROTEINS, - SALTS, + VITAMINS, CARBS, HUNGER; diff --git a/src/main/java/tk/shanebee/survival/data/Stat.java b/src/main/java/com/shanebeestudios/survival/api/data/Stat.java similarity index 78% rename from src/main/java/tk/shanebee/survival/data/Stat.java rename to src/main/java/com/shanebeestudios/survival/api/data/Stat.java index fcd54b5..67b08a4 100644 --- a/src/main/java/tk/shanebee/survival/data/Stat.java +++ b/src/main/java/com/shanebeestudios/survival/api/data/Stat.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.data; +package com.shanebeestudios.survival.api.data; /** * Player stat types diff --git a/src/main/java/com/shanebeestudios/survival/api/data/package-info.java b/src/main/java/com/shanebeestudios/survival/api/data/package-info.java new file mode 100644 index 0000000..e4d24bf --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/data/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes for holding data + */ +package com.shanebeestudios.survival.api.data; diff --git a/src/main/java/tk/shanebee/survival/events/EnergyLevelChangeEvent.java b/src/main/java/com/shanebeestudios/survival/api/events/EnergyLevelChangeEvent.java similarity index 88% rename from src/main/java/tk/shanebee/survival/events/EnergyLevelChangeEvent.java rename to src/main/java/com/shanebeestudios/survival/api/events/EnergyLevelChangeEvent.java index 5d5a396..1da955a 100644 --- a/src/main/java/tk/shanebee/survival/events/EnergyLevelChangeEvent.java +++ b/src/main/java/com/shanebeestudios/survival/api/events/EnergyLevelChangeEvent.java @@ -1,9 +1,10 @@ -package tk.shanebee.survival.events; +package com.shanebeestudios.survival.api.events; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; /** * Called when a player's energy level changes @@ -20,7 +21,7 @@ public class EnergyLevelChangeEvent extends Event implements Cancellable { public EnergyLevelChangeEvent(Player player, double changed, double level) { this.player = player; this.changed = changed; - this.level = level; + this.level = Math.clamp(level, 0, 20); this.isCancelled = false; } @@ -49,7 +50,7 @@ public static HandlerList getHandlerList() { return handlers; } @Override - public HandlerList getHandlers() { + public @NotNull HandlerList getHandlers() { return handlers; } diff --git a/src/main/java/tk/shanebee/survival/events/ShootRecurvedBowEvent.java b/src/main/java/com/shanebeestudios/survival/api/events/ShootRecurvedBowEvent.java similarity index 87% rename from src/main/java/tk/shanebee/survival/events/ShootRecurvedBowEvent.java rename to src/main/java/com/shanebeestudios/survival/api/events/ShootRecurvedBowEvent.java index b0248c9..134ea10 100644 --- a/src/main/java/tk/shanebee/survival/events/ShootRecurvedBowEvent.java +++ b/src/main/java/com/shanebeestudios/survival/api/events/ShootRecurvedBowEvent.java @@ -1,11 +1,12 @@ -package tk.shanebee.survival.events; +package com.shanebeestudios.survival.api.events; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.item.Item; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.Items; /** * Called when a player shoots a recurved bow/crossbow @@ -41,7 +42,7 @@ public ItemStack getItemStack() { } /** Get the custom Items type the player shoot - * @return The player's main hand {@link Item} type + * @return The player's main hand {@link Items} type */ public Item getItem() { return this.item; diff --git a/src/main/java/com/shanebeestudios/survival/api/events/ThirstLevelChangeEvent.java b/src/main/java/com/shanebeestudios/survival/api/events/ThirstLevelChangeEvent.java new file mode 100644 index 0000000..0abb5d7 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/events/ThirstLevelChangeEvent.java @@ -0,0 +1,74 @@ +package com.shanebeestudios.survival.api.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * Called when a player's thirst level changes + */ +@SuppressWarnings("unused") +public class ThirstLevelChangeEvent extends Event implements Cancellable { + + private final static HandlerList handlers = new HandlerList(); + private final Player player; + private final double thirst; + private final double changed; + private boolean isCancelled; + + public ThirstLevelChangeEvent(Player player, double changed, double thirst) { + this.player = player; + this.changed = changed; + this.thirst = Math.clamp(thirst, 0, 40); + this.isCancelled = false; + } + + /** + * Get the player involved in this event + * + * @return The player involved in this event + */ + public Player getPlayer() { + return this.player; + } + + /** + * Get the new thirst level from the event + * + * @return The new thirst level from the event + */ + public double getThirst() { + return this.thirst; + } + + /** + * Get the level of thirst that was changed + * + * @return The level that was changed + */ + public double getChanged() { + return this.changed; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + +} diff --git a/src/main/java/tk/shanebee/survival/events/WaterBowlFillEvent.java b/src/main/java/com/shanebeestudios/survival/api/events/WaterBowlFillEvent.java similarity index 95% rename from src/main/java/tk/shanebee/survival/events/WaterBowlFillEvent.java rename to src/main/java/com/shanebeestudios/survival/api/events/WaterBowlFillEvent.java index 802e1e5..d41afa2 100644 --- a/src/main/java/tk/shanebee/survival/events/WaterBowlFillEvent.java +++ b/src/main/java/com/shanebeestudios/survival/api/events/WaterBowlFillEvent.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.events; +package com.shanebeestudios.survival.api.events; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; diff --git a/src/main/java/com/shanebeestudios/survival/api/events/package-info.java b/src/main/java/com/shanebeestudios/survival/api/events/package-info.java new file mode 100644 index 0000000..efdea6d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/events/package-info.java @@ -0,0 +1,4 @@ +/** + * {@link org.bukkit.event.Event Events} other plugins can listen to + */ +package com.shanebeestudios.survival.api.events; diff --git a/src/main/java/com/shanebeestudios/survival/api/generator/TagFileGenerator.java b/src/main/java/com/shanebeestudios/survival/api/generator/TagFileGenerator.java new file mode 100644 index 0000000..854da57 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/generator/TagFileGenerator.java @@ -0,0 +1,399 @@ +package com.shanebeestudios.survival.api.generator; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import io.papermc.paper.registry.keys.tags.BlockTypeTagKeys; +import io.papermc.paper.registry.keys.tags.ItemTypeTagKeys; +import org.bukkit.Keyed; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.Tag; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +@SuppressWarnings({"UnstableApiUsage", "UnusedReturnValue", "SameParameterValue"}) +public class TagFileGenerator { + + private final File dataFolder; + + public TagFileGenerator(SurvivalPlugin plugin) { + this.dataFolder = plugin.getDataFolder(); + } + + public void generate() { + generateBlockTags(this.dataFolder, "generated/block-tags.yml"); + generateItemTags(this.dataFolder, "generated/item-tags.yml"); + generateEnchantmentTags(this.dataFolder, "generated/enchantment-tags.yml"); + } + + private FileConfiguration generateBlockTags(File pluginDataFolder, String path) { + File file = new File(pluginDataFolder, path); + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + + List header = new ArrayList<>(); + + header.add("Block Tags"); + header.add("This file is used to create some tags the plugin uses."); + header.add("Modify this to your liking but be very careful when you do."); + header.add(" "); + header.add("This accepts both Minecraft block types `minecraft:stone`"); + header.add("and block tags prefixed with `#`, ex: `#minecraft:logs` (minecraft or custom)"); + header.add(" "); + header.add("The names of these sections double as namespaces."); + header.add("The `survival_plus` section will create new tags"); + header.add("Example `requires_shovel` = `survival_plus:requires_shovel`"); + header.add(" "); + header.add("You can optionally add a `minecraft` section to add blocks to current Minecraft tags"); + header.add("Example (This would add oak_stairs to the `minecraft:logs` tag):"); + header.add("minecraft:"); + header.add(" logs:"); + header.add(" - minecraft:oak_stairs"); + config.options().setHeader(header); + + ConfigurationSection blocks = config.getConfigurationSection("survival_plus"); + if (blocks == null) blocks = config.createSection("survival_plus"); + + createConcreteTag(blocks); + createCookingBlockTag(blocks); + createGlazedTerracottaTag(blocks); + createOresTag(blocks); + createOreTypeBlockTag(blocks); + createStoneTypeTag(blocks); + createStorageBlockTag(blocks); + createUtilityBlockTag(blocks); + + createRequiresAxeTag(blocks); + createRequiresPickaxeTag(blocks); + createRequiresShovelTag(blocks); + createRequiresShearsTag(blocks); + createRequiresSickleTag(blocks); + createRequiresHammerTag(blocks); + + try { + config.save(file); + return config; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private FileConfiguration generateItemTags(File pluginDataFolder, String path) { + File file = new File(pluginDataFolder, path); + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + + List header = new ArrayList<>(); + + header.add("Items Tags"); + header.add("This file is used to create some tags the plugin uses."); + header.add("Modify this to your liking but be very careful when you do."); + header.add(" "); + header.add("This accepts both Minecraft item types `minecraft:diamond_sword`"); + header.add("and item tags prefixed with `#`, ex: `#minecraft:swords` (minecraft or custom)"); + header.add(" "); + header.add("The names of these sections double as namespaces."); + header.add("The `survival_plus` section will create new tags"); + header.add("Example `prevent_duel_wield` = `survival_plus:prevent_duel_wield`"); + header.add(" "); + header.add("You can optionally add a `minecraft` section to add items to current Minecraft tags"); + header.add("Example (This would add stick to the `minecraft:swords` tag):"); + header.add("minecraft:"); + header.add(" swords:"); + header.add(" - minecraft:stick"); + config.options().setHeader(header); + + ConfigurationSection items = config.getConfigurationSection("survival_plus"); + if (items == null) items = config.createSection("survival_plus"); + + createDualWieldTag(items); + + try { + config.save(file); + return config; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private FileConfiguration generateEnchantmentTags(File pluginDataFolder, String path) { + File file = new File(pluginDataFolder, path); + FileConfiguration config = YamlConfiguration.loadConfiguration(file); + + List header = new ArrayList<>(); + + header.add("Enchantment Tags"); + header.add("This file is used to create some tags the plugin uses."); + header.add("Modify this to your liking but be very careful when you do."); + header.add(" "); + header.add("This accepts both Minecraft enchantment types `minecraft:sharpness`"); + header.add("and enchantment tags prefixed with `#`, ex: `#minecraft:curse` (minecraft or custom)"); + header.add(" "); + header.add("The names of these sections double as namespaces."); + header.add("The `survival_plus` section will create new tags"); + header.add("The `minecraft` section will add to vanilla Minecraft enchantment tags."); + config.options().setHeader(header); + + ConfigurationSection enchantments = config.getConfigurationSection("minecraft"); + if (enchantments == null) enchantments = config.createSection("minecraft"); + + createInEnchantmentTableTag(enchantments); + + try { + config.save(file); + return config; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + // Block Tags + private void createGlazedTerracottaTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + Registry.BLOCK.stream().map(Keyed::getKey) + .sorted(Comparator.comparing(NamespacedKey::toString)) + .toList().forEach(namespacedKey -> { + String key = namespacedKey.toString(); + if (key.endsWith("_glazed_terracotta")) blocks.add(key); + }); + section.set("glazed_terracotta", blocks); + } + + private void createConcreteTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + Registry.BLOCK.stream().map(Keyed::getKey) + .sorted(Comparator.comparing(NamespacedKey::toString)) + .toList().forEach(namespacedKey -> { + String key = namespacedKey.toString(); + if (key.endsWith("_concrete")) blocks.add(key); + }); + section.set("concrete", blocks); + } + + private void createStoneTypeTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + blocks.add("minecraft:stone"); + blocks.add("minecraft:cobblestone"); + blocks.add("minecraft:mossy_cobblestone"); + blocks.add("minecraft:infested_cobblestone"); + blocks.add("minecraft:andesite"); + blocks.add("minecraft:polished_andesite"); + blocks.add("minecraft:diorite"); + blocks.add("minecraft:polished_diorite"); + blocks.add("minecraft:granite"); + blocks.add("minecraft:polished_granite"); + blocks.add("minecraft:bricks"); + blocks.add("minecraft:nether_bricks"); + blocks.add("minecraft:sandstone"); + blocks.add("minecraft:chiseled_sandstone"); + blocks.add("minecraft:smooth_sandstone"); + blocks.add("minecraft:cut_sandstone"); + blocks.add("minecraft:red_sandstone"); + blocks.add("minecraft:chiseled_red_sandstone"); + blocks.add("minecraft:cut_red_sandstone"); + blocks.add("minecraft:smooth_red_sandstone"); + blocks.add("minecraft:prismarine"); + blocks.add("minecraft:prismarine_bricks"); + blocks.add("minecraft:dark_prismarine"); + blocks.add("minecraft:netherrack"); + blocks.add("minecraft:end_stone"); + blocks.add("minecraft:end_stone_bricks"); + blocks.add("minecraft:purpur_block"); + blocks.add("minecraft:purpur_pillar"); + // nether blocks + blocks.add("minecraft:basalt"); + blocks.add("minecraft:polished_basalt"); + blocks.add("minecraft:blackstone"); + blocks.add("minecraft:polished_blackstone"); + blocks.add("minecraft:chiseled_polished_blackstone"); + blocks.add("minecraft:chiseled_nether_bricks"); + blocks.add("minecraft:cracked_nether_bricks"); + blocks.add("minecraft:quartz_bricks"); + + section.set("stone_type", blocks); + } + + private void createCookingBlockTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + blocks.add("minecraft:furnace"); + blocks.add("minecraft:blast_furnace"); + blocks.add("minecraft:smoker"); + section.set("cooking_block", blocks); + } + + private void createStorageBlockTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + + blocks.add("#" + BlockTypeTagKeys.SHULKER_BOXES.key()); + blocks.add("minecraft:chest"); + blocks.add("minecraft:ender_chest"); + blocks.add("minecraft:trapped_chest"); + blocks.add("minecraft:barrel"); + + section.set("storage_block", blocks); + } + + private void createUtilityBlockTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + + blocks.add("minecraft:cartography_table"); + blocks.add("minecraft:fletching_table"); + blocks.add("minecraft:lectern"); + blocks.add("minecraft:loom"); + blocks.add("minecraft:stonecutter"); + blocks.add("minecraft:grindstone"); + blocks.add("minecraft:smithing_table"); + blocks.add("minecraft:anvil"); + blocks.add("minecraft:enchanting_table"); + blocks.add("minecraft:jukebox"); + blocks.add("minecraft:note_block"); + blocks.add("minecraft:brewing_stand"); + blocks.add("minecraft:cauldron"); + blocks.add("minecraft:composter"); + blocks.add("minecraft:respawn_anchor"); + blocks.add("minecraft:lodestone"); + + section.set("utility_block", blocks); + } + + private void createOreTypeBlockTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + + blocks.add("minecraft:coal_block"); + blocks.add("minecraft:diamond_block"); + blocks.add("minecraft:emerald_block"); + blocks.add("minecraft:gold_block"); + blocks.add("minecraft:iron_block"); + blocks.add("minecraft:lapis_block"); + blocks.add("minecraft:quartz_block"); + blocks.add("minecraft:redstone_block"); + blocks.add("minecraft:netherite_block"); + + section.set("ore_type_block", blocks); + } + + private void createOresTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + Registry.BLOCK.stream().map(Keyed::getKey) + .sorted(Comparator.comparing(NamespacedKey::toString)) + .toList().forEach(namespacedKey -> { + String key = namespacedKey.toString(); + if (key.endsWith("_ore")) blocks.add(key); + }); + + section.set("ores", blocks); + } + + private void createRequiresSickleTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + + blocks.add("#" + BlockTypeTagKeys.CROPS.key()); + + blocks.add("minecraft:melon"); + blocks.add("minecraft:pumpkin"); + blocks.add("minecraft:chorus_flower"); + blocks.add("minecraft:chorus_plant"); + blocks.add("minecraft:sweet_berry_bush"); + blocks.add("minecraft:cocoa"); + + section.set("requires_sickle", blocks); + section.setInlineComments("requires_sickle", List.of("Blocks which require a sickle to break.")); + + } + + private void createRequiresAxeTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + for (Material value : Tag.MINEABLE_AXE.getValues().stream().sorted(Comparator.comparing(material -> material.getKey().toString())).toList()) { + if (Tag.REPLACEABLE.isTagged(value)) continue; + if (Tag.CROPS.isTagged(value)) continue; + if (Tag.SWORD_EFFICIENT.isTagged(value)) continue; + blocks.add(value.getKey().toString()); + } + section.set("requires_axe", blocks); + section.setInlineComments("requires_axe", List.of("Blocks which require an axe to break.")); + + } + + private void createRequiresPickaxeTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + blocks.add("#" + BlockTypeTagKeys.MINEABLE_PICKAXE.key()); + section.set("requires_pickaxe", blocks); + section.setInlineComments("requires_pickaxe", List.of("Blocks which require a pickaxe to break.")); + + } + + private void createRequiresShovelTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + blocks.add("#" + BlockTypeTagKeys.MINEABLE_SHOVEL.key()); + section.set("requires_shovel", blocks); + section.setInlineComments("requires_shovel", List.of("Blocks which require a shovel to break.")); + + } + + private void createRequiresShearsTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + blocks.add(Material.COBWEB.getKey().toString()); + blocks.add(Material.TRIPWIRE.getKey().toString()); + blocks.add(Material.TNT.getKey().toString()); + blocks.add(Material.MUSHROOM_STEM.getKey().toString()); + section.set("requires_shears", blocks); + section.setInlineComments("requires_shears", List.of("Blocks which require shears to break.")); + } + + private void createRequiresHammerTag(@NotNull ConfigurationSection section) { + List blocks = new ArrayList<>(); + blocks.add("#" + BlockTypeTagKeys.FENCE_GATES.key()); + blocks.add("#" + BlockTypeTagKeys.TERRACOTTA.key()); + blocks.add("#" + BlockTypeTagKeys.SHULKER_BOXES.key()); + blocks.add("#" + BlockTypeTagKeys.BEDS.key()); + blocks.add("#" + BlockTypeTagKeys.LOGS.key()); + blocks.add("#" + BlockTypeTagKeys.STAIRS.key()); + blocks.add("#" + BlockTypeTagKeys.SLABS.key()); + blocks.add("#" + BlockTypeTagKeys.PLANKS.key()); + blocks.add("#" + BlockTypeTagKeys.WOODEN_PRESSURE_PLATES.key()); + blocks.add("#" + BlockTypeTagKeys.WOODEN_FENCES.key()); + blocks.add("#" + BlockTypeTagKeys.RAILS.key()); + blocks.add("#" + BlockTypeTagKeys.BANNERS.key()); + blocks.add("#" + BlockTypeTagKeys.FENCES.key()); + blocks.add("#" + BlockTypeTagKeys.SIGNS.key()); + + blocks.add("#survival_plus:glazed_terracotta"); + blocks.add("#survival_plus:concrete"); + blocks.add("#survival_plus:stone_type"); + blocks.add("#survival_plus:cooking_block"); + blocks.add("#survival_plus:storage_block"); + blocks.add("#survival_plus:utility_block"); + blocks.add("#survival_plus:ore_type_block"); + + section.set("requires_hammer", blocks); + section.setInlineComments("requires_hammer", List.of("Blocks which require a hammer to place.")); + } + + // ItemTags + private void createDualWieldTag(@NotNull ConfigurationSection section) { + List items = new ArrayList<>(); + items.add("#" + ItemTypeTagKeys.AXES.key()); + items.add("#" + ItemTypeTagKeys.PICKAXES.key()); + items.add("#" + ItemTypeTagKeys.HOES.key()); + items.add("#" + ItemTypeTagKeys.SHOVELS.key()); + items.add("#" + ItemTypeTagKeys.SWORDS.key()); + + section.set("prevent_dual_wield", items); + section.setInlineComments("prevent_dual_wield", List.of("Items which cannot dual wield with legendary tools.")); + } + + // Enchantment Tags + private void createInEnchantmentTableTag(@NotNull ConfigurationSection section) { + List enchantments = new ArrayList<>(); + enchantments.add("survival_plus:building_reach"); + section.set("in_enchanting_table", enchantments); + section.setInlineComments("in_enchanting_table", List.of("Custom enchantments which can be used in the enchanting table.")); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/generator/package-info.java b/src/main/java/com/shanebeestudios/survival/api/generator/package-info.java new file mode 100644 index 0000000..6efdd08 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/generator/package-info.java @@ -0,0 +1,4 @@ +/** + * Generators for generating data + */ +package com.shanebeestudios.survival.api.generator; diff --git a/src/main/java/com/shanebeestudios/survival/api/goals/AngryWolfGoal.java b/src/main/java/com/shanebeestudios/survival/api/goals/AngryWolfGoal.java new file mode 100644 index 0000000..c0554b3 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/goals/AngryWolfGoal.java @@ -0,0 +1,123 @@ +package com.shanebeestudios.survival.api.goals; + +import com.destroystokyo.paper.entity.ai.Goal; +import com.destroystokyo.paper.entity.ai.GoalKey; +import com.destroystokyo.paper.entity.ai.GoalType; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import io.papermc.paper.registry.TypedKey; +import io.papermc.paper.registry.tag.Tag; +import io.papermc.paper.registry.tag.TagKey; +import net.kyori.adventure.key.Key; +import org.bukkit.GameMode; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wolf; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.PlayerInventory; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumSet; +import java.util.Optional; + +@SuppressWarnings({"UnstableApiUsage", "NullableProblems"}) +public class AngryWolfGoal implements Goal<@NotNull Wolf> { + + public enum Type { + ALWAYS(), + NIGHT(), + DISABLED(); + + public static Type getByKey(String key) { + return switch (key) { + case "always" -> ALWAYS; + case "night" -> NIGHT; + default -> DISABLED; + }; + } + } + + private static final Registry ITEM_REGISTRY = RegistryAccess.registryAccess().getRegistry(RegistryKey.ITEM); + + @SuppressWarnings("DataFlowIssue") + private static final GoalKey<@NotNull Wolf> GOAL_KEY = GoalKey.of(Wolf.class, NamespacedKey.fromString("survival_plus:angry_wolf_goal")); + + private final Wolf wolf; + private final Type type; + private Player target; + private @Nullable Tag foodTag; + + @SuppressWarnings("PatternValidation") + public AngryWolfGoal(Wolf wolf, Type type) { + this.wolf = wolf; + this.type = type; + TagKey tagKey = TagKey.create(RegistryKey.ITEM, Key.key(wolf.getType().key() + "_food")); + if (ITEM_REGISTRY.hasTag(tagKey)) { + this.foodTag = ITEM_REGISTRY.getTag(tagKey); + } + } + + @Override + public boolean shouldActivate() { + // Minecraft uses this to decide if the mob should random stroll + // If they can't, they're further than 32 blocks from a player + // No need to check for players close by + if (this.wolf.getNoActionTicks() > 100) return false; + + if (this.wolf.isAngry()) return false; // He's already angry + if (this.type == Type.NIGHT && this.wolf.getWorld().isDayTime()) return false; + + Optional any = this.wolf.getLocation().getNearbyPlayers(10, 7, 10, + p -> p.getGameMode() == GameMode.SURVIVAL || p.getGameMode() == GameMode.ADVENTURE) + .stream().findAny(); + if (any.isEmpty()) return false; + + this.target = any.get(); + return shouldAttack(); + } + + private boolean shouldAttack() { + if (this.wolf.isTamed()) return false; + if (this.type == Type.NIGHT && this.wolf.getWorld().isDayTime()) return false; + if (this.wolf.getLocation().distanceSquared(this.target.getLocation()) > (10 * 10)) return false; + + if (this.foodTag != null) { + PlayerInventory inventory = this.target.getInventory(); + TypedKey hand = TypedKey.create(RegistryKey.ITEM, inventory.getItemInMainHand().getType().key()); + TypedKey off = TypedKey.create(RegistryKey.ITEM, inventory.getItemInOffHand().getType().key()); + return !this.foodTag.contains(hand) && !this.foodTag.contains(off); + } + return true; + } + + @Override + public boolean shouldStayActive() { + return shouldAttack(); + } + + @Override + public void start() { + this.wolf.setTarget(this.target); + this.wolf.setAngry(true); + } + + @Override + public void stop() { + this.target = null; + this.wolf.setAngry(false); + this.wolf.setTarget(null); + } + + @Override + public @NotNull GoalKey<@NotNull Wolf> getKey() { + return GOAL_KEY; + } + + @Override + public @NotNull EnumSet getTypes() { + return EnumSet.of(GoalType.TARGET); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/goals/AvoidPlayerGoal.java b/src/main/java/com/shanebeestudios/survival/api/goals/AvoidPlayerGoal.java new file mode 100644 index 0000000..0b370c8 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/goals/AvoidPlayerGoal.java @@ -0,0 +1,145 @@ +package com.shanebeestudios.survival.api.goals; + +import com.destroystokyo.paper.entity.Pathfinder; +import com.destroystokyo.paper.entity.ai.Goal; +import com.destroystokyo.paper.entity.ai.GoalKey; +import com.destroystokyo.paper.entity.ai.GoalType; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import io.papermc.paper.registry.TypedKey; +import io.papermc.paper.registry.tag.Tag; +import io.papermc.paper.registry.tag.TagKey; +import net.kyori.adventure.key.Key; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.Statistic; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.EnumSet; +import java.util.Optional; +import java.util.Random; + +@SuppressWarnings({"NullableProblems", "UnstableApiUsage"}) +public class AvoidPlayerGoal implements Goal<@NotNull Mob> { + + private static final Registry ITEM_REGISTRY = RegistryAccess.registryAccess().getRegistry(RegistryKey.ITEM); + + @SuppressWarnings("DataFlowIssue") + private static final GoalKey<@NotNull Mob> GOAL_KEY = GoalKey.of(Mob.class, NamespacedKey.fromString("survival_plus:avoid_player_goal")); + + private final Random random = new Random(); + private final Mob mob; + private Player avoid; + private Pathfinder pathfinder; + private Pathfinder.PathResult path; + private @Nullable Tag foodTag; + private double speed = 1.6; + + @SuppressWarnings("PatternValidation") + public AvoidPlayerGoal(Mob mob) { + this.mob = mob; + this.pathfinder = mob.getPathfinder(); + TagKey tagKey = TagKey.create(RegistryKey.ITEM, Key.key(mob.getType().key() + "_food")); + if (ITEM_REGISTRY.hasTag(tagKey)) { + this.foodTag = ITEM_REGISTRY.getTag(tagKey); + } + } + + @Override + public boolean shouldActivate() { + // Minecraft uses this to decide if the mob should random stroll + // If they can't, they're further than 32 blocks from a player + // No need to check for players close by + if (this.mob.getNoActionTicks() > 100) return false; + + Optional any = this.mob.getLocation().getNearbyPlayers(7, 7, 7, + p -> p.getGameMode() == GameMode.SURVIVAL || p.getGameMode() == GameMode.ADVENTURE) + .stream().findAny(); + if (any.isEmpty()) return false; + + this.avoid = any.get(); + if (!shouldAvoid()) return false; + this.pathfinder = this.mob.getPathfinder(); + // TODO paper bug causes this to error +// if (this.mob instanceof Animals animal && !animal.isAdult()) { +// Goal goal = Bukkit.getMobGoals().getGoal(animal, VanillaGoal.FOLLOW_PARENT); +// if (goal != null) { +// goal.stop(); +// Optional parent = this.mob.getNearbyEntities(10, 4, 10).stream().filter(entity -> entity != this.mob +// && entity.getType() == this.mob.getType()).findFirst(); +// if (parent.isPresent()) { +// Pathfinder.PathResult pathToParent = this.pathfinder.findPath(parent.get().getLocation()); +// if (pathToParent != null) { +// this.path = pathToParent; +// return true; +// } +// } +// } +// } + Location mobLoc = this.mob.getLocation(); + Vector direction = mobLoc.toVector().subtract(this.avoid.getLocation().toVector()).normalize().multiply(10); + Location newLoc = mobLoc.add(direction); + int x = random.nextInt(2, 5); + int z = random.nextInt(2, 5); + x = random.nextBoolean() ? x : -x; + z = random.nextBoolean() ? z : -z; + Location add = newLoc.add(x, 0, z).getWorld().getHighestBlockAt(newLoc).getLocation().add(0, 1, 0); + this.path = this.pathfinder.findPath(add); + return this.path != null; + } + + private boolean shouldAvoid() { + if (this.avoid instanceof Player player && this.foodTag != null) { + PlayerInventory inventory = player.getInventory(); + TypedKey hand = TypedKey.create(RegistryKey.ITEM, inventory.getItemInMainHand().getType().key()); + TypedKey off = TypedKey.create(RegistryKey.ITEM, inventory.getItemInOffHand().getType().key()); + return !this.foodTag.contains(hand) && !this.foodTag.contains(off); + } + return !this.avoid.isSneaking(); + } + + @Override + public boolean shouldStayActive() { + int statistic = this.avoid.getStatistic(Statistic.PLAY_ONE_MINUTE); + this.speed = statistic > 48000 ? 1.6 : 1.25; + AttributeInstance attribute = this.mob.getAttribute(Attribute.MAX_HEALTH); + assert attribute != null; + // Slow the mob down when not at full health + if (this.mob.getHealth() / attribute.getValue() < 0.7) { + this.speed *= 0.8; + } + return this.shouldAvoid() && this.path != null && this.pathfinder.hasPath(); + } + + @Override + public void start() { + this.pathfinder.moveTo(this.path, this.speed); + } + + @Override + public void stop() { + this.avoid = null; + this.path = null; + } + + @Override + public @NotNull GoalKey<@NotNull Mob> getKey() { + return GOAL_KEY; + } + + @Override + public @NotNull EnumSet getTypes() { + return EnumSet.of(GoalType.MOVE); + } + +} diff --git a/src/main/java/tk/shanebee/survival/item/items/FireStriker.java b/src/main/java/com/shanebeestudios/survival/api/gui/FireStrikerGUI.java similarity index 62% rename from src/main/java/tk/shanebee/survival/item/items/FireStriker.java rename to src/main/java/com/shanebeestudios/survival/api/gui/FireStrikerGUI.java index 5e35e37..696cae7 100644 --- a/src/main/java/tk/shanebee/survival/item/items/FireStriker.java +++ b/src/main/java/com/shanebeestudios/survival/api/gui/FireStrikerGUI.java @@ -1,50 +1,63 @@ -package tk.shanebee.survival.item.items; +package com.shanebeestudios.survival.api.gui; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.Sound; import org.bukkit.Tag; import org.bukkit.World; import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.InventoryView.Property; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.MenuType; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.view.FurnaceView; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; +import org.jetbrains.annotations.Nullable; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.ItemUtils; -public class FireStriker implements Runnable, InventoryHolder { +import java.util.Random; + +@SuppressWarnings("UnstableApiUsage") +public class FireStrikerGUI implements Runnable, InventoryHolder { + + public static @Nullable FireStrikerGUI create(Player player, ItemStack itemStack) { + FireStrikerGUI fireStrikerGUI = new FireStrikerGUI(player, itemStack); + if (fireStrikerGUI.burnTime > 0) return fireStrikerGUI; + return null; + } private final int id; + private final FurnaceView furnaceView; private final Inventory inv; private final Player player; - private final ItemStack item; + private final ItemStack firestrikerItemStack; + private final Random random = new Random(); - private final int MAX_COOK_TIME; + private final int maxCookTime; + private final int maxBurnTime; private int cookTime; private int burnTime; - public FireStriker(Player player, ItemStack item) { - Survival plugin = Survival.getInstance(); - Lang lang = plugin.getLang(); - this.inv = Bukkit.createInventory(this, InventoryType.FURNACE, Utils.getColoredString(lang.firestriker)); + private FireStrikerGUI(Player player, ItemStack itemStack) { + SurvivalPlugin plugin = SurvivalPlugin.getInstance(); + this.furnaceView = MenuType.FURNACE.create(player, ItemUtils.getItemNameComponent(itemStack)); + this.inv = this.furnaceView.getTopInventory(); this.player = player; - this.item = item; - this.MAX_COOK_TIME = plugin.getSurvivalConfig().ITEM_FIRESTRIKER_COOK_TIME; + this.firestrikerItemStack = itemStack; + this.maxCookTime = plugin.getSurvivalConfig().item_mechanics_firestriker_cook_time; this.cookTime = 0; - ItemMeta itemMeta = item.getItemMeta(); + ItemMeta itemMeta = itemStack.getItemMeta(); assert itemMeta != null; - this.burnTime = 8 - (((Damageable) itemMeta).getDamage() / 7); + this.maxBurnTime = Items.FIRESTRIKER.getMaxCooks(); + this.burnTime = ItemUtils.getDurability(itemStack); this.id = Bukkit.getScheduler().runTaskTimer(plugin, this, 0, 1).getTaskId(); } @@ -55,7 +68,7 @@ public void run() { private void tick() { if (canCook() && canBurn()) { - if (cookTime < MAX_COOK_TIME) { + if (cookTime < maxCookTime) { cookTime++; } else { cook(); @@ -77,34 +90,32 @@ private void tick() { } private void updateFuel() { - ItemStack fuel = inv.getItem(1); - if (fuel != null && Item.FIRESTRIKER.compare(fuel)) { - Damageable meta = ((Damageable) fuel.getItemMeta()); - assert meta != null; - burnTime = 8 - (meta.getDamage() / 7); + ItemStack fuel = this.inv.getItem(1); + if (fuel != null && Items.FIRESTRIKER.is(fuel)) { + this.burnTime = this.maxBurnTime - ItemUtils.getDurability(fuel); } } private boolean canBurn() { ItemStack fuel = inv.getItem(1); - return fuel != null && Item.FIRESTRIKER.compare(fuel) && burnTime > 0; + return fuel != null && Items.FIRESTRIKER.is(fuel) && burnTime > 0; } private void burn() { - ItemStack fuel = inv.getItem(1); - assert fuel != null; - ItemMeta itemMeta = fuel.getItemMeta(); - assert itemMeta != null; + ItemStack fuelItemStack = this.inv.getItem(1); + assert fuelItemStack != null; + ItemMeta itemMeta = fuelItemStack.getItemMeta(); int damage = ((Damageable) itemMeta).getDamage(); - damage += 7; - if (damage <= 52) { + damage++; + if (damage < this.maxBurnTime) { ((Damageable) itemMeta).setDamage(damage); - fuel.setItemMeta(itemMeta); - inv.setItem(1, fuel); - burnTime--; + fuelItemStack.setItemMeta(itemMeta); + this.inv.setItem(1, fuelItemStack); + this.burnTime--; } else { - inv.setItem(1, null); - burnTime = 0; + this.inv.setItem(1, null); + this.player.getWorld().playSound(this.player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, this.random.nextFloat() * 0.4F + 0.8F); + this.burnTime = 0; } } @@ -152,17 +163,15 @@ private void cook() { inv.setItem(0, input); } + @SuppressWarnings("UnstableApiUsage") private void updateView() { - InventoryView view = player.getOpenInventory(); - view.setProperty(Property.COOK_TIME, cookTime); - view.setProperty(Property.TICKS_FOR_CURRENT_SMELTING, MAX_COOK_TIME); - view.setProperty(Property.BURN_TIME, burnTime); - view.setProperty(Property.TICKS_FOR_CURRENT_FUEL, 8); + this.furnaceView.setCookTime(this.cookTime, this.maxCookTime); + this.furnaceView.setBurnTime(this.burnTime, 8); } public void open() { - inv.setItem(1, this.item); - player.openInventory(inv); + inv.setItem(1, this.firestrikerItemStack); + player.openInventory(this.furnaceView); } public void close() { @@ -214,7 +223,11 @@ private Material getOutput(Material material) { @Override public @NotNull Inventory getInventory() { - return inv; + return this.inv; + } + + public FurnaceView getFurnaceView() { + return this.furnaceView; } } diff --git a/src/main/java/tk/shanebee/survival/gui/NutritionGUI.java b/src/main/java/com/shanebeestudios/survival/api/gui/NutritionGUI.java similarity index 72% rename from src/main/java/tk/shanebee/survival/gui/NutritionGUI.java rename to src/main/java/com/shanebeestudios/survival/api/gui/NutritionGUI.java index 132d430..39ffe26 100644 --- a/src/main/java/tk/shanebee/survival/gui/NutritionGUI.java +++ b/src/main/java/com/shanebeestudios/survival/api/gui/NutritionGUI.java @@ -1,5 +1,6 @@ -package tk.shanebee.survival.gui; +package com.shanebeestudios.survival.api.gui; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -11,10 +12,10 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.item.Nutrition; -import tk.shanebee.survival.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.api.item.Nutrition; +import com.shanebeestudios.survival.api.util.Utils; import java.util.ArrayList; import java.util.List; @@ -28,11 +29,11 @@ public class NutritionGUI implements InventoryHolder, Listener { private final ItemStack LAST_PAGE_BUTTON; private final ItemStack NEXT_PAGE_BUTTON; - public NutritionGUI(Survival plugin) { + public NutritionGUI(SurvivalPlugin plugin) { this.lang = plugin.getLang(); Bukkit.getPluginManager().registerEvents(this, plugin); - LAST_PAGE_BUTTON = getButton(Material.PAPER, Utils.getColoredString(lang.nutrition_gui_last_page)); - NEXT_PAGE_BUTTON = getButton(Material.PAPER, Utils.getColoredString(lang.nutrition_gui_next_page)); + LAST_PAGE_BUTTON = getButton(Material.PAPER, Utils.getMini(this.lang.nutrition_gui_last_page)); + NEXT_PAGE_BUTTON = getButton(Material.PAPER, Utils.getMini(this.lang.nutrition_gui_next_page)); } @NotNull @@ -54,7 +55,7 @@ public void openInventory(Player player, int page) { listSize = nutritions.size() - p; rows = listSize > 45 ? 6 : (int) Math.ceil((double) listSize / 9) + 1; } - this.inv = Bukkit.createInventory(this, rows * 9, Utils.getColoredString(lang.nutrition_gui)); + this.inv = Bukkit.createInventory(this, rows * 9, Utils.getMini(this.lang.nutrition_gui)); for (int i = 0; i < (Math.min(listSize, pages ? 45 : 54)); i++) { Nutrition nutrition = nutritions.get(i + p); @@ -69,11 +70,12 @@ public void openInventory(Player player, int page) { player.openInventory(inv); } - private ItemStack getButton(Material material, String name) { + @SuppressWarnings("SameParameterValue") + private ItemStack getButton(Material material, Component name) { ItemStack itemStack = new ItemStack(material); ItemMeta meta = itemStack.getItemMeta(); assert meta != null; - meta.setDisplayName(Utils.getColoredString(name)); + meta.displayName(name); itemStack.setItemMeta(meta); return itemStack; } @@ -83,12 +85,13 @@ private ItemStack getItemStack(Nutrition nutrition) { ItemMeta meta = item.getItemMeta(); assert meta != null; - List lore = meta.getLore() != null ? meta.getLore() : new ArrayList<>(); - lore.add(" "); - lore.add(Utils.getColoredString("&2" + lang.carbohydrates + ": &7" + nutrition.getCarbs())); - lore.add(Utils.getColoredString("&4" + lang.protein + ": &7" + nutrition.getProteins())); - lore.add(Utils.getColoredString("&5" + lang.vitamins + ": &7" + nutrition.getVitamins())); - meta.setLore(lore); + List oldLore = meta.lore(); + List lore = oldLore != null ? oldLore : new ArrayList<>(); + lore.add(Component.empty()); + lore.add(Utils.getMini("<#A0E853>%s: %s", this.lang.carbohydrates, nutrition.getCarbs())); + lore.add(Utils.getMini("<#CE784D>%s: %s", this.lang.protein, nutrition.getProteins())); + lore.add(Utils.getMini("<#53DDE8>%s: %s", this.lang.vitamins, nutrition.getVitamins())); + meta.lore(lore); item.setItemMeta(meta); return item; diff --git a/src/main/java/com/shanebeestudios/survival/api/gui/package-info.java b/src/main/java/com/shanebeestudios/survival/api/gui/package-info.java new file mode 100644 index 0000000..5ea3090 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/gui/package-info.java @@ -0,0 +1,4 @@ +/** + * Represents GUIs used by the plugin + */ +package com.shanebeestudios.survival.api.gui; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/Item.java b/src/main/java/com/shanebeestudios/survival/api/item/Item.java new file mode 100644 index 0000000..d4e5786 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/Item.java @@ -0,0 +1,226 @@ +package com.shanebeestudios.survival.api.item; + +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.config.ItemConfig; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.DyedItemColor; +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import io.papermc.paper.registry.set.RegistryKeySet; +import io.papermc.paper.registry.tag.TagKey; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; +import org.bukkit.block.BlockType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings({"UnstableApiUsage", "PatternValidation"}) +public abstract class Item { + + protected static final ItemConfig ITEM_CONFIG = new ItemConfig(); + private static final MiniMessage MINI = MiniMessage.miniMessage(); + + // Minecraft default keys + protected static final NamespacedKey BASE_ATTACK_DAMAGE = NamespacedKey.minecraft("base_attack_damage"); + protected static final NamespacedKey BASE_ATTACK_SPEED = NamespacedKey.minecraft("base_attack_speed"); + // Non-official keys + protected static final NamespacedKey BASE_MOVEMENT_SPEED = NamespacedKey.minecraft("base_movement_speed"); + + private Key key; + protected NamespacedKey recipeKey; + private ItemStack itemStack; + private String name; + + private double repairPercent; + private int repairCost; + private boolean preventDuelWield; + + /** + * Get an ItemStack from this item + * + * @return Cloned ItemStack of this item + */ + public ItemStack getItemStack() { + return getItemStack(1); + } + + /** + * Get an ItemStack from this item + * + * @param amount Stack amount + * @return Cloned ItemStack of this item + */ + public ItemStack getItemStack(int amount) { + ItemStack clone = this.itemStack.clone(); + clone.setAmount(amount); + return clone; + } + + protected void setupDefaults(String key, ItemStack itemStack) { + setupDefaults(key, itemStack, false); + } + + @SuppressWarnings("PatternValidation") + protected void setupDefaults(String key, ItemStack itemStack, boolean vanillaModel) { + this.key = Key.key("survival_plus", key); + this.recipeKey = NamespacedKey.fromString(this.key.toString()); + if (!vanillaModel) { + itemStack.setData(DataComponentTypes.ITEM_MODEL, this.key); + } + + // Color + int color = ITEM_CONFIG.getColor(key); + if (color != 0) { + DyedItemColor dyedItemColor = DyedItemColor.dyedItemColor(Color.fromRGB(color), false); + itemStack.setData(DataComponentTypes.DYED_COLOR, dyedItemColor); + } + + // Item Name + String itemName = ITEM_CONFIG.getName(key); + if (itemName != null) { + if (itemStack.hasData(DataComponentTypes.POTION_CONTENTS)) { + // Stupid workaround because potion names override item_name + itemStack.setData(DataComponentTypes.CUSTOM_NAME, MINI.deserialize("" + itemName)); + } else { + itemStack.setData(DataComponentTypes.ITEM_NAME, MINI.deserialize(itemName)); + } + } else if (!vanillaModel) { + Utils.logMini("Failed to load item name for item '" + key + "'"); + } + this.name = itemName; + + // Lore + List lore = ITEM_CONFIG.getLore(key); + if (lore != null && !lore.isEmpty()) { + List loreComponents = new ArrayList<>(); + for (String line : lore) { + loreComponents.add(MINI.deserialize("" + line)); + } + itemStack.lore(loreComponents); + } + + // Max Damage + int maxDamage = ITEM_CONFIG.getMaxDamage(key); + if (maxDamage > 0) { + itemStack.setData(DataComponentTypes.MAX_DAMAGE, maxDamage); + itemStack.setData(DataComponentTypes.DAMAGE, 0); + } + + // Repair Cost + this.repairCost = ITEM_CONFIG.getRepairCost(key); + if (this.repairCost > 0) { + itemStack.setData(DataComponentTypes.REPAIR_COST, this.repairCost); + } + + // Repair Percent + this.repairPercent = ITEM_CONFIG.getRepairPercent(key); + this.itemStack = itemStack; + + // Prevent dual wield + this.preventDuelWield = ITEM_CONFIG.getBoolean(key, "prevent_dual_wield", false); + + Items.ALL_ITEMS.put(this.key, this); + } + + @SuppressWarnings("NullableProblems") + protected RegistryKeySet getBlockTag(TagKey tagKey) { + return RegistryAccess.registryAccess().getRegistry(RegistryKey.BLOCK).getTag(tagKey); + } + + @SuppressWarnings("NullableProblems") + protected RegistryKeySet getBlockTag(Tag tag) { + TagKey tagKey = TagKey.create(RegistryKey.BLOCK, tag.key()); + return RegistryAccess.registryAccess().getRegistry(RegistryKey.BLOCK).getTag(tagKey); + } + + /** + * Get the recipe of this item + * + * @return Recipe of this item if registered + */ + public @Nullable Recipe getRecipe() { + return null; + } + + /** + * Check if an {@link ItemStack} matches this item + * + * @param itemStack ItemStack to compare + * @return True if the item matches + */ + public boolean is(ItemStack itemStack) { + if (itemStack.hasData(DataComponentTypes.ITEM_MODEL)) { + Key data = itemStack.getData(DataComponentTypes.ITEM_MODEL); + return data != null && data.equals(this.key); + } + return false; + } + + /** + * Get the repair percent of this item + *

This is used to determine output durability during repairs

+ * + * @return Repair percent of item + */ + public double getRepairPercent() { + return this.repairPercent; + } + + /** + * Get the repair cost of this item + * + * @return Repair cost of item + */ + public int getRepairCost() { + return this.repairCost; + } + + /** + * Check if an item cannot dual wield + * + * @return Whether item prevents dual wielding + */ + public boolean isPreventDuelWield() { + return this.preventDuelWield; + } + + /** + * Get the {@link Key} of this item + * + * @return Key of this item + */ + public Key getKey() { + return this.key; + } + + /** + * Get the name of this item + * + * @return Name of item + */ + public @Nullable String getName() { + return this.name; + } + + @Override + public String toString() { + return "Item{" + + "key=" + key + + ", recipeKey=" + recipeKey + + ", itemStack=" + itemStack + + ", name='" + name + '\'' + + ", repairPercent=" + repairPercent + + ", repairCost=" + repairCost + + ", preventDuelWield=" + preventDuelWield + + '}'; + } +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/Items.java b/src/main/java/com/shanebeestudios/survival/api/item/Items.java new file mode 100644 index 0000000..7a5df73 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/Items.java @@ -0,0 +1,296 @@ +package com.shanebeestudios.survival.api.item; + +import com.google.common.collect.Lists; +import io.papermc.paper.datacomponent.DataComponentTypes; +import net.kyori.adventure.key.Key; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.entity.Entity; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import com.shanebeestudios.survival.api.item.items.armor.ArmorPiece; +import com.shanebeestudios.survival.api.item.items.armor.ArmorPiece.ArmorMaterial; +import com.shanebeestudios.survival.api.item.items.armor.ArmorPiece.ArmorType; +import com.shanebeestudios.survival.api.item.items.armor.BeekeeperPiece; +import com.shanebeestudios.survival.api.item.items.armor.RainBoots; +import com.shanebeestudios.survival.api.item.items.armor.ReinforcedPiece; +import com.shanebeestudios.survival.api.item.items.armor.SnowBoots; +import com.shanebeestudios.survival.api.item.items.blocks.Campfire; +import com.shanebeestudios.survival.api.item.items.blocks.Workbench; +import com.shanebeestudios.survival.api.item.items.drinks.Coffee; +import com.shanebeestudios.survival.api.item.items.drinks.ColdMilk; +import com.shanebeestudios.survival.api.item.items.drinks.HotMilk; +import com.shanebeestudios.survival.api.item.items.drinks.Water; +import com.shanebeestudios.survival.api.item.items.food.SuspiciousMeat; +import com.shanebeestudios.survival.api.item.items.legendary.BlazeSword; +import com.shanebeestudios.survival.api.item.items.legendary.EnderGiantBlade; +import com.shanebeestudios.survival.api.item.items.legendary.ObsidianMace; +import com.shanebeestudios.survival.api.item.items.legendary.QuartzPickaxe; +import com.shanebeestudios.survival.api.item.items.legendary.ValkyriesAxe; +import com.shanebeestudios.survival.api.item.items.misc.BreedingEgg; +import com.shanebeestudios.survival.api.item.items.misc.CoffeeBean; +import com.shanebeestudios.survival.api.item.items.misc.FermentedSkin; +import com.shanebeestudios.survival.api.item.items.tools.Compass; +import com.shanebeestudios.survival.api.item.items.tools.FireStriker; +import com.shanebeestudios.survival.api.item.items.tools.GrapplingHook; +import com.shanebeestudios.survival.api.item.items.tools.Hammer; +import com.shanebeestudios.survival.api.item.items.tools.Hatchet; +import com.shanebeestudios.survival.api.item.items.tools.Mattock; +import com.shanebeestudios.survival.api.item.items.tools.MedicKit; +import com.shanebeestudios.survival.api.item.items.tools.RecurvedBow; +import com.shanebeestudios.survival.api.item.items.tools.RecurvedCrossbow; +import com.shanebeestudios.survival.api.item.items.tools.Shiv; +import com.shanebeestudios.survival.api.item.items.tools.Sickle; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * Custom SurvivalPlus {@link Item Items} + */ +@SuppressWarnings("UnstableApiUsage") +public class Items { + + static final Map ALL_ITEMS = new LinkedHashMap<>(); + + // TOOLS + public static final Item HATCHET = new Hatchet(); + public static final Item MATTOCK = new Mattock(); + public static final Item SHIV = new Shiv(); + public static final Item HAMMER = new Hammer(); + public static final FireStriker FIRESTRIKER = new FireStriker(); + public static final Item GRAPPLING_HOOK = new GrapplingHook(); + public static final Item COMPASS = new Compass(); + public static final Item FLINT_SICKLE = new Sickle("flint", Material.FLINT); + public static final Item STONE_SICKLE = new Sickle("stone", Material.COBBLESTONE); + public static final Item IRON_SICKLE = new Sickle("iron", Material.IRON_INGOT); + public static final Item DIAMOND_SICKLE = new Sickle("diamond", Material.DIAMOND); + public static final MedicKit MEDIC_KIT = new MedicKit(); + public static final RecurvedBow RECURVED_BOW = new RecurvedBow(); + public static final RecurvedCrossbow RECURVED_CROSSBOW = new RecurvedCrossbow(); + + // LEGENDARY TOOLS + public static final Item VALKYRIES_AXE = new ValkyriesAxe(); + public static final Item QUARTZ_PICKAXE = new QuartzPickaxe(); + public static final Item OBSIDIAN_MACE = new ObsidianMace(); + public static final EnderGiantBlade ENDER_GIANT_BLADE = new EnderGiantBlade(); + public static final Item BLAZE_SWORD = new BlazeSword(); + + // ARMOR + public static final ReinforcedPiece REINFORCED_LEATHER_HELMET = new ReinforcedPiece(ArmorType.HELMET); + public static final ReinforcedPiece REINFORCED_LEATHER_TUNIC = new ReinforcedPiece(ArmorType.CHESTPLATE); + public static final ReinforcedPiece REINFORCED_LEATHER_TROUSERS = new ReinforcedPiece(ArmorType.LEGGINGS); + public static final ReinforcedPiece REINFORCED_LEATHER_BOOTS = new ReinforcedPiece(ArmorType.BOOTS); + + public static final ArmorPiece GOLDEN_CROWN = new ArmorPiece(ArmorType.HELMET, ArmorMaterial.GOLDEN, 1.0, -0.0125); + public static final ArmorPiece GOLDEN_GUARD = new ArmorPiece(ArmorType.CHESTPLATE, ArmorMaterial.GOLDEN, 3.0, -0.02); + public static final ArmorPiece GOLDEN_GREAVES = new ArmorPiece(ArmorType.LEGGINGS, ArmorMaterial.GOLDEN, 2.0, -0.02); + public static final ArmorPiece GOLDEN_SABATONS = new ArmorPiece(ArmorType.BOOTS, ArmorMaterial.GOLDEN, 1.0, -0.0125); + + public static final ArmorPiece IRON_HELMET = new ArmorPiece(ArmorType.HELMET, ArmorMaterial.IRON, 2.0, -0.02); + public static final ArmorPiece IRON_CHESTPLATE = new ArmorPiece(ArmorType.CHESTPLATE, ArmorMaterial.IRON, 6.0, -0.03); + public static final ArmorPiece IRON_LEGGINGS = new ArmorPiece(ArmorType.LEGGINGS, ArmorMaterial.IRON, 5.0, -0.03); + public static final ArmorPiece IRON_BOOTS = new ArmorPiece(ArmorType.BOOTS, ArmorMaterial.IRON, 2.0, -0.02); + + public static final ArmorPiece DIAMOND_HELMET = new ArmorPiece(ArmorType.HELMET, ArmorMaterial.DIAMOND, 3, -0.02); + public static final ArmorPiece DIAMOND_CHESTPLATE = new ArmorPiece(ArmorType.CHESTPLATE, ArmorMaterial.DIAMOND, 8, -0.03); + public static final ArmorPiece DIAMOND_LEGGINGS = new ArmorPiece(ArmorType.LEGGINGS, ArmorMaterial.DIAMOND, 6, -0.03); + public static final ArmorPiece DIAMOND_BOOTS = new ArmorPiece(ArmorType.BOOTS, ArmorMaterial.DIAMOND, 3, -0.02); + + public static final ArmorPiece NETHERITE_HELMET = new ArmorPiece(ArmorType.HELMET, ArmorMaterial.NETHERITE, 3.0, -0.02, 3.0, 0.1); + public static final ArmorPiece NETHERITE_CHESTPLATE = new ArmorPiece(ArmorType.CHESTPLATE, ArmorMaterial.NETHERITE, 8.0, -0.02, 3.0, 0.1); + public static final ArmorPiece NETHERITE_LEGGINGS = new ArmorPiece(ArmorType.LEGGINGS, ArmorMaterial.NETHERITE, 6.0, -0.02, 3.0, 0.1); + public static final ArmorPiece NETHERITE_BOOTS = new ArmorPiece(ArmorType.BOOTS, ArmorMaterial.NETHERITE, 3.0, -0.02, 3.0, 0.1); + + public static final BeekeeperPiece BEEKEEPER_HELMET = new BeekeeperPiece(ArmorType.HELMET); + public static final BeekeeperPiece BEEKEEPER_CHESTPLATE = new BeekeeperPiece(ArmorType.CHESTPLATE); + public static final BeekeeperPiece BEEKEEPER_LEGGINGS = new BeekeeperPiece(ArmorType.LEGGINGS); + public static final BeekeeperPiece BEEKEEPER_BOOTS = new BeekeeperPiece(ArmorType.BOOTS); + public static final Item SNOW_BOOTS = new SnowBoots(); + public static final Item RAIN_BOOTS = new RainBoots(); + + // BLOCKS + public static final Item WORKBENCH = new Workbench(); + public static final Item CAMPFIRE = new Campfire(); + + // MISC + public static final Item FERMENTED_SKIN = new FermentedSkin(); + public static final Item COFFEE_BEAN = new CoffeeBean(); + public static final Item BREEDING_EGG = new BreedingEgg(); + + // FOOD + public static final Item SUSPICIOUS_MEAT = new SuspiciousMeat(); + + // DRINKS + public static final Water DIRTY_WATER = Water.dirty(); + public static final Water CLEAN_WATER = Water.clean(); + public static final Water PURIFIED_WATER = Water.purified(); + public static final Water SALTY_WATER = Water.salty(); + public static final Water MURKY_WATER = Water.murky(); + public static final Water WATER_BOWL = Water.waterBowl(); + public static final Coffee COFFEE = new Coffee(); + public static final HotMilk HOT_MILK = new HotMilk(); + public static final ColdMilk COLD_MILK = new ColdMilk(); + + /** + * Currently null, don't use + */ + // TODO Experimental + public static final Item PERSISTENT_TORCH = null; + + public static Set allItemKeys() { + return ALL_ITEMS.keySet(); + } + + /** + * Get an {@link Item} by {@link Key} + * + * @param key Key of item + * @return Item if available + */ + @SuppressWarnings("PatternValidation") + @Nullable + public static Item getByKey(@NotNull String key) { + key = key.toLowerCase(Locale.ROOT); + if (!key.contains("survival_plus:")) { + key = "survival_plus:" + key; + } + return ALL_ITEMS.get(Key.key(key)); + } + + /** + * Get an {@link Item} from an {@link ItemStack} + * + * @param itemStack ItemStack to grab item from + * @return Item if ItemStack has linked item + */ + @Nullable + public static Item getFromStack(@NotNull ItemStack itemStack) { + if (itemStack.hasData(DataComponentTypes.ITEM_MODEL)) { + Key data = itemStack.getData(DataComponentTypes.ITEM_MODEL); + if (data != null) return ALL_ITEMS.get(data); + } + return null; + } + + /** + * Get a water bottle based on a biome + * + * @param biome Biome to check for bottle + * @return Water bottle based on biome + */ + public static Water getBiomeBasedWaterBottle(Biome biome) { + String string = biome.getKey().getKey(); + if (string.contains("ocean")) { + return Items.SALTY_WATER; + } else if (string.contains("swamp")) { + return Items.MURKY_WATER; + } else if (string.contains("lush")) { + return Items.PURIFIED_WATER; + } + return Items.DIRTY_WATER; + } + + private static final List DEBUG_DISPLAYS = Lists.newArrayList(); + + /** + * Spawn {@link ItemDisplay ItemDisplays} for each item at the provided player + *

Leaving player null will remove the previous spawned entities

+ * + * @param player Player to spawn at, or null to clear previous spawns + */ + public static void debug(@Nullable Player player) { + if (player == null) { + DEBUG_DISPLAYS.forEach(Entity::remove); + DEBUG_DISPLAYS.clear(); + return; + } + Location location = player.getLocation().getBlock().getLocation().clone().add(0, 1, 0); + + double x = 0; + double y = 0; + World world = player.getWorld(); + for (Item item : ALL_ITEMS.values()) { + Location loc = location.clone().add(x, y, 0); + ItemDisplay itemDisplay = world.spawn(loc, ItemDisplay.class, display -> { + display.setItemStack(item.getItemStack()); + display.customName(Utils.getMini(item.getName())); + display.setCustomNameVisible(true); + }); + DEBUG_DISPLAYS.add(itemDisplay); + x += 3; + if (x > 20) { + x = 0; + y += 1.5; + } + } + } + + /** + * Tags for different {@link Items} groups + */ + public enum Tags { + /** + * Any sickle + */ + SICKLES(FLINT_SICKLE, STONE_SICKLE, IRON_SICKLE, DIAMOND_SICKLE), + /** + * Any reinforced leather armor + */ + REINFORCED_LEATHER_ARMOR(REINFORCED_LEATHER_BOOTS, REINFORCED_LEATHER_TROUSERS, + REINFORCED_LEATHER_TUNIC, REINFORCED_LEATHER_HELMET), + /** + * Any water bottle + */ + WATER_BOTTLE(DIRTY_WATER, MURKY_WATER, SALTY_WATER, CLEAN_WATER, PURIFIED_WATER), + /** + * Any drinkable item + */ + DRINKABLE(DIRTY_WATER, MURKY_WATER, SALTY_WATER, CLEAN_WATER, PURIFIED_WATER, WATER_BOWL, + COLD_MILK, HOT_MILK, COFFEE), + + /** + * Any legendary item + */ + LEGENDARY(BLAZE_SWORD, OBSIDIAN_MACE, VALKYRIES_AXE, ENDER_GIANT_BLADE, QUARTZ_PICKAXE); + + private final Item[] items; + + Tags(Item... items) { + this.items = items; + } + + /** + * Get all items tagged in this group + * + * @return All items tagged in this group + */ + public Item[] getItems() { + return items; + } + + /** + * Check if an ItemStack is tagged in a group of custom {@link Items} + * + * @param itemStack ItemStack to check + * @return True if item matches tag + */ + public boolean isTagged(ItemStack itemStack) { + for (Item item : this.items) { + if (item.is(itemStack)) return true; + } + return false; + } + + } + +} diff --git a/src/main/java/tk/shanebee/survival/item/Nutrition.java b/src/main/java/com/shanebeestudios/survival/api/item/Nutrition.java similarity index 78% rename from src/main/java/tk/shanebee/survival/item/Nutrition.java rename to src/main/java/com/shanebeestudios/survival/api/item/Nutrition.java index 8b425c7..7ff9a22 100644 --- a/src/main/java/tk/shanebee/survival/item/Nutrition.java +++ b/src/main/java/com/shanebeestudios/survival/api/item/Nutrition.java @@ -1,15 +1,20 @@ -package tk.shanebee.survival.item; +package com.shanebeestudios.survival.api.item; import com.google.common.base.Preconditions; +import io.papermc.paper.datacomponent.DataComponentTypes; import org.bukkit.Keyed; import org.bukkit.Material; import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import tk.shanebee.survival.Survival; +import com.shanebeestudios.survival.plugin.config.ItemConfig; +import com.shanebeestudios.survival.api.util.Utils; import java.util.ArrayList; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -21,7 +26,7 @@ @SuppressWarnings("unused") public class Nutrition implements Keyed { - static void setup() { + public static void setup() { } private static final Map NUTRITION_MAP = new LinkedHashMap<>(); @@ -40,6 +45,7 @@ static void setup() { public static final Nutrition BEETROOT = register(0, 0, 35, Material.BEETROOT); public static final Nutrition DRIED_KELP = register(15, 50, 50, Material.DRIED_KELP); public static final Nutrition SWEET_BERRIES = register(40, 0, 60, Material.SWEET_BERRIES); + public static final Nutrition GLOW_BERRIES = register(40, 0, 60, Material.GLOW_BERRIES); // PREPARED FOODS public static final Nutrition BREAD = register(300, 25, 12, Material.BREAD); @@ -73,12 +79,13 @@ static void setup() { public static final Nutrition SPIDER_EYE = register(0, 50, 0, Material.SPIDER_EYE); public static final Nutrition ROTTEN_FLESH = register(0, 25, 25, Material.ROTTEN_FLESH); public static final Nutrition MILK_BUCKET = register(0, 250, 0, Material.MILK_BUCKET); + public static final Nutrition HONEY_BOTTLE = register(17, 0, 60, Material.HONEY_BOTTLE); @NotNull private static Nutrition register(int carbs, int proteins, int vitamins, Material material) { String key = material.toString().toLowerCase(Locale.ROOT); int[] nutritions = ItemConfig.INSTANCE.getNutritionValues(key, carbs, proteins, vitamins); - NamespacedKey namespacedKey = new NamespacedKey(Survival.getInstance(), "nutrition_" + key); + NamespacedKey namespacedKey = Utils.getNamespacedKey("nutrition_" + key); ItemStack itemStack = new ItemStack(material); return register(namespacedKey, false, itemStack, nutritions[0], nutritions[1], nutritions[2]); } @@ -134,6 +141,42 @@ public static boolean unregister(@NotNull NamespacedKey key) { return false; } + @SuppressWarnings("UnstableApiUsage") + public static void debug() { + Nutrition.getAllNutritions().stream().sorted(Comparator.comparing(nutrition -> nutrition.getKey().toString())) + .forEach(nutrition -> { + String nutritionKey = nutrition.getKey().toString().replace(":", ":"); + String itemKey = nutrition.getItemStack().getType().getKey().toString().replace(":", ":"); + Utils.logMini("Nutrition%s:", nutrition.isCustom() ? "(CUSTOM)" : ""); + Utils.logMini(" - Key: %s", nutritionKey); + Utils.logMini(" - Item: %s", itemKey); + Utils.logMini(" - Values: Carbs: %s, Proteins: %s, Vitamins: %s", + nutrition.getCarbs(), nutrition.getProteins(), nutrition.getVitamins()); + }); + + List nutritionMaterials = new ArrayList<>(); + getAllNutritions().forEach(nutrition -> nutritionMaterials.add(nutrition.itemStack.getType())); + + Utils.logMini(" "); + Utils.logMini("Nutrition Materials Missing:"); + for (ItemType itemType : Registry.ITEM.stream().sorted(Comparator.comparing(itemType -> itemType.getKey().toString())).toList()) { + ItemStack itemStack = itemType.createItemStack(); + Material type = itemStack.getType(); + if (itemStack.hasData(DataComponentTypes.FOOD)) { + if (!nutritionMaterials.contains(type)) { + Utils.logMini(" - Nutrition missing for food item: %s", type.getKey().toString()); + } + } else if (itemStack.hasData(DataComponentTypes.CONSUMABLE)) { + if (!nutritionMaterials.contains(type)) { + Utils.logMini(" - <#F09616>Nutrition missing for consumable item: %s", type.getKey().toString()); + } + } else if (nutritionMaterials.contains(type)) { + if (type == Material.CAKE) continue; + Utils.logMini(" - Nutrition present for non food item: %s", type.getKey().toString()); + } + } + } + private final NamespacedKey key; private final boolean custom; private final int carbs; @@ -159,7 +202,7 @@ public static boolean unregister(@NotNull NamespacedKey key) { this.proteins = proteins; this.vitamins = vitamins; this.item = item; - this.itemStack = item.getItem(); + this.itemStack = item.getItemStack(); } /** diff --git a/src/main/java/com/shanebeestudios/survival/api/item/Recipes.java b/src/main/java/com/shanebeestudios/survival/api/item/Recipes.java new file mode 100644 index 0000000..cd4045f --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/Recipes.java @@ -0,0 +1,467 @@ +package com.shanebeestudios.survival.api.item; + +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.config.Config; +import io.papermc.paper.potion.PotionMix; +import org.bukkit.Bukkit; +import org.bukkit.Keyed; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; +import org.bukkit.entity.Player; +import org.bukkit.inventory.BlastingRecipe; +import org.bukkit.inventory.CampfireRecipe; +import org.bukkit.inventory.FurnaceRecipe; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.ShapelessRecipe; +import org.bukkit.inventory.SmokingRecipe; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; + +/** + * Enums of all custom recipes + */ +public class Recipes { + + private static final Collection ALL_RECIPE_KEYS = new HashSet<>(); + private static boolean INITIALIZED = false; + + // CUSTOM TOOLS/ITEMS + public static Recipes HATCHET; + public static Recipes MATTOCK; + public static Recipes SHIV; + public static Recipes HAMMER; + public static Recipes WORKBENCH; + public static Recipes FIRESTRIKER; + public static Recipes VALKYRIES_AXE; + public static Recipes QUARTZ_PICKAXE; + public static Recipes OBSIDIAN_MACE; + public static Recipes ENDER_GIANT_BLADE; + public static Recipes BLAZE_SWORD; + public static Recipes FERMENTED_SKIN; + public static Recipes MEDIC_KIT; + public static Recipes REINFORCED_LEATHER_BOOTS; + public static Recipes REINFORCED_LEATHER_CHESTPLATE; + public static Recipes REINFORCED_LEATHER_LEGGINGS; + public static Recipes REINFORCED_LEATHER_HELMET; + public static Recipes GOLD_SABATONS; + public static Recipes GOLD_GUARD; + public static Recipes GOLD_GREAVES; + public static Recipes GOLD_CROWN; + public static Recipes RECURVED_BOW; + public static Recipes RECURVED_CROSSBOW; + public static Recipes UNLIT_CAMPFIRE; + public static Recipes FLINT_SICKLE; + public static Recipes STONE_SICKLE; + public static Recipes IRON_SICKLE; + public static Recipes DIAMOND_SICKLE; + public static Recipes GRAPPLING_HOOK; + public static Recipes CLEAN_WATER_BOTTLES; + public static Recipes COFFEE_BEAN; + public static Recipes COLD_MILK; + public static Recipes HOT_MILK; + public static Recipes COFFEE; + public static Recipes BEEKEEPER_SUIT; + public static Recipes SNOW_BOOTS; + public static Recipes RAIN_BOOTS; + + // VANILLA ITEMS + public static Recipes ENCHANTED_GOLDEN_APPLE; + public static Recipes SADDLE; + public static Recipes NAMETAG; + public static Recipes STRING_FROM_WEB; + public static Recipes STRING_FROM_WOOL; + public static Recipes IRON_HORSE_ARMOR; + public static Recipes GOLD_HORSE_ARMOR; + public static Recipes DIAMOND_HORSE_ARMOR; + public static Recipes LEATHER_HORSE_ARMOR; + public static Recipes TORCH; + public static Recipes FLINT; + public static Recipes FERMENTED_SPIDER_EYE; + public static Recipes POISONOUS_POTATO; + public static Recipes GLASS_BOTTLE; + public static Recipes BOWL; + public static Recipes FISHING_ROD; + public static Recipes IRON_INGOT; + public static Recipes IRON_NUGGET; + public static Recipes GOLD_INGOT; + public static Recipes GOLD_NUGGET; + public static Recipes BREAD; + public static Recipes COOKIE; + public static Recipes SLIMEBALL; + public static Recipes COBWEB; + public static Recipes STICK; + public static Recipes IRON_BOOTS; + public static Recipes IRON_LEGGINGS; + public static Recipes IRON_CHESTPLATE; + public static Recipes IRON_HELMET; + public static Recipes DIAMOND_BOOTS; + public static Recipes DIAMOND_LEGGINGS; + public static Recipes DIAMOND_CHESTPLATE; + public static Recipes DIAMOND_HELMET; + public static Recipes NETHERITE_BOOTS; + public static Recipes NETHERITE_LEGGINGS; + public static Recipes NETHERITE_CHESTPLATE; + public static Recipes NETHERITE_HELMET; + public static Recipes COMPASS; + + // VANILLA BLOCKS + public static Recipes CLAY_BRICK; + public static Recipes QUARTZ; + public static Recipes FURNACE; + public static Recipes CHEST; + public static Recipes CLAY; + public static Recipes DIORITE; + public static Recipes ANDESITE; + public static Recipes GRANITE; + public static Recipes GRAVEL; + public static Recipes ICE; + public static Recipes PACKED_ICE; + + // SMELTING RECIPES + public static Recipes FURNACE_IRON_INGOT; + public static Recipes FURNACE_GOLD_INGOT; + public static Recipes BLAST_IRON_INGOT; + public static Recipes BLAST_GOLD_INGOT; + + private static Recipes register(boolean register, Recipe... recipes) { + return new Recipes(register, recipes); + } + + public static void init(Config config) { + if (INITIALIZED) { + throw new IllegalStateException("Recipes already initialized"); + } + INITIALIZED = true; + BEEKEEPER_SUIT = register(config.entity_mechanics_beekeeper_suit_enabled, Items.BEEKEEPER_HELMET.getRecipe(), Items.BEEKEEPER_CHESTPLATE.getRecipe(), Items.BEEKEEPER_LEGGINGS.getRecipe(), Items.BEEKEEPER_BOOTS.getRecipe()); + HATCHET = register(config.survival_enabled, Items.HATCHET.getRecipe()); + MATTOCK = register(config.survival_enabled, Items.MATTOCK.getRecipe()); + SHIV = register(config.survival_enabled, Items.SHIV.getRecipe()); + HAMMER = register(config.survival_enabled, Items.HAMMER.getRecipe()); + FIRESTRIKER = register(config.survival_enabled, Items.FIRESTRIKER.getRecipe()); + FLINT_SICKLE = register(config.survival_enabled && config.survival_break_only_with_sickle && config.survival_sickle_flint, Items.FLINT_SICKLE.getRecipe()); + STONE_SICKLE = register(config.survival_enabled && config.survival_break_only_with_sickle && config.survival_sickle_stone, Items.STONE_SICKLE.getRecipe()); + IRON_SICKLE = register(config.survival_enabled && config.survival_break_only_with_sickle && config.survival_sickle_iron, Items.IRON_SICKLE.getRecipe()); + DIAMOND_SICKLE = register(config.survival_enabled && config.survival_break_only_with_sickle && config.survival_sickle_diamond, Items.DIAMOND_SICKLE.getRecipe()); + WORKBENCH = register(config.survival_enabled && config.recipes_workbench, Items.WORKBENCH.getRecipe()); + VALKYRIES_AXE = register(config.legendary_valkyrie, Items.VALKYRIES_AXE.getRecipe()); + QUARTZ_PICKAXE = register(config.legendary_quartz_pickaxe, Items.QUARTZ_PICKAXE.getRecipe()); + OBSIDIAN_MACE = register(config.legendary_obsidian_mace, Items.OBSIDIAN_MACE.getRecipe()); + ENDER_GIANT_BLADE = register(config.legendary_giant_blade, Items.ENDER_GIANT_BLADE.getRecipe()); + BLAZE_SWORD = register(config.legendary_blaze_sword, Items.BLAZE_SWORD.getRecipe()); + SNOW_BOOTS = register(config.mechanics_weather_enabled, Items.SNOW_BOOTS.getRecipe()); + RAIN_BOOTS = register(config.mechanics_weather_enabled, Items.RAIN_BOOTS.getRecipe()); + FERMENTED_SKIN = register(config.mechanics_fermented_skin, Items.FERMENTED_SKIN.getRecipe()); + REINFORCED_LEATHER_HELMET = register(config.mechanics_reinforced_armor, Items.REINFORCED_LEATHER_HELMET.getRecipe()); + REINFORCED_LEATHER_CHESTPLATE = register(config.mechanics_reinforced_armor, Items.REINFORCED_LEATHER_TUNIC.getRecipe()); + REINFORCED_LEATHER_LEGGINGS = register(config.mechanics_reinforced_armor, Items.REINFORCED_LEATHER_TROUSERS.getRecipe()); + REINFORCED_LEATHER_BOOTS = register(config.mechanics_reinforced_armor, Items.REINFORCED_LEATHER_BOOTS.getRecipe()); + GOLD_CROWN = register(config.legendary_gold_armor_buff, Items.GOLDEN_CROWN.getRecipe()); + GOLD_GUARD = register(config.legendary_gold_armor_buff, Items.GOLDEN_GUARD.getRecipe()); + GOLD_GREAVES = register(config.legendary_gold_armor_buff, Items.GOLDEN_GREAVES.getRecipe()); + GOLD_SABATONS = register(config.legendary_gold_armor_buff, Items.GOLDEN_SABATONS.getRecipe()); + IRON_HELMET = register(config.mechanics_slow_armor, Items.IRON_HELMET.getRecipe()); + IRON_CHESTPLATE = register(config.mechanics_slow_armor, Items.IRON_CHESTPLATE.getRecipe()); + IRON_LEGGINGS = register(config.mechanics_slow_armor, Items.IRON_LEGGINGS.getRecipe()); + IRON_BOOTS = register(config.mechanics_slow_armor, Items.IRON_BOOTS.getRecipe()); + DIAMOND_HELMET = register(config.mechanics_slow_armor, Items.DIAMOND_HELMET.getRecipe()); + DIAMOND_CHESTPLATE = register(config.mechanics_slow_armor, Items.DIAMOND_CHESTPLATE.getRecipe()); + DIAMOND_LEGGINGS = register(config.mechanics_slow_armor, Items.DIAMOND_LEGGINGS.getRecipe()); + DIAMOND_BOOTS = register(config.mechanics_slow_armor, Items.DIAMOND_BOOTS.getRecipe()); + NETHERITE_HELMET = register(config.mechanics_slow_armor, Items.NETHERITE_HELMET.getRecipe()); + NETHERITE_CHESTPLATE = register(config.mechanics_slow_armor, Items.NETHERITE_CHESTPLATE.getRecipe()); + NETHERITE_LEGGINGS = register(config.mechanics_slow_armor, Items.NETHERITE_LEGGINGS.getRecipe()); + NETHERITE_BOOTS = register(config.mechanics_slow_armor, Items.NETHERITE_BOOTS.getRecipe()); + MEDIC_KIT = register(config.mechanics_medic_kit, Items.MEDIC_KIT.getRecipe()); + RECURVED_BOW = register(config.mechanics_recurved_bow, Items.RECURVED_BOW.getRecipe()); + RECURVED_CROSSBOW = register(config.mechanics_recurved_bow, Items.RECURVED_CROSSBOW.getRecipe()); + UNLIT_CAMPFIRE = register(true, Items.CAMPFIRE.getRecipe());// TODO config?!?! + GRAPPLING_HOOK = register(config.mechanics_grappling_hook, Items.GRAPPLING_HOOK.getRecipe()); + COFFEE_BEAN = register(config.mechanics_energy_coffee_enabled, Items.COFFEE_BEAN.getRecipe()); + COLD_MILK = register(config.mechanics_energy_coffee_enabled, Items.COLD_MILK.getRecipe()); + HOT_MILK = register(config.mechanics_energy_coffee_enabled, Items.HOT_MILK.getRecipe()); + COFFEE = register(config.mechanics_energy_coffee_enabled, Items.COFFEE.getRecipe()); + COMPASS = register(config.mechanics_compass_waypoint, Items.COMPASS.getRecipe()); + + ShapedRecipe notchApple = new ShapedRecipe(Utils.getNamespacedKey("enchanted_golden_apple"), new ItemStack(Material.ENCHANTED_GOLDEN_APPLE, 1)); + notchApple.shape("@@@", "@*@", "@@@"); + notchApple.setIngredient('@', Material.GOLD_BLOCK); + notchApple.setIngredient('*', Material.GOLDEN_APPLE); + ENCHANTED_GOLDEN_APPLE = register(config.legendary_notch_apple, notchApple); + + ShapedRecipe saddle = new ShapedRecipe(Utils.getNamespacedKey("saddle"), new ItemStack(Material.SADDLE, 1)); + saddle.shape("@@@", "*-*", "= ="); + saddle.setIngredient('@', Material.LEATHER); + saddle.setIngredient('*', Material.LEAD); + saddle.setIngredient('-', Material.IRON_INGOT); + saddle.setIngredient('=', Material.IRON_NUGGET); + SADDLE = register(config.recipes_saddle, saddle); + + ShapedRecipe nametag = new ShapedRecipe(Utils.getNamespacedKey("nametag"), new ItemStack(Material.NAME_TAG, 1)); + nametag.shape(" -@", " *-", "* "); + nametag.setIngredient('@', Material.STRING); + nametag.setIngredient('-', Material.IRON_INGOT); + nametag.setIngredient('*', Material.PAPER); + NAMETAG = register(config.recipes_name_tag, nametag); + + ShapedRecipe packedIce = new ShapedRecipe(Utils.getNamespacedKey("packed_ice"), new ItemStack(Material.PACKED_ICE, 1)); + packedIce.shape("@@ ", "@@ "); + packedIce.setIngredient('@', Material.ICE); + PACKED_ICE = register(config.recipes_packed_ice, packedIce); + + + ShapedRecipe ice = new ShapedRecipe(Utils.getNamespacedKey("ice1"), new ItemStack(Material.ICE, 1)); + ShapelessRecipe ice2 = new ShapelessRecipe(Utils.getNamespacedKey("ice2"), new ItemStack(Material.ICE, 4)); + ice.shape("@@@", "@*@", "@@@"); + ice.setIngredient('@', Material.SNOWBALL); + ice.setIngredient('*', Material.WATER_BUCKET); + ice2.addIngredient(Material.PACKED_ICE); + ICE = register(config.recipes_ice, ice, ice2); + + ShapedRecipe iron_horse_armor = new ShapedRecipe(Utils.getNamespacedKey("iron_horse_armor"), new ItemStack(Material.IRON_HORSE_ARMOR, 1)); + iron_horse_armor.shape(" @", "#-#", "= ="); + iron_horse_armor.setIngredient('#', Material.IRON_BLOCK); + iron_horse_armor.setIngredient('@', Material.IRON_INGOT); + iron_horse_armor.setIngredient('-', Material.LEATHER_HORSE_ARMOR); + iron_horse_armor.setIngredient('=', Material.IRON_NUGGET); + IRON_HORSE_ARMOR = register(config.recipes_iron_bard, iron_horse_armor); + + ShapedRecipe gold_horse_armor = new ShapedRecipe(Utils.getNamespacedKey("gold_horse_armor"), new ItemStack(Material.GOLDEN_HORSE_ARMOR, 1)); + gold_horse_armor.shape(" @", "#-#", "= ="); + gold_horse_armor.setIngredient('#', Material.GOLD_BLOCK); + gold_horse_armor.setIngredient('@', Material.GOLD_INGOT); + gold_horse_armor.setIngredient('-', Material.LEATHER_HORSE_ARMOR); + gold_horse_armor.setIngredient('=', Material.GOLD_NUGGET); + GOLD_HORSE_ARMOR = register(config.recipes_gold_bard, gold_horse_armor); + + ShapedRecipe diamond_horse_armor = new ShapedRecipe(Utils.getNamespacedKey("diamond_horse_armor"), new ItemStack(Material.DIAMOND_HORSE_ARMOR, 1)); + diamond_horse_armor.shape(" H", "@-@", "B B"); + diamond_horse_armor.setIngredient('@', Material.DIAMOND); + diamond_horse_armor.setIngredient('-', Material.IRON_HORSE_ARMOR); + diamond_horse_armor.setIngredient('H', Material.DIAMOND_HELMET); + diamond_horse_armor.setIngredient('B', Material.DIAMOND_BOOTS); + DIAMOND_HORSE_ARMOR = register(config.recipes_diamond_bard, diamond_horse_armor); + + ShapedRecipe leather_horse_armor = new ShapedRecipe(Utils.getNamespacedKey("leather_horse_armor"), new ItemStack(Material.LEATHER_HORSE_ARMOR, 1)); + leather_horse_armor.shape(" C", "ABA", "A A"); + leather_horse_armor.setIngredient('A', Material.LEATHER); + leather_horse_armor.setIngredient('B', Material.SADDLE); + leather_horse_armor.setIngredient('C', Material.LEATHER_HELMET); + LEATHER_HORSE_ARMOR = register(config.recipes_leather_bard, leather_horse_armor); + + ShapelessRecipe clay_brick = new ShapelessRecipe(Utils.getNamespacedKey("clay_brick"), new ItemStack(Material.BRICK, 4)); + clay_brick.addIngredient(Material.BRICKS); + CLAY_BRICK = register(config.recipes_clay_brick, clay_brick); + + ShapelessRecipe quartz = new ShapelessRecipe(Utils.getNamespacedKey("quartz"), new ItemStack(Material.QUARTZ, 4)); + quartz.addIngredient(Material.QUARTZ_BLOCK); + QUARTZ = register(config.recipes_quartz_block, quartz); + + ShapelessRecipe string_from_wool = new ShapelessRecipe(Utils.getNamespacedKey("string_from_wool"), new ItemStack(Material.STRING, 4)); + ShapelessRecipe string_from_cobweb = new ShapelessRecipe(Utils.getNamespacedKey("string_from_cobweb"), new ItemStack(Material.STRING, 2)); + string_from_wool.addIngredient(new RecipeChoice.MaterialChoice(Tag.WOOL)); + string_from_cobweb.addIngredient(Material.COBWEB); + STRING_FROM_WEB = register(config.recipes_web_string, string_from_cobweb); + STRING_FROM_WOOL = register(config.recipes_wool_string, string_from_wool); + + ShapedRecipe furnace = new ShapedRecipe(Utils.getNamespacedKey("furnace"), new ItemStack(Material.FURNACE, 1)); + furnace.shape("@@@", "@*@", "@@@"); + furnace.setIngredient('@', Material.BRICK); + furnace.setIngredient('*', Items.FIRESTRIKER.getItemStack()); + FURNACE = register(config.survival_enabled && config.recipes_furnace, furnace); + + ShapedRecipe chest = new ShapedRecipe(Utils.getNamespacedKey("chest"), new ItemStack(Material.CHEST, 1)); + chest.shape("@@@", "@#@", "@@@"); + chest.setIngredient('@', new RecipeChoice.MaterialChoice(Tag.PLANKS)); + chest.setIngredient('#', Material.IRON_INGOT); + CHEST = register(config.survival_enabled, chest); + + ShapedRecipe clay = new ShapedRecipe(Utils.getNamespacedKey("clay"), new ItemStack(Material.CLAY, 1)); + clay.shape(" ", "123", " "); + clay.setIngredient('1', Material.DIRT); + clay.setIngredient('2', Material.SAND); + clay.setIngredient('3', Items.WATER_BOWL.getItemStack()); + CLAY = register(config.recipes_clay, clay); + + ShapelessRecipe diorite = new ShapelessRecipe(Utils.getNamespacedKey("diorite"), new ItemStack(Material.DIORITE, 1)); + diorite.addIngredient(new RecipeChoice.MaterialChoice(Material.BONE_MEAL, Material.WHITE_DYE)); + diorite.addIngredient(Material.COBBLESTONE); + DIORITE = register(config.recipes_diorite, diorite); + + ShapelessRecipe granite = new ShapelessRecipe(Utils.getNamespacedKey("granite"), new ItemStack(Material.GRANITE, 1)); + granite.addIngredient(Material.NETHERRACK); + granite.addIngredient(Material.COBBLESTONE); + GRANITE = register(config.recipes_granite, granite); + + ShapelessRecipe andesite = new ShapelessRecipe(Utils.getNamespacedKey("andesite"), new ItemStack(Material.ANDESITE, 1)); + andesite.addIngredient(Material.GRAVEL); + andesite.addIngredient(Material.COBBLESTONE); + ANDESITE = register(config.recipes_andesite, andesite); + + ShapedRecipe gravel = new ShapedRecipe(NamespacedKey.minecraft("gravel"), new ItemStack(Material.GRAVEL, 2)); + gravel.shape("@B", "B@"); + gravel.setIngredient('@', Material.SAND); + gravel.setIngredient('B', Material.COBBLESTONE); + GRAVEL = register(config.recipes_gravel, gravel); + + ShapedRecipe torch_from_firestriker = new ShapedRecipe(Utils.getNamespacedKey("torch_from_firestriker"), new ItemStack(Material.TORCH, 8)); + ShapedRecipe torch = new ShapedRecipe(Utils.getNamespacedKey("torch"), new ItemStack(Material.TORCH, 16)); + torch_from_firestriker.shape("AAA", "ABA", "AAA"); + torch_from_firestriker.setIngredient('B', Items.FIRESTRIKER.getItemStack()); + torch_from_firestriker.setIngredient('A', Material.STICK); + torch_from_firestriker.setGroup("torch"); + + torch.shape("ACA", "ABA", "AAA"); + torch.setIngredient('C', new RecipeChoice.MaterialChoice(Tag.ITEMS_COALS)); + torch.setIngredient('B', Items.FIRESTRIKER.getItemStack()); + torch.setIngredient('A', Material.STICK); + torch.setGroup("torch"); + TORCH = register(config.survival_torch, torch_from_firestriker, torch); + + ShapelessRecipe flint = new ShapelessRecipe(NamespacedKey.minecraft("flint"), new ItemStack(Material.FLINT, 1)); + flint.addIngredient(Material.GRAVEL); + FLINT = register(config.survival_enabled, flint); + + ShapelessRecipe fermented_spider_eye = new ShapelessRecipe(Utils.getNamespacedKey("fermented_spider_eye"), new ItemStack(Material.FERMENTED_SPIDER_EYE, 1)); + fermented_spider_eye.addIngredient(Material.SPIDER_EYE); + fermented_spider_eye.addIngredient(Material.SUGAR); + fermented_spider_eye.addIngredient(new RecipeChoice.MaterialChoice(Material.RED_MUSHROOM, Material.BROWN_MUSHROOM)); + FERMENTED_SPIDER_EYE = register(config.mechanics_fermented_skin, fermented_spider_eye); // TODO not sure about the config here + + ShapelessRecipe poisonousPotato = new ShapelessRecipe(Utils.getNamespacedKey("poisonous_potato"), new ItemStack(Material.POISONOUS_POTATO, 1)); + poisonousPotato.addIngredient(Material.POTATO); + poisonousPotato.addIngredient(new RecipeChoice.MaterialChoice(Material.BONE_MEAL, Material.WHITE_DYE)); + POISONOUS_POTATO = register(config.mechanics_poison_potato, poisonousPotato); + + ShapelessRecipe glassBottle = new ShapelessRecipe(Utils.getNamespacedKey("glass_bottle"), new ItemStack(Material.GLASS_BOTTLE, 1)); + glassBottle.addIngredient(Material.POTION); + GLASS_BOTTLE = register(config.mechanics_empty_potion, glassBottle); + + ShapedRecipe bowl = new ShapedRecipe(Utils.getNamespacedKey("bowl"), new ItemStack(Material.BOWL, 1)); + bowl.shape(" ", " 1"); + bowl.setIngredient('1', Items.WATER_BOWL.getItemStack()); + BOWL = register(config.mechanics_empty_potion, bowl); + + List dirtyWaters = List.of(Items.DIRTY_WATER.getItemStack(), Items.MURKY_WATER.getItemStack(), Items.SALTY_WATER.getItemStack()); + FurnaceRecipe clean_water_furnace = new FurnaceRecipe(Utils.getNamespacedKey("clean_water_furnace"), + Items.CLEAN_WATER.getItemStack(), new RecipeChoice.ExactChoice(dirtyWaters), 0, 600); + SmokingRecipe clean_water_smoker = new SmokingRecipe(Utils.getNamespacedKey("clean_water_smoker"), + Items.CLEAN_WATER.getItemStack(), new RecipeChoice.ExactChoice(dirtyWaters), 0, 300); + CampfireRecipe clean_water_camp = new CampfireRecipe(Utils.getNamespacedKey("clean_water_campfire"), + Items.CLEAN_WATER.getItemStack(), new RecipeChoice.ExactChoice(dirtyWaters), 0, 2400); + CLEAN_WATER_BOTTLES = register(config.mechanics_thirst_purify_water, clean_water_camp, clean_water_smoker, clean_water_furnace); + + makeBrewingRecipe("dirty_water", Items.DIRTY_WATER); + makeBrewingRecipe("murky_water", Items.MURKY_WATER); + makeBrewingRecipe("salty_water", Items.SALTY_WATER); + makeBrewingRecipe("clean_water", Items.CLEAN_WATER); + + ShapedRecipe fishing_rod = new ShapedRecipe(Utils.getNamespacedKey("fishing_rod"), new ItemStack(Material.FISHING_ROD, 1)); + fishing_rod.shape("1- ", "1 -", "1@*"); + fishing_rod.setIngredient('1', Material.STICK); + fishing_rod.setIngredient('@', Material.IRON_INGOT); + fishing_rod.setIngredient('-', Material.STRING); + fishing_rod.setIngredient('*', Material.FEATHER); + FISHING_ROD = register(config.recipes_fishing_rod, fishing_rod); + + ShapedRecipe iron_ingot = new ShapedRecipe(Utils.getNamespacedKey("iron_ingot"), new ItemStack(Material.IRON_INGOT, 1)); + iron_ingot.shape("@@", "@@"); + iron_ingot.setIngredient('@', Material.IRON_NUGGET); + IRON_INGOT = register(config.mechanics_reduced_iron_nugget, iron_ingot); + + ShapelessRecipe iron_nugget = new ShapelessRecipe(Utils.getNamespacedKey("iron_nugget"), new ItemStack(Material.IRON_NUGGET, 4)); + iron_nugget.addIngredient(Material.IRON_INGOT); + IRON_NUGGET = register(config.mechanics_reduced_iron_nugget, iron_nugget); + + ShapedRecipe gold_ingot = new ShapedRecipe(Utils.getNamespacedKey("gold_ingot"), new ItemStack(Material.GOLD_INGOT, 1)); + gold_ingot.shape("@@", "@@"); + gold_ingot.setIngredient('@', Material.GOLD_NUGGET); + GOLD_INGOT = register(config.mechanics_reduced_gold_nugget, gold_ingot); + + ShapelessRecipe gold_nugget = new ShapelessRecipe(Utils.getNamespacedKey("gold_nugget"), new ItemStack(Material.GOLD_NUGGET, 4)); + gold_nugget.addIngredient(Material.GOLD_INGOT); + GOLD_NUGGET = register(config.mechanics_reduced_gold_nugget, gold_nugget); + + FurnaceRecipe smelt_ironIngot = new FurnaceRecipe(Utils.getNamespacedKey("furnace_iron_ingot"), + new ItemStack(Material.IRON_INGOT, 1), Material.IRON_ORE, 1, 400); + FurnaceRecipe smelt_goldIngot = new FurnaceRecipe(Utils.getNamespacedKey("furnace_gold_ingot"), + new ItemStack(Material.GOLD_INGOT, 1), Material.GOLD_ORE, 1, 400); + BlastingRecipe blast_ironIngot = new BlastingRecipe(Utils.getNamespacedKey("blast_iron_ingot"), + new ItemStack(Material.IRON_INGOT, 1), Material.IRON_ORE, 1, 100); + BlastingRecipe blast_goldIngot = new BlastingRecipe(Utils.getNamespacedKey("blast_gold_ingot"), + new ItemStack(Material.GOLD_INGOT, 1), Material.GOLD_ORE, 1, 100); + FURNACE_IRON_INGOT = register(config.mechanics_reduced_iron_nugget, smelt_ironIngot); + FURNACE_GOLD_INGOT = register(config.mechanics_reduced_gold_nugget, smelt_goldIngot); + BLAST_IRON_INGOT = register(config.mechanics_reduced_iron_nugget, blast_ironIngot); + BLAST_GOLD_INGOT = register(config.mechanics_reduced_gold_nugget, blast_goldIngot); + + ShapedRecipe bread = new ShapedRecipe(Utils.getNamespacedKey("bread"), new ItemStack(Material.BREAD, 2)); + bread.shape(" E ", "WWW"); + bread.setIngredient('E', Material.EGG); + bread.setIngredient('W', Material.WHEAT); + BREAD = register(config.mechanics_farming_products_bread, bread); + + ShapedRecipe cookie = new ShapedRecipe(Utils.getNamespacedKey("cookie"), new ItemStack(Material.COOKIE, 8)); + cookie.shape(" E ", "WCW", " S "); + cookie.setIngredient('E', Material.EGG); + cookie.setIngredient('W', Material.WHEAT); + cookie.setIngredient('S', Material.SUGAR); + cookie.setIngredient('C', Material.COCOA_BEANS); + COOKIE = register(config.mechanics_farming_products_cookie, cookie); + + ShapelessRecipe slimeball = new ShapelessRecipe(Utils.getNamespacedKey("slimeball"), new ItemStack(Material.SLIME_BALL, 1)); + slimeball.addIngredient(Material.MILK_BUCKET); + slimeball.addIngredient(8, Material.VINE); + SLIMEBALL = register(config.recipes_slimeball, slimeball); + + ShapelessRecipe cobweb = new ShapelessRecipe(Utils.getNamespacedKey("cobweb"), new ItemStack(Material.COBWEB, 1)); + cobweb.addIngredient(Material.SLIME_BALL); + cobweb.addIngredient(2, Material.STRING); + COBWEB = register(config.recipes_cobweb, cobweb); + + ShapelessRecipe stick = new ShapelessRecipe(Utils.getNamespacedKey("stick"), new ItemStack(Material.STICK, 4)); + stick.addIngredient(new RecipeChoice.MaterialChoice(Tag.SAPLINGS)); + STICK = register(config.recipes_sapling_stick, stick); + } + + private static void makeBrewingRecipe(String key, Item input) { + PotionMix potionMix = new PotionMix(Utils.getNamespacedKey("purified_water_from_" + key), + Items.PURIFIED_WATER.getItemStack(), + new RecipeChoice.ExactChoice(input.getItemStack()), + new RecipeChoice.MaterialChoice(Material.CHARCOAL)); + Bukkit.getPotionBrewer().addPotionMix(potionMix); + } + + private final Collection keys; + + Recipes(boolean register, Recipe... recipes) { + ArrayList list = new ArrayList<>(); + for (Recipe recipe : recipes) { + if (recipe instanceof Keyed keyedRecipe) { + list.add(keyedRecipe.getKey()); + ALL_RECIPE_KEYS.add(keyedRecipe.getKey()); + if (register) Bukkit.addRecipe(recipe); + } + } + this.keys = list; + } + + public List getKeys() { + return new ArrayList<>(this.keys); + } + + public void unlock(Player player) { + player.discoverRecipes(this.keys); + } + + public static Collection getAllRecipeKeys() { + return ALL_RECIPE_KEYS; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/armor/ArmorPiece.java b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/ArmorPiece.java new file mode 100644 index 0000000..232d83b --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/ArmorPiece.java @@ -0,0 +1,142 @@ +package com.shanebeestudios.survival.api.item.items.armor; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.Equippable; +import net.kyori.adventure.key.Key; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.ItemMeta; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class ArmorPiece extends Item { + + private final ArmorType armorType; + private final ArmorMaterial armorMaterial; + + public ArmorPiece(ArmorType armorType, ArmorMaterial armorMaterial, double armor, double moveSpeed) { + this(armorType, armorMaterial, armor, moveSpeed, 0, 0); + } + + public ArmorPiece(ArmorType armorType, ArmorMaterial armorMaterial, double armor, double moveSpeed, double toughness, double knockback) { + this.armorType = armorType; + this.armorMaterial = armorMaterial; + + ItemStack itemStack = armorMaterial.getItemType(armorType).createItemStack(); + ItemMeta itemMeta = itemStack.getItemMeta(); + + NamespacedKey modKey = NamespacedKey.minecraft("armor." + armorType.key); + + AttributeModifier armorMod = new AttributeModifier(modKey, armor, Operation.ADD_NUMBER, armorType.slotGroup); + itemMeta.addAttributeModifier(Attribute.ARMOR, armorMod); + + AttributeModifier speedMod = new AttributeModifier(modKey, moveSpeed, Operation.ADD_SCALAR, armorType.slotGroup); + itemMeta.addAttributeModifier(Attribute.MOVEMENT_SPEED, speedMod); + + if (toughness > 0) { + AttributeModifier toughnessMod = new AttributeModifier(modKey, toughness, Operation.ADD_NUMBER, armorType.slotGroup); + itemMeta.addAttributeModifier(Attribute.ARMOR_TOUGHNESS, toughnessMod); + } + + if (knockback > 0) { + AttributeModifier knockbackMod = new AttributeModifier(modKey, knockback, Operation.ADD_NUMBER, armorType.slotGroup); + itemMeta.addAttributeModifier(Attribute.KNOCKBACK_RESISTANCE, knockbackMod); + } + + itemStack.setItemMeta(itemMeta); + + // Golden crown override + if (armorMaterial == ArmorMaterial.GOLDEN && armorType == ArmorType.HELMET) { + itemStack.setData(DataComponentTypes.EQUIPPABLE, + Equippable.equippable(EquipmentSlot.HEAD) + .assetId(Key.key("survival_plus:gold")) + .build()); + } + + setupDefaults(armorMaterial.getKey(armorType), itemStack, this.armorMaterial != ArmorMaterial.GOLDEN && this.armorMaterial != ArmorMaterial.LEATHER); + } + + @SuppressWarnings({"DataFlowIssue", "deprecation"}) + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + if (this.armorMaterial == ArmorMaterial.GOLDEN && this.armorType == ArmorType.HELMET) { + recipe.shape("#e#", "###"); + recipe.setIngredient('e', Material.EMERALD); + } else { + recipe.shape(this.armorType.shape); + } + recipe.setIngredient('#', this.armorMaterial.recipeMaterial.asMaterial()); + return recipe; + } + + /** + * Types of armor pieces + */ + public enum ArmorType { + HELMET("helmet", "crown", EquipmentSlotGroup.HEAD, "###", "# #"), + CHESTPLATE("chestplate", "guard", EquipmentSlotGroup.CHEST, "# #", "###", "###"), + LEGGINGS("leggings", "greaves", EquipmentSlotGroup.LEGS, "###", "# #", "# #"), + BOOTS("boots", "sabatons", EquipmentSlotGroup.FEET, "# #", "# #"); + + private final String key; + private final String name; + private final EquipmentSlotGroup slotGroup; + private final String[] shape; + + ArmorType(String key, String name, EquipmentSlotGroup slotGroup, String... shape) { + this.key = key; + this.name = name; + this.slotGroup = slotGroup; + this.shape = shape; + } + + public String getKey() { + return this.key; + } + + public EquipmentSlotGroup getSlotGroup() { + return this.slotGroup; + } + } + + /** + * Material types of armor pieces + */ + public enum ArmorMaterial { + LEATHER("leather", null), + GOLDEN("golden", ItemType.GOLD_INGOT), + IRON("iron", ItemType.IRON_INGOT), + DIAMOND("diamond", ItemType.DIAMOND), + NETHERITE("netherite", ItemType.NETHERITE_INGOT); + + private final String key; + private final ItemType recipeMaterial; + + ArmorMaterial(String key, ItemType recipeMaterial) { + this.key = key; + this.recipeMaterial = recipeMaterial; + } + + public ItemType getItemType(ArmorType armorType) { + String typeKey = this.key + "_" + armorType.key; + return Registry.ITEM.get(NamespacedKey.minecraft(typeKey)); + } + + public String getKey(ArmorType armorType) { + return this.key + "_" + (this == GOLDEN ? armorType.name : armorType.key); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/armor/BeekeeperPiece.java b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/BeekeeperPiece.java new file mode 100644 index 0000000..a71702d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/BeekeeperPiece.java @@ -0,0 +1,72 @@ +package com.shanebeestudios.survival.api.item.items.armor; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.items.armor.ArmorPiece.ArmorMaterial; +import com.shanebeestudios.survival.api.item.items.armor.ArmorPiece.ArmorType; + +@SuppressWarnings("UnstableApiUsage") +public class BeekeeperPiece extends Item { + + private final ArmorType armorType; + + public BeekeeperPiece(ArmorType armorType) { + this.armorType = armorType; + String key = "beekeeper_" + armorType.getKey(); + ItemStack itemStack = ArmorMaterial.LEATHER.getItemType(armorType).createItemStack(); + if (itemStack.getItemMeta() instanceof LeatherArmorMeta leatherArmorMeta) { + int color = ITEM_CONFIG.getColor(key); + if (color > 0) { + leatherArmorMeta.setColor(Color.fromRGB(color)); + leatherArmorMeta.addItemFlags(ItemFlag.HIDE_DYE); + itemStack.setItemMeta(leatherArmorMeta); + } + } + setupDefaults(key, itemStack); + } + + @Override + public Recipe getRecipe() { + switch (this.armorType) { + case HELMET -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("121", "3 3", " "); + recipe.setIngredient('1', Material.HONEYCOMB); + recipe.setIngredient('2', Material.IRON_INGOT); + recipe.setIngredient('3', Material.LEATHER); + return recipe; + } + case CHESTPLATE -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("1 1", "232", "323"); + recipe.setIngredient('1', Material.HONEYCOMB); + recipe.setIngredient('2', Material.IRON_INGOT); + recipe.setIngredient('3', Material.LEATHER); + return recipe; + } + case LEGGINGS -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("131", "3 3", "2 2"); + recipe.setIngredient('1', Material.HONEYCOMB); + recipe.setIngredient('2', Material.IRON_INGOT); + recipe.setIngredient('3', Material.LEATHER); + return recipe; + } + case BOOTS -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape(" ", "1 1", "3 3"); + recipe.setIngredient('1', Material.HONEYCOMB); + recipe.setIngredient('3', Material.LEATHER); + return recipe; + } + } + return null; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/armor/RainBoots.java b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/RainBoots.java new file mode 100644 index 0000000..ef35878 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/RainBoots.java @@ -0,0 +1,34 @@ +package com.shanebeestudios.survival.api.item.items.armor; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.DyedItemColor; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class RainBoots extends Item { + + public RainBoots() { + ItemStack itemStack = ItemType.LEATHER_BOOTS.createItemStack(); + itemStack.setData(DataComponentTypes.DYED_COLOR, + DyedItemColor.dyedItemColor(Color.fromRGB(214, 231, 3), + false)); + setupDefaults("rain_boots", itemStack); + + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("ili"); + recipe.setIngredient('i', Material.IRON_INGOT); + recipe.setIngredient('l', Material.LEATHER_BOOTS); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/armor/ReinforcedPiece.java b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/ReinforcedPiece.java new file mode 100644 index 0000000..221dd80 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/ReinforcedPiece.java @@ -0,0 +1,103 @@ +package com.shanebeestudios.survival.api.item.items.armor; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.Equippable; +import net.kyori.adventure.key.Key; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.ItemMeta; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.items.armor.ArmorPiece.ArmorType; + +@SuppressWarnings("UnstableApiUsage") +public class ReinforcedPiece extends Item { + + private final ArmorType armorType; + + public ReinforcedPiece(ArmorType armorType) { + this.armorType = armorType; + ItemStack itemStack = itemType().createItemStack(); + if (armorType == ArmorType.BOOTS) { + ItemMeta itemMeta = itemStack.getItemMeta(); + AttributeModifier mod = new AttributeModifier(NamespacedKey.minecraft("armor." + armorType.getKey()), 2, Operation.ADD_NUMBER, armorType.getSlotGroup()); + itemMeta.addAttributeModifier(Attribute.ARMOR, mod); + itemStack.setItemMeta(itemMeta); + } + itemStack.setData(DataComponentTypes.EQUIPPABLE, + Equippable.equippable(getSlotGroup()) + .assetId(Key.key("survival_plus:reinforced_leather")) + .build()); + setupDefaults(key(), itemStack); + } + + @Override + public Recipe getRecipe() { + return switch (this.armorType) { + case HELMET -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("@*@"); + recipe.setIngredient('@', Material.IRON_INGOT); + recipe.setIngredient('*', Material.LEATHER_HELMET); + yield recipe; + } + case CHESTPLATE -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape(" @ ", "@*@", " @ "); + recipe.setIngredient('@', Material.IRON_INGOT); + recipe.setIngredient('*', Material.LEATHER_CHESTPLATE); + yield recipe; + } + case LEGGINGS -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape(" @ ", "@*@", " @ "); + recipe.setIngredient('@', Material.IRON_INGOT); + recipe.setIngredient('*', Material.LEATHER_LEGGINGS); + yield recipe; + } + case BOOTS -> { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("@*@"); + recipe.setIngredient('@', Material.IRON_INGOT); + recipe.setIngredient('*', Material.LEATHER_BOOTS); + yield recipe; + } + default -> throw new IllegalStateException("Unexpected value: " + this.armorType); + }; + } + + private String key() { + return "reinforced_leather_" + switch (this.armorType) { + case HELMET -> "helmet"; + case CHESTPLATE -> "tunic"; + case LEGGINGS -> "trousers"; + case BOOTS -> "boots"; + }; + } + + private EquipmentSlot getSlotGroup() { + return switch (this.armorType) { + case HELMET -> EquipmentSlot.HEAD; + case CHESTPLATE -> EquipmentSlot.CHEST; + case LEGGINGS -> EquipmentSlot.LEGS; + case BOOTS -> EquipmentSlot.FEET; + }; + } + + private ItemType itemType() { + return switch (this.armorType) { + case HELMET -> ItemType.LEATHER_HELMET; + case CHESTPLATE -> ItemType.LEATHER_CHESTPLATE; + case LEGGINGS -> ItemType.LEATHER_LEGGINGS; + case BOOTS -> ItemType.LEATHER_BOOTS; + }; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/armor/SnowBoots.java b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/SnowBoots.java new file mode 100644 index 0000000..0186447 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/SnowBoots.java @@ -0,0 +1,33 @@ +package com.shanebeestudios.survival.api.item.items.armor; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.DyedItemColor; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class SnowBoots extends Item { + + public SnowBoots() { + ItemStack itemStack = ItemType.LEATHER_BOOTS.createItemStack(); + itemStack.setData(DataComponentTypes.DYED_COLOR, + DyedItemColor.dyedItemColor(Color.fromRGB(158, 201, 202), + false)); + setupDefaults("snow_boots", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("dld"); + recipe.setIngredient('d', Material.DIAMOND); + recipe.setIngredient('l', Material.LEATHER_BOOTS); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/armor/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/package-info.java new file mode 100644 index 0000000..2ccd1dc --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/armor/package-info.java @@ -0,0 +1,4 @@ +/** + * Armor {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item.items.armor; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/Campfire.java b/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/Campfire.java new file mode 100644 index 0000000..3e2f082 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/Campfire.java @@ -0,0 +1,39 @@ +package com.shanebeestudios.survival.api.item.items.blocks; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.block.data.BlockData; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice.MaterialChoice; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.BlockDataMeta; +import org.bukkit.inventory.meta.ItemMeta; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class Campfire extends Item { + + public Campfire() { + ItemStack campfire = ItemType.CAMPFIRE.createItemStack(); + ItemMeta campfireMeta = campfire.getItemMeta(); + BlockData data = Bukkit.createBlockData("minecraft:campfire[lit=false]"); + ((BlockDataMeta) campfireMeta).setBlockData(data); + campfire.setItemMeta(campfireMeta); + setupDefaults("unlit_campfire", campfire); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + recipe.shape(" s ", "scs", "lll"); + recipe.setIngredient('s', Material.STICK); + recipe.setIngredient('c', new MaterialChoice(Tag.ITEMS_COALS)); + recipe.setIngredient('l', new MaterialChoice(Tag.LOGS)); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/Workbench.java b/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/Workbench.java new file mode 100644 index 0000000..a3b3785 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/Workbench.java @@ -0,0 +1,32 @@ +package com.shanebeestudios.survival.api.item.items.blocks; + +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.ShapelessRecipe; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.Items; + +@SuppressWarnings("UnstableApiUsage") +public class Workbench extends Item { + + public Workbench() { + ItemStack itemStack = ItemType.CRAFTING_TABLE.createItemStack(); + setupDefaults("workbench", itemStack, true); + } + + @Override + public Recipe getRecipe() { + ShapelessRecipe recipe = new ShapelessRecipe(this.recipeKey, this.getItemStack()); + + recipe.addIngredient(new RecipeChoice.MaterialChoice(Tag.LOGS)); + recipe.addIngredient(Material.LEATHER); + recipe.addIngredient(Material.STRING); + recipe.addIngredient(Items.HAMMER.getItemStack()); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/package-info.java new file mode 100644 index 0000000..7a70405 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/blocks/package-info.java @@ -0,0 +1,4 @@ +/** + * Block {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item.items.blocks; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/Coffee.java b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/Coffee.java new file mode 100644 index 0000000..2719b40 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/Coffee.java @@ -0,0 +1,31 @@ +package com.shanebeestudios.survival.api.item.items.drinks; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.ShapedRecipe; +import com.shanebeestudios.survival.api.item.Items; + +@SuppressWarnings("UnstableApiUsage") +public class Coffee extends DrinkItem { + + public Coffee() { + ItemStack itemStack = ItemType.STICK.createItemStack(); + setupDefaults("coffee", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack(2)); + + recipe.shape(" ", "12 ", "34 "); + recipe.setIngredient('1', new RecipeChoice.ExactChoice(Items.COFFEE_BEAN.getItemStack())); + recipe.setIngredient('2', Material.COCOA_BEANS); + recipe.setIngredient('3', new RecipeChoice.ExactChoice(Items.HOT_MILK.getItemStack())); + recipe.setIngredient('4', new RecipeChoice.ExactChoice(Items.PURIFIED_WATER.getItemStack())); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/ColdMilk.java b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/ColdMilk.java new file mode 100644 index 0000000..c69ce0a --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/ColdMilk.java @@ -0,0 +1,32 @@ +package com.shanebeestudios.survival.api.item.items.drinks; + +import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +import java.util.List; + +@SuppressWarnings("UnstableApiUsage") +public class ColdMilk extends DrinkItem { + + public ColdMilk() { + ItemStack itemStack = ItemType.STICK.createItemStack(); + setupDefaults("cold_milk", itemStack, List.of( + ConsumeEffect.clearAllStatusEffects() + )); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + recipe.shape(" ", "12 ", " "); + recipe.setIngredient('1', Material.MILK_BUCKET); + recipe.setIngredient('2', Material.GLASS_BOTTLE); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/DrinkItem.java b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/DrinkItem.java new file mode 100644 index 0000000..fb6a8a6 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/DrinkItem.java @@ -0,0 +1,61 @@ +package com.shanebeestudios.survival.api.item.items.drinks; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.Consumable; +import io.papermc.paper.datacomponent.item.UseRemainder; +import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect; +import io.papermc.paper.datacomponent.item.consumable.ItemUseAnimation; +import net.kyori.adventure.key.Key; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import com.shanebeestudios.survival.api.item.Item; + +import java.util.List; + +/** + * Represents a drinkable {@link Item} that has a thirst level + */ +@SuppressWarnings("UnstableApiUsage") +public abstract class DrinkItem extends Item { + + private double thirstLevel; + + @Override + protected void setupDefaults(String key, ItemStack itemStack) { + this.thirstLevel = ITEM_CONFIG.getDouble(key, "thirst_level", 1); + super.setupDefaults(key, itemStack); + } + + @Override + protected void setupDefaults(String key, ItemStack itemStack, boolean vanillaModel) { + this.thirstLevel = ITEM_CONFIG.getDouble(key, "thirst_level", 1); + super.setupDefaults(key, itemStack, vanillaModel); + } + + protected void setupDefaults(String key, ItemStack itemStack, @NotNull List effects) { + setupDefaults(key, itemStack, effects, null); + } + + protected void setupDefaults(String key, ItemStack itemStack, @NotNull List effects, @Nullable ItemStack remainder) { + Consumable.Builder consumable = Consumable.consumable(); + consumable.hasConsumeParticles(false); + consumable.sound(Key.key("minecraft:entity.generic.drink")); + consumable.animation(ItemUseAnimation.DRINK); + if (!effects.isEmpty()) { + consumable.addEffects(effects); + } + + itemStack.setData(DataComponentTypes.CONSUMABLE, consumable.build()); + itemStack.setData(DataComponentTypes.MAX_STACK_SIZE, 1); + UseRemainder useRemainder = UseRemainder.useRemainder(remainder != null ? remainder : new ItemStack(Material.GLASS_BOTTLE)); + itemStack.setData(DataComponentTypes.USE_REMAINDER, useRemainder); + setupDefaults(key, itemStack); + } + + public double getThirstLevel() { + return this.thirstLevel; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/HotMilk.java b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/HotMilk.java new file mode 100644 index 0000000..9f15a2b --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/HotMilk.java @@ -0,0 +1,35 @@ +package com.shanebeestudios.survival.api.item.items.drinks; + +import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect; +import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect.ApplyStatusEffects; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.SmokingRecipe; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import com.shanebeestudios.survival.api.item.Items; + +import java.util.List; + + +@SuppressWarnings("UnstableApiUsage") +public class HotMilk extends DrinkItem { + + public HotMilk() { + ItemStack itemStack = ItemType.STICK.createItemStack(); + ApplyStatusEffects effects = ConsumeEffect.applyStatusEffects(List.of( + new PotionEffect(PotionEffectType.HUNGER, 100, 0, true, false, false), + new PotionEffect(PotionEffectType.INSTANT_DAMAGE, 1, 0, true, false, false)), + 1.0f); + setupDefaults("hot_milk", itemStack, List.of(effects)); + } + + @Override + public Recipe getRecipe() { + return new SmokingRecipe(this.recipeKey, this.getItemStack(), + new RecipeChoice.ExactChoice(Items.COLD_MILK.getItemStack()), 0, 200); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/Water.java b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/Water.java new file mode 100644 index 0000000..65c373d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/Water.java @@ -0,0 +1,97 @@ +package com.shanebeestudios.survival.api.item.items.drinks; + +import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; + +/** + * {@link com.shanebeestudios.survival.api.item.Item} class for water based drinks + */ +@SuppressWarnings("UnstableApiUsage") +public class Water extends DrinkItem { + + public Water(String key) { + this(key, List.of()); + } + + public Water(String key, List effects) { + this(key, effects, null); + } + + public Water(String key, List effects, ItemStack remainder) { + ItemStack itemStack = ItemType.STICK.createItemStack(); + setupDefaults(key, itemStack, effects, remainder); + } + + /** + * @hidden + */ + public static Water dirty() { + PotionEffect poison = new PotionEffect(PotionEffectType.POISON, 100, 0); + PotionEffect nausea = new PotionEffect(PotionEffectType.NAUSEA, 200, 0); + return new Water("dirty_water", List.of( + ConsumeEffect.applyStatusEffects(List.of(poison), 0.5f), + ConsumeEffect.applyStatusEffects(List.of(nausea), 1.0f) + )); + } + + /** + * @hidden + */ + public static Water salty() { + PotionEffect hunger = new PotionEffect(PotionEffectType.HUNGER, 400, 0); + PotionEffect nausea = new PotionEffect(PotionEffectType.NAUSEA, 100, 0); + PotionEffect slowness = new PotionEffect(PotionEffectType.SLOWNESS, 400, 0); + return new Water("salty_water", List.of( + ConsumeEffect.applyStatusEffects(List.of(hunger), 0.75f), + ConsumeEffect.applyStatusEffects(List.of(nausea), 0.5f), + ConsumeEffect.applyStatusEffects(List.of(slowness), 0.5f) + )); + } + + /** + * @hidden + */ + public static Water murky() { + PotionEffect poison = new PotionEffect(PotionEffectType.POISON, 200, 2); + PotionEffect nausea = new PotionEffect(PotionEffectType.NAUSEA, 1000, 0); + PotionEffect weakness = new PotionEffect(PotionEffectType.WEAKNESS, 1000, 0); + PotionEffect slowness = new PotionEffect(PotionEffectType.SLOWNESS, 400, 0); + return new Water("murky_water", List.of( + ConsumeEffect.applyStatusEffects(List.of(poison), 0.8f), + ConsumeEffect.applyStatusEffects(List.of(nausea), 0.5f), + ConsumeEffect.applyStatusEffects(List.of(weakness), 1.0f), + ConsumeEffect.applyStatusEffects(List.of(slowness), 0.2f) + )); + } + + /** + * @hidden + */ + public static Water clean() { + return new Water("clean_water"); + } + + /** + * @hidden + */ + public static Water purified() { + PotionEffect health = new PotionEffect(PotionEffectType.HEALTH_BOOST, 100, 2); + return new Water("purified_water", List.of( + ConsumeEffect.applyStatusEffects(List.of(health), 0.5f) + )); + } + + /** + * @hidden + */ + public static Water waterBowl() { + return new Water("water_bowl", List.of(), new ItemStack(Material.BOWL)); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/package-info.java new file mode 100644 index 0000000..f60f8e4 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/drinks/package-info.java @@ -0,0 +1,4 @@ +/** + * Drinkable {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item.items.drinks; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/food/SuspiciousMeat.java b/src/main/java/com/shanebeestudios/survival/api/item/items/food/SuspiciousMeat.java new file mode 100644 index 0000000..4b26f90 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/food/SuspiciousMeat.java @@ -0,0 +1,60 @@ +package com.shanebeestudios.survival.api.item.items.food; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.SuspiciousStewEffects; +import io.papermc.paper.potion.SuspiciousEffectEntry; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.potion.PotionEffectType; +import com.shanebeestudios.survival.api.item.Item; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +@SuppressWarnings("UnstableApiUsage") +public class SuspiciousMeat extends Item { + + private static final List POTION_EFFECTS = new ArrayList<>(); + + @SuppressWarnings("UnstableApiUsage") + public SuspiciousMeat() { + ItemStack itemStack = ItemType.APPLE.createItemStack(); + setupDefaults("suspicious_meat", itemStack); + } + + @Override + public ItemStack getItemStack(int amount) { + // Add random effect when item is requested + ItemStack itemStack = super.getItemStack(amount); + itemStack.setData(DataComponentTypes.SUSPICIOUS_STEW_EFFECTS, SuspiciousStewEffects.suspiciousStewEffects().add(getRandomEffect()).build()); + return itemStack; + } + + static { + // BAD + POTION_EFFECTS.add(PotionEffectType.BAD_OMEN); + POTION_EFFECTS.add(PotionEffectType.NAUSEA); + POTION_EFFECTS.add(PotionEffectType.POISON); + POTION_EFFECTS.add(PotionEffectType.UNLUCK); + POTION_EFFECTS.add(PotionEffectType.HUNGER); + POTION_EFFECTS.add(PotionEffectType.INSTANT_DAMAGE); + POTION_EFFECTS.add(PotionEffectType.SLOWNESS); + // GOOD + POTION_EFFECTS.add(PotionEffectType.DOLPHINS_GRACE); + POTION_EFFECTS.add(PotionEffectType.ABSORPTION); + POTION_EFFECTS.add(PotionEffectType.HASTE); + POTION_EFFECTS.add(PotionEffectType.LUCK); + POTION_EFFECTS.add(PotionEffectType.HEALTH_BOOST); + POTION_EFFECTS.add(PotionEffectType.REGENERATION); + POTION_EFFECTS.add(PotionEffectType.SPEED); + } + + private static SuspiciousEffectEntry getRandomEffect() { + Random random = new Random(); + int randomEffect = random.nextInt(POTION_EFFECTS.size()); + int randomDuration = random.nextInt(200) + 200; + return SuspiciousEffectEntry.create(POTION_EFFECTS.get(randomEffect), randomDuration); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/food/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/items/food/package-info.java new file mode 100644 index 0000000..86172b1 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/food/package-info.java @@ -0,0 +1,4 @@ +/** + * Edible {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item.items.food; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/BlazeSword.java b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/BlazeSword.java new file mode 100644 index 0000000..cde23d9 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/BlazeSword.java @@ -0,0 +1,59 @@ +package com.shanebeestudios.survival.api.item.items.legendary; + +import com.shanebeestudios.survival.api.registry.Enchantments; +import io.papermc.paper.datacomponent.DataComponentTypes; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.ItemMeta; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class BlazeSword extends Item { + + public BlazeSword() { + ItemStack itemStack = ItemType.DIAMOND_SWORD.createItemStack(); + ItemMeta itemMeta = itemStack.getItemMeta(); + + int gSword_dmg = 6; + float gSword_spd = 1.6f; + int gSword_health = -6; + + AttributeModifier i_gSwordDamage = new AttributeModifier(BASE_ATTACK_DAMAGE, gSword_dmg - 1, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + itemMeta.addAttributeModifier(Attribute.ATTACK_DAMAGE, i_gSwordDamage); + + AttributeModifier i_gSwordSpeed = new AttributeModifier(BASE_ATTACK_SPEED, gSword_spd - 4, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + itemMeta.addAttributeModifier(Attribute.ATTACK_SPEED, i_gSwordSpeed); + + AttributeModifier i_gSwordHealth = new AttributeModifier(NamespacedKey.minecraft("base_max_health"), gSword_health, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + itemMeta.addAttributeModifier(Attribute.MAX_HEALTH, i_gSwordHealth); + + itemMeta.addEnchant(Enchantment.FIRE_ASPECT, 2, true); + itemMeta.addEnchant(Enchantment.UNBREAKING, 3, false); + itemMeta.addEnchant(Enchantments.BLAZING, 1, true); + itemStack.setItemMeta(itemMeta); + + itemStack.unsetData(DataComponentTypes.REPAIRABLE); + setupDefaults("blaze_sword", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe blaze_sword = new ShapedRecipe(this.recipeKey, this.getItemStack()); + blaze_sword.shape("BgB", "BgB", "BbB"); + + blaze_sword.setIngredient('g', Material.GOLD_INGOT); + blaze_sword.setIngredient('b', Material.BLAZE_ROD); + blaze_sword.setIngredient('B', Material.BLAZE_POWDER); + return blaze_sword; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/EnderGiantBlade.java b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/EnderGiantBlade.java new file mode 100644 index 0000000..56b830b --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/EnderGiantBlade.java @@ -0,0 +1,63 @@ +package com.shanebeestudios.survival.api.item.items.legendary; + +import com.shanebeestudios.survival.api.registry.Enchantments; +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import io.papermc.paper.datacomponent.item.ItemEnchantments; +import io.papermc.paper.datacomponent.item.UseCooldown; +import net.kyori.adventure.key.Key; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class EnderGiantBlade extends Item { + + private final double chargeDamage; + + public EnderGiantBlade() { + String key = "ender_giant_blade"; + ItemStack itemStack = ItemType.DIAMOND_SWORD.createItemStack(); + + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, new AttributeModifier(BASE_ATTACK_DAMAGE, 8f, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND)) + .addModifier(Attribute.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED, -2.5f, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND)) + .addModifier(Attribute.MOVEMENT_SPEED, new AttributeModifier(BASE_MOVEMENT_SPEED, -0.5f, Operation.ADD_SCALAR, EquipmentSlotGroup.OFFHAND)) + .build()); + itemStack.setData(DataComponentTypes.ENCHANTMENTS, ItemEnchantments.itemEnchantments() + .add(Enchantments.ENDER_POWER, 3) + .build()); + + itemStack.setData(DataComponentTypes.USE_COOLDOWN, UseCooldown.useCooldown(10) + .cooldownGroup(Key.key("survival_plus:" + key)).build()); + this.chargeDamage = ITEM_CONFIG.getDouble(key, "charge_damage", 3); + setupDefaults(key, itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + recipe.shape(" dd", "Ded", "pD "); + + recipe.setIngredient('e', Material.ENDER_EYE); + recipe.setIngredient('d', Material.DIAMOND); + recipe.setIngredient('D', Material.DIAMOND_BLOCK); + recipe.setIngredient('p', new RecipeChoice.MaterialChoice(Tag.PLANKS)); + return recipe; + } + + public double getChargeDamage() { + return this.chargeDamage; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/ObsidianMace.java b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/ObsidianMace.java new file mode 100644 index 0000000..3ac488c --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/ObsidianMace.java @@ -0,0 +1,55 @@ +package com.shanebeestudios.survival.api.item.items.legendary; + +import com.shanebeestudios.survival.api.registry.Enchantments; +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import io.papermc.paper.datacomponent.item.ItemEnchantments; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemRarity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class ObsidianMace extends Item { + + public ObsidianMace() { + ItemStack itemStack = ItemType.MACE.createItemStack(); + + itemStack.setData(DataComponentTypes.ENCHANTMENTS, ItemEnchantments.itemEnchantments() + .add(Enchantments.OBSIDIAN_POWER, 1) + .add(Enchantment.KNOCKBACK, 3) + .add(Enchantment.UNBREAKING, 5) + .add(Enchantment.BINDING_CURSE, 1) + .build()); + + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, new AttributeModifier(BASE_ATTACK_DAMAGE, 6f, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND)) + .addModifier(Attribute.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED, -3.2f, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND)) + .addModifier(Attribute.KNOCKBACK_RESISTANCE, new AttributeModifier(NamespacedKey.minecraft("base_attack_resistance"), 0.5f, Operation.ADD_SCALAR, EquipmentSlotGroup.HAND)) + .addModifier(Attribute.MOVEMENT_SPEED, new AttributeModifier(BASE_MOVEMENT_SPEED, -0.2, Operation.ADD_SCALAR, EquipmentSlotGroup.HAND)) + .build()); + + itemStack.setData(DataComponentTypes.RARITY, ItemRarity.EPIC); + setupDefaults("obsidian_mace", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape(" oo", " eo", "s "); + recipe.setIngredient('o', Material.OBSIDIAN); + recipe.setIngredient('e', Material.END_CRYSTAL); + recipe.setIngredient('s', Material.STICK); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/QuartzPickaxe.java b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/QuartzPickaxe.java new file mode 100644 index 0000000..0cefdd5 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/QuartzPickaxe.java @@ -0,0 +1,50 @@ +package com.shanebeestudios.survival.api.item.items.legendary; + +import com.shanebeestudios.survival.api.registry.Enchantments; +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import io.papermc.paper.datacomponent.item.ItemEnchantments; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class QuartzPickaxe extends Item { + + public QuartzPickaxe() { + ItemStack itemStack = ItemType.DIAMOND_PICKAXE.createItemStack(); + + itemStack.setData(DataComponentTypes.ENCHANTMENTS, ItemEnchantments.itemEnchantments() + .add(Enchantment.SILK_TOUCH, 1) + .add(Enchantments.QUARTZ_MINING, 1) + .build()); + + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, new AttributeModifier(BASE_ATTACK_DAMAGE, 2.0, Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND)) + .addModifier(Attribute.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED, -3.0, Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND)) + .build()); + setupDefaults("quartz_pickaxe", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("qDd", "De ", "d s"); + + recipe.setIngredient('q', Material.QUARTZ_BLOCK); + recipe.setIngredient('d', Material.DIAMOND); + recipe.setIngredient('D', Material.DIAMOND_BLOCK); + recipe.setIngredient('s', Material.STICK); + recipe.setIngredient('e', Material.DRAGON_EGG); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/ValkyriesAxe.java b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/ValkyriesAxe.java new file mode 100644 index 0000000..95fcb7c --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/ValkyriesAxe.java @@ -0,0 +1,47 @@ +package com.shanebeestudios.survival.api.item.items.legendary; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.ItemMeta; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class ValkyriesAxe extends Item { + + public ValkyriesAxe() { + ItemStack itemStack = ItemType.DIAMOND_AXE.createItemStack(); + ItemMeta itemMeta = itemStack.getItemMeta(); + + int gAxe_spd = 1; + int gAxe_dmg = 8; // TODO, why is this here? + + AttributeModifier i_gAxeSpeed = new AttributeModifier(BASE_ATTACK_SPEED, gAxe_spd - 4, Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + itemMeta.addAttributeModifier(Attribute.ATTACK_SPEED, i_gAxeSpeed); + + itemMeta.addEnchant(Enchantment.UNBREAKING, 5, true); + itemStack.setItemMeta(itemMeta); + + itemStack.unsetData(DataComponentTypes.REPAIRABLE); + setupDefaults("valkyries_axe", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("ddd", "dnd", " s "); + recipe.setIngredient('d', Material.DIAMOND); + recipe.setIngredient('n', Material.NETHER_STAR); + recipe.setIngredient('s', Material.STICK); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/package-info.java new file mode 100644 index 0000000..c39e8cf --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/legendary/package-info.java @@ -0,0 +1,4 @@ +/** + * Legendary {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item.items.legendary; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/misc/BreedingEgg.java b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/BreedingEgg.java new file mode 100644 index 0000000..bc22769 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/BreedingEgg.java @@ -0,0 +1,15 @@ +package com.shanebeestudios.survival.api.item.items.misc; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class BreedingEgg extends Item { + + public BreedingEgg() { + ItemStack itemStack = ItemType.EGG.createItemStack(); + setupDefaults("breeding_egg", itemStack); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/misc/CoffeeBean.java b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/CoffeeBean.java new file mode 100644 index 0000000..d98554d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/CoffeeBean.java @@ -0,0 +1,24 @@ +package com.shanebeestudios.survival.api.item.items.misc; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.SmokingRecipe; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class CoffeeBean extends Item { + + public CoffeeBean() { + ItemStack itemStack = ItemType.COCOA_BEANS.createItemStack(); + setupDefaults("coffee_bean", itemStack); + } + + @Override + public Recipe getRecipe() { + return new SmokingRecipe(this.recipeKey, this.getItemStack(), + Material.COCOA_BEANS, 0, 200); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/misc/FermentedSkin.java b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/FermentedSkin.java new file mode 100644 index 0000000..2db4f35 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/FermentedSkin.java @@ -0,0 +1,29 @@ +package com.shanebeestudios.survival.api.item.items.misc; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.ShapelessRecipe; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class FermentedSkin extends Item { + + public FermentedSkin() { + ItemStack itemStack = ItemType.RABBIT_HIDE.createItemStack(); // TODO rotten flesh instead? maybe an apple?!?! + setupDefaults("fermented_skin", itemStack); + + } + + @Override + public Recipe getRecipe() { + ShapelessRecipe recipe = new ShapelessRecipe(this.recipeKey, this.getItemStack()); + recipe.addIngredient(Material.ROTTEN_FLESH); + recipe.addIngredient(Material.SUGAR); + recipe.addIngredient(new RecipeChoice.MaterialChoice(Material.BROWN_MUSHROOM, Material.RED_MUSHROOM)); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/misc/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/package-info.java new file mode 100644 index 0000000..8bd42a3 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/misc/package-info.java @@ -0,0 +1,4 @@ +/** + * Misc {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item.items.misc; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Compass.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Compass.java new file mode 100644 index 0000000..428cadc --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Compass.java @@ -0,0 +1,27 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class Compass extends Item { + + public Compass() { + ItemStack itemStack = ItemType.COMPASS.createItemStack(); + setupDefaults("compass", itemStack, true); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape(" i ", "iri", " i "); + recipe.setIngredient('i', Material.IRON_INGOT); + recipe.setIngredient('r', Material.REDSTONE); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/FireStriker.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/FireStriker.java new file mode 100644 index 0000000..38e6811 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/FireStriker.java @@ -0,0 +1,43 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice; +import org.bukkit.inventory.ShapelessRecipe; +import org.bukkit.inventory.meta.ItemMeta; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class FireStriker extends Item { + + private final int maxCooks; + + public FireStriker() { + ItemStack itemStack = ItemType.STICK.createItemStack(); + this.maxCooks = ITEM_CONFIG.getInt("firestriker", "max_cooks", 8); + itemStack.setData(DataComponentTypes.MAX_DAMAGE, this.maxCooks); + itemStack.setData(DataComponentTypes.DAMAGE, 0); + itemStack.setData(DataComponentTypes.MAX_STACK_SIZE, 1); + ItemMeta itemMeta = itemStack.getItemMeta(); + + itemStack.setItemMeta(itemMeta); + setupDefaults("firestriker", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapelessRecipe recipe = new ShapelessRecipe(this.recipeKey, this.getItemStack()); + recipe.addIngredient(Material.FLINT); + recipe.addIngredient(new RecipeChoice.MaterialChoice(Tag.ITEMS_COALS)); + return recipe; + } + + public int getMaxCooks() { + return this.maxCooks; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/GrapplingHook.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/GrapplingHook.java new file mode 100644 index 0000000..1363ee5 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/GrapplingHook.java @@ -0,0 +1,29 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import com.shanebeestudios.survival.api.item.Item; + +@SuppressWarnings("UnstableApiUsage") +public class GrapplingHook extends Item { + + public GrapplingHook() { + ItemStack itemStack = ItemType.FISHING_ROD.createItemStack(); + setupDefaults("grappling_hook", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + recipe.shape(" i ", "fsf", " i "); + recipe.setIngredient('f', Material.FISHING_ROD); + recipe.setIngredient('s', Material.STRING); + recipe.setIngredient('i', Material.IRON_INGOT); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Hammer.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Hammer.java new file mode 100644 index 0000000..55229ca --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Hammer.java @@ -0,0 +1,48 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.Enchantable; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import io.papermc.paper.datacomponent.item.Tool; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +public class Hammer extends Item { + + @SuppressWarnings("UnstableApiUsage") + public Hammer() { + ItemStack itemStack = ItemType.STICK.createItemStack(); + + itemStack.setData(DataComponentTypes.TOOL, Tool.tool() + .defaultMiningSpeed(0.0001f) + .build()); + + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, new AttributeModifier(BASE_ATTACK_DAMAGE, 2.5d, Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND)) + .addModifier(Attribute.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED, -3.0d, Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND)) + .build()); + + itemStack.setData(DataComponentTypes.MAX_STACK_SIZE, 1); + itemStack.setData(DataComponentTypes.ENCHANTABLE, Enchantable.enchantable(1)); + + setupDefaults("hammer", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("c ", "sc"); + recipe.setIngredient('c', Material.COBBLESTONE); + recipe.setIngredient('s', Material.STICK); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Hatchet.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Hatchet.java new file mode 100644 index 0000000..a57f7eb --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Hatchet.java @@ -0,0 +1,49 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import io.papermc.paper.datacomponent.item.Tool; +import io.papermc.paper.registry.keys.tags.BlockTypeTagKeys; +import net.kyori.adventure.util.TriState; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class Hatchet extends Item { + + public Hatchet() { + ItemStack itemStack = ItemType.WOODEN_AXE.createItemStack(); + + AttributeModifier attackDamage = new AttributeModifier(BASE_ATTACK_DAMAGE, 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + AttributeModifier attackSpeed = new AttributeModifier(BASE_ATTACK_SPEED, -3.5, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, attackDamage) + .addModifier(Attribute.ATTACK_SPEED, attackSpeed) + .build()); + + itemStack.setData(DataComponentTypes.TOOL, Tool.tool() + .defaultMiningSpeed(0.0001f) + .addRule(Tool.rule(getBlockTag(BlockTypeTagKeys.INCORRECT_FOR_WOODEN_TOOL), 0.0001f, TriState.FALSE)) + .addRule(Tool.rule(getBlockTag(BlockTypeTagKeys.LOGS), 0.35f, TriState.FALSE)) + .addRule(Tool.rule(getBlockTag(BlockTypeTagKeys.MINEABLE_AXE), 0.75f, TriState.TRUE)) + .build()); + setupDefaults("hatchet", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("ff", " s"); + recipe.setIngredient('f', Material.FLINT); + recipe.setIngredient('s', Material.STICK); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Mattock.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Mattock.java new file mode 100644 index 0000000..aeac3c8 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Mattock.java @@ -0,0 +1,53 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import io.papermc.paper.datacomponent.item.Tool; +import io.papermc.paper.registry.keys.tags.BlockTypeTagKeys; +import net.kyori.adventure.util.TriState; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.RecipeChoice.MaterialChoice; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class Mattock extends Item { + + public Mattock() { + ItemStack itemStack = ItemType.WOODEN_PICKAXE.createItemStack(); + + AttributeModifier attackDamage = new AttributeModifier(BASE_ATTACK_DAMAGE, 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + AttributeModifier attackSpeed = new AttributeModifier(BASE_ATTACK_SPEED, -3.5, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlotGroup.HAND); + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, attackDamage) + .addModifier(Attribute.ATTACK_SPEED, attackSpeed) + .build()); + + itemStack.setData(DataComponentTypes.TOOL, Tool.tool() + .defaultMiningSpeed(0.0001f) + .addRule(Tool.rule(getBlockTag(BlockTypeTagKeys.INCORRECT_FOR_WOODEN_TOOL), 0.0001f, TriState.FALSE)) + .addRule(Tool.rule(getBlockTag(BlockTypeTagKeys.BASE_STONE_OVERWORLD), 0.25f, TriState.TRUE)) + .addRule(Tool.rule(getBlockTag(BlockTypeTagKeys.MINEABLE_PICKAXE), 0.75f, TriState.TRUE)) + .build()); + + setupDefaults("mattock", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("fp", "sf"); + recipe.setIngredient('f', Material.FLINT); + recipe.setIngredient('p', new MaterialChoice(Tag.PLANKS)); + recipe.setIngredient('s', Material.STICK); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/MedicKit.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/MedicKit.java new file mode 100644 index 0000000..c7c7aae --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/MedicKit.java @@ -0,0 +1,39 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.util.ItemUtils; + +@SuppressWarnings("UnstableApiUsage") +public class MedicKit extends Item { + + public MedicKit() { + ItemStack itemStack = ItemType.STICK.createItemStack(); + int maxHeals = ITEM_CONFIG.getInt("medic_kit", "max_heals", 10); + itemStack.setData(DataComponentTypes.MAX_DAMAGE, maxHeals); + itemStack.setData(DataComponentTypes.DAMAGE, 0); + itemStack.setData(DataComponentTypes.MAX_STACK_SIZE, 1); + setupDefaults("medic_kit", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape(" g ", "fgp", " g "); + recipe.setIngredient('g', Material.GOLD_INGOT); + recipe.setIngredient('f', Material.FEATHER); + recipe.setIngredient('g', Material.GLISTERING_MELON_SLICE); + recipe.setIngredient('p', Material.PAPER); + return recipe; + } + + public boolean canHeal(ItemStack itemStack) { + return ItemUtils.getDurability(itemStack) > 0; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/RecurvedBow.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/RecurvedBow.java new file mode 100644 index 0000000..6f1fe4f --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/RecurvedBow.java @@ -0,0 +1,38 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import com.shanebeestudios.survival.api.item.Item; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.meta.ItemMeta; + +@SuppressWarnings("UnstableApiUsage") +public class RecurvedBow extends Item { + + public RecurvedBow() { + this("recurved_bow", ItemType.BOW.createItemStack()); + } + + public RecurvedBow(String key, ItemStack itemStack) { + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.addEnchant(Enchantment.PUNCH, 1, true); + itemStack.setItemMeta(itemMeta); + setupDefaults(key, itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + recipe.shape(" is", "pbs", " is"); + recipe.setIngredient('b', Material.BOW); + recipe.setIngredient('p', Material.PISTON); + recipe.setIngredient('i', Material.IRON_INGOT); + recipe.setIngredient('s', Material.STRING); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/RecurvedCrossbow.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/RecurvedCrossbow.java new file mode 100644 index 0000000..83d3549 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/RecurvedCrossbow.java @@ -0,0 +1,27 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class RecurvedCrossbow extends RecurvedBow { + + public RecurvedCrossbow() { + super("recurved_crossbow", ItemType.CROSSBOW.createItemStack()); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + recipe.shape(" dm", "pcm", " dm"); + recipe.setIngredient('d', Material.DIAMOND); + recipe.setIngredient('m', Material.PHANTOM_MEMBRANE); + recipe.setIngredient('p', Material.PISTON); + recipe.setIngredient('c', Material.CROSSBOW); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Shiv.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Shiv.java new file mode 100644 index 0000000..1e4a3a0 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Shiv.java @@ -0,0 +1,44 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class Shiv extends Item { + + public Shiv() { + ItemStack itemStack = ItemType.WOODEN_SWORD.createItemStack(); + + AttributeModifier attackDamage = new AttributeModifier(BASE_ATTACK_DAMAGE, 3, Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND); + AttributeModifier attackSpeed = new AttributeModifier(BASE_ATTACK_SPEED, -2.2, Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND); + + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, attackDamage) + .addModifier(Attribute.ATTACK_SPEED, attackSpeed) + .build()); + + setupDefaults("shiv", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + recipe.shape("*f", "se"); + recipe.setIngredient('f', Material.FLINT); + recipe.setIngredient('s', Material.STICK); + recipe.setIngredient('*', Material.STRING); + recipe.setIngredient('e', Material.SPIDER_EYE); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Sickle.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Sickle.java new file mode 100644 index 0000000..060342b --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/Sickle.java @@ -0,0 +1,61 @@ +package com.shanebeestudios.survival.api.item.items.tools; + +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.registry.BlockTags; +import io.papermc.paper.datacomponent.DataComponentTypes; +import io.papermc.paper.datacomponent.item.ItemAttributeModifiers; +import io.papermc.paper.datacomponent.item.Tool; +import net.kyori.adventure.util.TriState; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; + +@SuppressWarnings("UnstableApiUsage") +public class Sickle extends Item { + + private final Material recipeMaterial; + + public Sickle(String typeKey, Material recipeMaterial) { + this.recipeMaterial = recipeMaterial; + ItemStack itemStack = ItemType.WOODEN_HOE.createItemStack(); + + double damage = switch (typeKey) { + case "stone" -> 0; + case "iron" -> 1.0; + case "diamond" -> 2.0; + default -> -0.5; + }; + + AttributeModifier attackDamage = new AttributeModifier(BASE_ATTACK_DAMAGE, damage, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND); + AttributeModifier attackSpeed = new AttributeModifier(BASE_ATTACK_SPEED, -3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlotGroup.MAINHAND); + + itemStack.setData(DataComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.itemAttributes() + .addModifier(Attribute.ATTACK_DAMAGE, attackDamage) + .addModifier(Attribute.ATTACK_SPEED, attackSpeed) + .build()); + + itemStack.setData(DataComponentTypes.TOOL, Tool.tool() + .defaultMiningSpeed(0.0001f) + .addRule(Tool.rule(getBlockTag(BlockTags.REQUIRES_SICKLE), 1.0f, TriState.TRUE)) + .build()); + + setupDefaults(typeKey + "_sickle", itemStack); + } + + @Override + public Recipe getRecipe() { + ShapedRecipe recipe = new ShapedRecipe(this.recipeKey, this.getItemStack()); + + recipe.shape("oof", " s", " s "); + recipe.setIngredient('o', this.recipeMaterial); + recipe.setIngredient('f', Material.FLINT); + recipe.setIngredient('s', Material.STICK); + return recipe; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/item/items/tools/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/package-info.java new file mode 100644 index 0000000..9ba0ac8 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/items/tools/package-info.java @@ -0,0 +1,4 @@ +/** + * Tool based {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item.items.tools; diff --git a/src/main/java/com/shanebeestudios/survival/api/item/package-info.java b/src/main/java/com/shanebeestudios/survival/api/item/package-info.java new file mode 100644 index 0000000..a93254c --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/item/package-info.java @@ -0,0 +1,4 @@ +/** + * Main package for {@link com.shanebeestudios.survival.api.item.Item Items} + */ +package com.shanebeestudios.survival.api.item; diff --git a/src/main/java/com/shanebeestudios/survival/api/registry/BlockTags.java b/src/main/java/com/shanebeestudios/survival/api/registry/BlockTags.java new file mode 100644 index 0000000..a297803 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/registry/BlockTags.java @@ -0,0 +1,99 @@ +package com.shanebeestudios.survival.api.registry; + +import com.shanebeestudios.survival.api.util.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; + +/** + * Custom block tags + *

These are created in the `block-tags.yml` file

+ */ +@SuppressWarnings("unused") +public class BlockTags { + + private BlockTags() { + } + + private static boolean initialized = false; + + /** + * @hidden + */ + public static void initialize() { + if (initialized) { + throw new IllegalStateException("BlockTags already initialized"); + } + initialized = true; + } + + /** + * Concrete blocks + */ + public static Tag CONCRETE = getTag("concrete"); + /** + * Cooking blocks (furnace, smoker, blast furnace) + */ + public static Tag COOKING_BLOCK = getTag("cooking_block"); + /** + * All glazed terracotta + */ + public static Tag GLAZED_TERRACOTTA = getTag("glazed_terracotta"); + /** + * Ores + */ + public static Tag ORES = getTag("ores"); + /** + * Blocks from ore blocks (such as diamond block, coal block, iron block) + */ + public static Tag ORE_TYPE_BLOCK = getTag("ore_type_block"); + /** + * Blocks that represent stone types + */ + public static Tag STONE_TYPE = getTag("stone_type"); + /** + * Blocks that can hold items + */ + public static Tag STORAGE_BLOCK = getTag("storage_block"); + /** + * Blocks that a player can utilize + */ + public static Tag UTILITY_BLOCK = getTag("utility_block"); + /** + * Blocks that require an axe to break + */ + public static Tag REQUIRES_AXE = getTag("requires_axe"); + /** + * Blocks that require a pickaxe to break + */ + public static Tag REQUIRES_PICKAXE = getTag("requires_pickaxe"); + /** + * Blocks that require a shovel to break + */ + public static Tag REQUIRES_SHOVEL = getTag("requires_shovel"); + /** + * Blocks that require shears to break + */ + public static Tag REQUIRES_SHEARS = getTag("requires_shears"); + /** + * Blocks that requires a sickle to break + */ + public static Tag REQUIRES_SICKLE = getTag("requires_sickle"); + /** + * Blocks that require a hammer to build + */ + public static Tag REQUIRES_HAMMER = getTag("requires_hammer"); + + private static Tag getTag(String key) { + NamespacedKey namespacedKey = NamespacedKey.fromString("survival_plus:" + key); + assert namespacedKey != null; + Tag tag = Bukkit.getTag(Tag.REGISTRY_BLOCKS, namespacedKey, Material.class); + if (tag == null) { + Utils.logMini("Could not find tag for '%s'", namespacedKey.toString()); + return null; + } + return tag; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/registry/DamageTypes.java b/src/main/java/com/shanebeestudios/survival/api/registry/DamageTypes.java new file mode 100644 index 0000000..b3919e6 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/registry/DamageTypes.java @@ -0,0 +1,21 @@ +package com.shanebeestudios.survival.api.registry; + +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import net.kyori.adventure.key.Key; +import org.bukkit.damage.DamageType; + +/** + * Custom {@link DamageType DamageTypes} + */ +@SuppressWarnings("UnstableApiUsage") +public class DamageTypes { + + public static final DamageType ENDER_POWER = get("ender_power"); + + private static DamageType get(String key) { + return RegistryAccess.registryAccess().getRegistry(RegistryKey.DAMAGE_TYPE) + .get(Key.key("survival_plus:" + key)); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/registry/Enchantments.java b/src/main/java/com/shanebeestudios/survival/api/registry/Enchantments.java new file mode 100644 index 0000000..ad51ae1 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/registry/Enchantments.java @@ -0,0 +1,25 @@ +package com.shanebeestudios.survival.api.registry; + +import io.papermc.paper.registry.RegistryAccess; +import io.papermc.paper.registry.RegistryKey; +import net.kyori.adventure.key.Key; +import org.bukkit.enchantments.Enchantment; + +/** + * Custom {@link Enchantment Enchantments} + */ +public class Enchantments { + + public static final Enchantment BLAZING = get("blazing"); + public static final Enchantment ENDER_POWER = get("ender_power"); + public static final Enchantment BUILDING_REACH = get("building_reach"); + public static final Enchantment OBSIDIAN_POWER = get("obsidian_power"); + public static final Enchantment QUARTZ_MINING = get("quartz_mining"); + + @SuppressWarnings("PatternValidation") + private static Enchantment get(String key) { + return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENCHANTMENT) + .get(Key.key("survival_plus:" + key)); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/registry/ItemTags.java b/src/main/java/com/shanebeestudios/survival/api/registry/ItemTags.java new file mode 100644 index 0000000..55a6542 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/registry/ItemTags.java @@ -0,0 +1,42 @@ +package com.shanebeestudios.survival.api.registry; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; +import org.jetbrains.annotations.NotNull; + +/** + * Custom item tags + *

These are created in the `item-tags.yml` file

+ */ +public class ItemTags { + + private ItemTags() { + } + + private static boolean initialized = false; + + /** + * @hidden + */ + public static void initialize() { + if (initialized) { + throw new IllegalStateException("BlockTags already initialized"); + } + initialized = true; + } + + public static final Tag PREVENT_DUAL_WIELD = getTag("prevent_dual_wield"); + + private static @NotNull Tag getTag(String key) { + NamespacedKey namespacedKey = NamespacedKey.fromString("survival_plus:" + key); + assert namespacedKey != null; + Tag tag = Bukkit.getTag(Tag.REGISTRY_ITEMS, namespacedKey, Material.class); + if (tag == null) { + throw new IllegalArgumentException("Could not find tag for " + namespacedKey.toString()); + } + return tag; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/registry/package-info.java b/src/main/java/com/shanebeestudios/survival/api/registry/package-info.java new file mode 100644 index 0000000..e7f6af1 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/registry/package-info.java @@ -0,0 +1,4 @@ +/** + * {@link org.bukkit.Registry} based classes + */ +package com.shanebeestudios.survival.api.registry; diff --git a/src/main/java/tk/shanebee/survival/util/Difficulty.java b/src/main/java/com/shanebeestudios/survival/api/util/Difficulty.java similarity index 98% rename from src/main/java/tk/shanebee/survival/util/Difficulty.java rename to src/main/java/com/shanebeestudios/survival/api/util/Difficulty.java index 878e8b5..ca8ae61 100644 --- a/src/main/java/tk/shanebee/survival/util/Difficulty.java +++ b/src/main/java/com/shanebeestudios/survival/api/util/Difficulty.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.util; +package com.shanebeestudios.survival.api.util; import org.bukkit.Chunk; import org.bukkit.World; diff --git a/src/main/java/com/shanebeestudios/survival/api/util/ItemUtils.java b/src/main/java/com/shanebeestudios/survival/api/util/ItemUtils.java new file mode 100644 index 0000000..39b2dc0 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/util/ItemUtils.java @@ -0,0 +1,103 @@ +package com.shanebeestudios.survival.api.util; + +import com.shanebeestudios.survival.api.item.Item; +import io.papermc.paper.datacomponent.DataComponentTypes; +import net.kyori.adventure.text.Component; +import org.bukkit.Sound; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Map; +import java.util.Random; + +/** + * Utility methods for {@link ItemStack ItemStacks} + */ +@SuppressWarnings("UnstableApiUsage") +public class ItemUtils { + + private static final Random RANDOM = new Random(); + + /** + * Check the durability of an ItemStack + * + * @param item The ItemStack to check + * @return The durability of the ItemStack + */ + public static int getDurability(ItemStack item) { + if (item.hasData(DataComponentTypes.MAX_DAMAGE) && item.hasData(DataComponentTypes.DAMAGE)) { + Integer maxDamage = item.getData(DataComponentTypes.MAX_DAMAGE); + Integer damage = item.getData(DataComponentTypes.DAMAGE); + assert maxDamage != null; + assert damage != null; + return maxDamage - damage; + } + return 0; + } + + /** + * Get the max damage of an ItemStack + * + * @param item Item to get max from + * @return Max damage of item + */ + public static int getMaxDamage(ItemStack item) { + if (item.hasData(DataComponentTypes.MAX_DAMAGE)) { + Integer maxDamage = item.getData(DataComponentTypes.MAX_DAMAGE); + return maxDamage == null ? 0 : maxDamage; + } + return 0; + } + + public static void damageItem(Player player, ItemStack item, int damage) { + player.damageItemStack(item, damage); + if (getDurability(item) <= 0) { + item.setAmount(0); + player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1); + } + } + + @SuppressWarnings({"UnstableApiUsage", "deprecation"}) + public static String getItemName(ItemStack itemStack) { + if (itemStack.hasData(DataComponentTypes.CUSTOM_NAME)) { + Component data = itemStack.getData(DataComponentTypes.CUSTOM_NAME); + if (data != null) return Utils.reverseComponent(data); + } else if (itemStack.hasData(DataComponentTypes.ITEM_NAME)) { + Component data = itemStack.getData(DataComponentTypes.ITEM_NAME); + if (data != null) return Utils.reverseComponent(data); + } + return itemStack.getItemMeta().getDisplayName(); + } + + @SuppressWarnings("UnstableApiUsage") + public static Component getItemNameComponent(ItemStack itemStack) { + if (itemStack.hasData(DataComponentTypes.CUSTOM_NAME)) { + Component data = itemStack.getData(DataComponentTypes.CUSTOM_NAME); + if (data != null) return data; + } else if (itemStack.hasData(DataComponentTypes.ITEM_NAME)) { + Component data = itemStack.getData(DataComponentTypes.ITEM_NAME); + if (data != null) return data; + } + return itemStack.getItemMeta().displayName(); + } + + /** + * Apply the enchantments from an {@link Item} to an existing ItemStack + * + * @param itemStack Current ItemStack to apply enchantments to + * @param item Item to grab data from + */ + public static void applyEnchantments(ItemStack itemStack, Item item) { + ItemStack from = item.getItemStack(); + ItemMeta metaTo = itemStack.getItemMeta(); + ItemMeta metaFrom = from.getItemMeta(); + Map enchants = metaTo.getEnchants(); + for (Enchantment enchantment : enchants.keySet()) { + metaFrom.addEnchant(enchantment, enchants.get(enchantment), true); + } + itemStack.setItemMeta(metaFrom); + } + +} diff --git a/src/main/java/tk/shanebee/survival/util/Math.java b/src/main/java/com/shanebeestudios/survival/api/util/Math.java similarity index 98% rename from src/main/java/tk/shanebee/survival/util/Math.java rename to src/main/java/com/shanebeestudios/survival/api/util/Math.java index 7ac6301..525d8e0 100644 --- a/src/main/java/tk/shanebee/survival/util/Math.java +++ b/src/main/java/com/shanebeestudios/survival/api/util/Math.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.util; +package com.shanebeestudios.survival.api.util; /** * Simple math util methods diff --git a/src/main/java/com/shanebeestudios/survival/api/util/PlayerUtils.java b/src/main/java/com/shanebeestudios/survival/api/util/PlayerUtils.java new file mode 100644 index 0000000..c8214fb --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/util/PlayerUtils.java @@ -0,0 +1,41 @@ +package com.shanebeestudios.survival.api.util; + +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +/** + * Utility methods for {@link Player Players} + */ +public class PlayerUtils { + + /** + * Freeze/Unfreeze a player + *

Prevents them from walking/jumping

+ * + * @param player Player to freeze + * @param freeze Whether to freeze or unfreeze + */ + public static void freezePlayer(@NotNull Player player, boolean freeze) { + AttributeInstance moveAttribute = player.getAttribute(Attribute.MOVEMENT_SPEED); + assert moveAttribute != null; + + if (freeze) { + moveAttribute.setBaseValue(0); + } else { + // Default player value from Minecraft + moveAttribute.setBaseValue(0.10000000149011612D); + } + + AttributeInstance jumpAttribute = player.getAttribute(Attribute.JUMP_STRENGTH); + assert jumpAttribute != null; + + if (freeze) { + jumpAttribute.setBaseValue(0); + } else { + jumpAttribute.setBaseValue(jumpAttribute.getDefaultValue()); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/util/Utils.java b/src/main/java/com/shanebeestudios/survival/api/util/Utils.java new file mode 100644 index 0000000..a8141cb --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/util/Utils.java @@ -0,0 +1,265 @@ +package com.shanebeestudios.survival.api.util; + +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Particle; +import org.bukkit.Statistic; +import org.bukkit.entity.Player; +import org.bukkit.metadata.Metadatable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +/** + * General utility methods for the plugin + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Utils { + + private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage(); + private static final LegacyComponentSerializer COMPONENT_SERIALIZER = LegacyComponentSerializer.legacySection(); + + private static final Pattern HEX_PATTERN = Pattern.compile("<#([A-Fa-f0-9]){6}>"); + + /** + * Get the drops for a certain material + * + * @param material Material that will be broken + * @param grown If the block is grown + * @return List of materials this material will drop + */ + public static List getDrops(Material material, Boolean grown) { + List mat = new ArrayList<>(); + switch (material) { + case PUMPKIN: + mat.add(Material.PUMPKIN); + break; + case MELON_STEM: + mat.add(Material.MELON_SEEDS); + break; + case MELON: + mat.add(Material.MELON_SLICE); + break; + case PUMPKIN_STEM: + mat.add(Material.PUMPKIN_SEEDS); + break; + case CHORUS_FLOWER: + mat.add(Material.CHORUS_FLOWER); + break; + case CARROTS: + mat.add(Material.CARROT); + break; + case POTATOES: + mat.add(Material.POTATO); + break; + case BEETROOTS: + if (grown) { + mat.add(Material.BEETROOT); + } + mat.add(Material.BEETROOT_SEEDS); + break; + case WHEAT: + if (grown) { + mat.add(Material.WHEAT); + } + mat.add(Material.WHEAT_SEEDS); + break; + case SWEET_BERRY_BUSH: + mat.add(Material.SWEET_BERRIES); + break; + case COCOA: + mat.add(Material.COCOA_BEANS); + break; + default: + mat.add(Material.AIR); + } + return mat; + } + + public static Component getMini(String format, Object... args) { + String msg = args != null ? String.format(format, args) : format; + return MINI_MESSAGE.deserialize(msg); + } + + public static void sendColoredMini(@Nullable Audience receiver, @NotNull String format, Object... args) { + if (receiver == null) return; + String f = String.format(format, args); + receiver.sendMessage(MINI_MESSAGE.deserialize(f)); + } + + /** + * Convert a component into a string + * + * @param component Component to convert + * @return String version of component + */ + public static String reverseComponent(Component component) { + return COMPONENT_SERIALIZER.serialize(component); + } + + /** + * Log a prefixed message to console + * + * @param msg Message to log to console + */ + public static void logMini(String msg) { + SurvivalPlugin plugin = SurvivalPlugin.getInstance(); + String prefix = "[SurvivalPlus] "; + if (plugin != null && plugin.getLang() != null) { + prefix = plugin.getLang().prefix; + } + sendColoredMini(Bukkit.getConsoleSender(), prefix + msg); + } + + /** + * Log a prefixed formatted message to console + *

Formatted in the same style as {@link String#format(String, Object...)} + * + * @param format Message format + * @param objects Objects in format + */ + public static void logMini(String format, Object... objects) { + logMini(String.format(format, objects)); + } + + /** + * Spawn a particle at a location for all players + * + * @param location The location to spawn a particle at + * @param particle The particle to spawn + * @param amount The amount of particles + * @param offsetX Offset by x + * @param offsetY Offset by y + * @param offsetZ Offset by z + */ + public static void spawnParticle(Location location, Particle particle, int amount, double offsetX, double offsetY, double offsetZ) { + assert location.getWorld() != null; + location.getWorld().spawnParticle(particle, location, amount, offsetX, offsetY, offsetZ); + } + + /** + * Spawn a particle at a location for a player + * + * @param location The location to spawn a particle at + * @param particle The particle to spawn + * @param amount The amount of particles + * @param offsetX Offset by x + * @param offsetY Offset by y + * @param offsetZ Offset by z + * @param player The player to spawn a particle for + */ + public static void spawnParticle(Location location, Particle particle, int amount, double offsetX, double offsetY, double offsetZ, Player player) { + player.spawnParticle(particle, location, amount, offsetX, offsetY, offsetZ); + } + + /** + * Gets the minutes a player has played on the server + * + * @param player The player to check + * @return The number of minutes they have played on the server + */ + @SuppressWarnings("IntegerDivisionInFloatingPointContext") + public static int getMinutesPlayed(Player player) { + int played = player.getStatistic(Statistic.PLAY_ONE_MINUTE); + return Math.round(played / 1200); + } + + /** + * Check if server is running a minimum Minecraft version + * + * @param major Major version to check (Most likely just going to be 1) + * @param minor Minor version to check + * @return True if running this version or higher + */ + public static boolean isRunningMinecraft(int major, int minor) { + return isRunningMinecraft(major, minor, 0); + } + + /** + * Check if server is running a minimum Minecraft version + * + * @param major Major version to check (Most likely just going to be 1) + * @param minor Minor version to check + * @param revision Revision to check + * @return True if running this version or higher + */ + public static boolean isRunningMinecraft(int major, int minor, int revision) { + String[] version = Bukkit.getServer().getBukkitVersion().split("-")[0].split("\\."); + int maj = Integer.parseInt(version[0]); + int min = Integer.parseInt(version[1]); + int rev; + try { + rev = Integer.parseInt(version[2]); + } catch (Exception ignore) { + rev = 0; + } + return maj > major || min > minor || (min == minor && rev >= revision); + } + + public static boolean isRunningPaper() { + return classExists("io.papermc.paper.ServerBuildInfo"); + } + + /** + * Check if a class exists + * + * @param className The {@link Class#getCanonicalName() canonical name} of the class + * @return True if the class exists + */ + public static boolean classExists(final String className) { + try { + Class.forName(className); + return true; + } catch (ClassNotFoundException ex) { + return false; + } + } + + /** + * Check if a method exists + * + * @param c Class the method belongs to + * @param methodName Name of method + * @param parameterTypes Parameter types for this method + * @return True if the method exists + */ + public static boolean methodExists(final Class c, final String methodName, final Class... parameterTypes) { + try { + c.getDeclaredMethod(methodName, parameterTypes); + return true; + } catch (NoSuchMethodException ex) { + return false; + } + } + + /** + * Check if this entity is a Citizens NPC + * + * @param entity Entity to check + * @return True if entity is an NPC + */ + public static boolean isCitizensNPC(Metadatable entity) { + return entity.hasMetadata("NPC"); + } + + /** + * Get a {@link NamespacedKey} linked to this plugin + * + * @param key Key to create + * @return New NamespacedKey linked to this plugin + */ + public static NamespacedKey getNamespacedKey(String key) { + return new NamespacedKey("survival_plus", key); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/api/util/package-info.java b/src/main/java/com/shanebeestudios/survival/api/util/package-info.java new file mode 100644 index 0000000..4fb37f3 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/api/util/package-info.java @@ -0,0 +1,4 @@ +/** + * General utility classes + */ +package com.shanebeestudios.survival.api.util; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/SurvivalBootstrap.java b/src/main/java/com/shanebeestudios/survival/plugin/SurvivalBootstrap.java new file mode 100644 index 0000000..b1b4699 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/SurvivalBootstrap.java @@ -0,0 +1,16 @@ +package com.shanebeestudios.survival.plugin; + +import com.shanebeestudios.survival.plugin.registry.TagGenerator; +import io.papermc.paper.plugin.bootstrap.BootstrapContext; +import io.papermc.paper.plugin.bootstrap.PluginBootstrap; +import org.jetbrains.annotations.NotNull; + +@SuppressWarnings({"UnstableApiUsage", "unused"}) +public class SurvivalBootstrap implements PluginBootstrap { + + @Override + public void bootstrap(@NotNull BootstrapContext context) { + new TagGenerator(context); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/SurvivalPlugin.java b/src/main/java/com/shanebeestudios/survival/plugin/SurvivalPlugin.java new file mode 100644 index 0000000..cdbb784 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/SurvivalPlugin.java @@ -0,0 +1,367 @@ +package com.shanebeestudios.survival.plugin; + +import com.shanebeestudios.survival.api.registry.ItemTags; +import com.shanebeestudios.survival.plugin.commands.SurvivalCommand; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.config.PlayerDataConfig; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.listeners.EventManager; +import com.shanebeestudios.survival.plugin.managers.EffectManager; +import com.shanebeestudios.survival.plugin.managers.LootManager; +import com.shanebeestudios.survival.plugin.managers.MessageManager; +import com.shanebeestudios.survival.plugin.managers.PapiPlaceholders; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import com.shanebeestudios.survival.plugin.managers.RecipeManager; +import com.shanebeestudios.survival.plugin.managers.ScoreBoardManager; +import com.shanebeestudios.survival.plugin.tasks.TaskManager; +import com.shanebeestudios.survival.api.registry.BlockTags; +import com.shanebeestudios.survival.api.util.Utils; +import dev.jorel.commandapi.CommandAPI; +import dev.jorel.commandapi.CommandAPIBukkitConfig; +import dev.jorel.commandapi.exceptions.UnsupportedVersionException; +import org.bstats.bukkit.Metrics; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * Main plugin class + */ +@SuppressWarnings("UnstableApiUsage") +public class SurvivalPlugin extends JavaPlugin implements Listener { + + static { + ConfigurationSerialization.registerClass(PlayerData.class); + } + + private static SurvivalPlugin INSTANCE; + + // Lists & Map + private Map playerDataMap = new HashMap<>(); + + // Configs + private Config config; + private Lang lang; + private PlayerDataConfig playerDataConfig; + + // Managers + private EffectManager effectManager; + private ScoreBoardManager scoreBoardManager; + private PlayerManager playerManager; + private TaskManager taskManager; + private LootManager lootManager; + private RecipeManager recipeManager; + private MessageManager messageManager; + + // Other + private boolean loaded = true; + + /** + * @hidden + */ + @Override + public void onLoad() { + try { + CommandAPI.onLoad(new CommandAPIBukkitConfig(this) + .setNamespace("survivalplus") + .verboseOutput(false) + .silentLogs(true) + .skipReloadDatapacks(true)); + } catch (UnsupportedVersionException ignore) { + Utils.logMini("CommandAPI does not support this version of Minecraft, will update soon."); + } + } + + /** + * @hidden + */ + public void onEnable() { + INSTANCE = this; + long time = System.currentTimeMillis(); + + // VERSION CHECK + if (!Utils.isRunningMinecraft(1, 21, 4)) { + Utils.logMini("-----------------------------------------------------------"); + Utils.logMini("Your version is not supported: " + Bukkit.getMinecraftVersion()); + Utils.logMini("This plugin only works on Minecraft 1.16+"); + Utils.logMini("-----------------------------------------------------------"); + loaded = false; + Bukkit.getPluginManager().disablePlugin(this); + return; + } + + // PAPER CHECK + // This shouldn't really happen since we're using paper-plugin.yml + if (!Utils.isRunningPaper()) { + Utils.logMini("-----------------------------------------------------------"); + Utils.logMini("Your server software is not supported: " + Bukkit.getName()); + Utils.logMini("This plugin will only work on Paper."); + Utils.logMini("-----------------------------------------------------------"); + loaded = false; + Bukkit.getPluginManager().disablePlugin(this); + return; + } + + // LOAD CONFIG FILES + loadSettings(Bukkit.getConsoleSender()); + + // LOAD RESOURCE PACK + if (this.config.settings_resource_pack_enabled) { + if (this.config.settings_resource_pack_url.isEmpty()) { + Utils.logMini("Resource Pack is not set! Plugin disabling"); + Bukkit.getPluginManager().disablePlugin(this); + return; + } else { + Utils.logMini("Resource pack enabled"); + } + } else { + Utils.logMini("Resource Pack disabled"); + } + + // LOAD TAGS + BlockTags.initialize(); + ItemTags.initialize(); + + // LOAD MANAGERS + this.playerManager = new PlayerManager(this, this.playerDataMap); + this.effectManager = new EffectManager(this); + this.taskManager = new TaskManager(this); + this.scoreBoardManager = new ScoreBoardManager(this); + this.lootManager = new LootManager(this); + this.recipeManager = new RecipeManager(this); + this.messageManager = new MessageManager(this); + + // LOAD PLAYER DATA - (during a reload if players are still online) + playerDataLoader(true); + this.scoreBoardManager.resetStatusScoreboard(config.mechanics_status_scoreboard); + + // LOAD PLACEHOLDERS + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + new PapiPlaceholders(this).register(); + Utils.logMini("PlaceholderAPI placeholders enabled"); + } + + // REGISTER EVENTS & COMMANDS + registerCommands(); + EventManager eventManager = new EventManager(this); + eventManager.registerEvents(); + + // LOAD CUSTOM RECIPES + // This is a helper for other plugins that wipe custom recipes - secret hidden config + if (this.config.recipe_delay > 0) { + Utils.logMini("Custom recipe loading delayed... will load in " + this.config.recipe_delay + " second[s]"); + Bukkit.getScheduler().runTaskLater(this, () -> { + this.recipeManager.loadCustomRecipes(); + Utils.logMini("Custom recipes loaded"); + }, this.config.recipe_delay * 20L); + + } else { + this.recipeManager.loadCustomRecipes(); + Utils.logMini("Custom recipes loaded"); + } + + // LOAD METRICS + new Metrics(this, 24831); + + Utils.logMini("Successfully loaded in " + (System.currentTimeMillis() - time) + " milliseconds"); + + // BETA WARNING + if (this.getPluginMeta().getVersion().contains("Beta")) { + Utils.logMini("YOU ARE RUNNING A BETA VERSION, PLEASE USE WITH CAUTION!"); + } + } + + /** + * @hidden + */ + public void onDisable() { + if (!loaded) return; + Utils.logMini("Shutting down"); + getServer().getScheduler().cancelTasks(this); + + // Unload player data (decrease chance of memory leak) + playerDataLoader(false); + + //Avoid WorkbenchShare glitch + if (this.config.mechanics_shared_workbench) { + for (Player p : Bukkit.getOnlinePlayers()) { + if (p.hasMetadata("shared_workbench")) { + Block workbench = (p.getMetadata("shared_workbench").getFirst().value() instanceof Block) ? (Block) + p.getMetadata("shared_workbench").getFirst().value() : null; + + if (workbench != null && workbench.getType() == Material.CRAFTING_TABLE) { + if (workbench.hasMetadata("shared_players")) + workbench.removeMetadata("shared_players", SurvivalPlugin.INSTANCE); + else + p.getOpenInventory().getTopInventory().clear(); + p.closeInventory(); + } + p.removeMetadata("shared_workbench", SurvivalPlugin.INSTANCE); + } + } + } + INSTANCE = null; + Utils.logMini("Successfully disabled"); + } + + private void playerDataLoader(boolean load) { + int size = Bukkit.getOnlinePlayers().size(); + if (load) { + // Load player data - if players are online (useful during reload) + for (Player player : Bukkit.getOnlinePlayers()) { + if (this.playerDataConfig.hasPlayerDataFile(player)) { + this.playerManager.loadPlayerData(player); + } else { + this.playerManager.createNewPlayerData(player); + } + } + if (size > 0) { + Utils.logMini("Loading player data for " + size + " player" + (size != 1 ? "s" : "")); + } + } else { + // Unload player data - if players are still online + for (Player player : Bukkit.getOnlinePlayers()) { + playerManager.unloadPlayerData(player); + } + // Clear/delete player data map to prevent memory leaks + this.playerDataMap.clear(); + this.playerDataMap = null; + Utils.logMini("Unloading player data for " + size + " player" + (size != 1 ? "s" : "")); + } + } + + /** + * Load config settings + * + * @param sender The person/console loading config + */ + public void loadSettings(CommandSender sender) { + if (this.config == null) { + this.config = new Config(this); + } + this.config.loadDefaultSettings(); + if (this.lang == null) { + this.lang = new Lang(this, this.config.lang); + } + this.lang.loadLangFile(sender); + this.playerDataConfig = new PlayerDataConfig(this); + } + + private void registerCommands() { + if (CommandAPI.isLoaded()) { + CommandAPI.onEnable(); + new SurvivalCommand(this, "survival"); + } + } + + /** + * Get instance of this plugin + * + * @return Instance of this plugin + */ + public static SurvivalPlugin getInstance() { + return INSTANCE; + } + + /** + * Get the effect manager + * + * @return Instance of the effect manager + */ + public EffectManager getEffectManager() { + return this.effectManager; + } + + /** + * Get the scoreboard manager + * + * @return Instance of the scoreboard manager + */ + public ScoreBoardManager getScoreboardManager() { + return this.scoreBoardManager; + } + + /** + * Get the player manager + * + * @return Instance of the player manager + */ + public PlayerManager getPlayerManager() { + return this.playerManager; + } + + /** + * Get the task manager + * + * @return Instance of the task manager + */ + @SuppressWarnings("unused") + public TaskManager getTaskManager() { + return this.taskManager; + } + + /** + * Get an instance of the loot manager + * + * @return Instance of the loot manager + */ + public LootManager getLootManager() { + return lootManager; + } + + /** + * Get an instance of the recipe manager + * + * @return Instance of recipe manager + */ + public RecipeManager getRecipeManager() { + return recipeManager; + } + + /** + * Get an instance of the message manager + * + * @return Instance of message manager + */ + public MessageManager getMessageManager() { + return this.messageManager; + } + + /** + * Get the main SurvivalPlus config + * + * @return SurvivalPlus config + */ + public Config getSurvivalConfig() { + return this.config; + } + + /** + * Get an instance of the language config + * + * @return Language config + */ + public Lang getLang() { + return lang; + } + + /** + * Get an instance of the player data config + * + * @return Player data config + */ + public PlayerDataConfig getPlayerDataConfig() { + return playerDataConfig; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/BaseCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/BaseCommand.java new file mode 100644 index 0000000..ff4db5a --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/BaseCommand.java @@ -0,0 +1,25 @@ +package com.shanebeestudios.survival.plugin.commands; + +import dev.jorel.commandapi.arguments.Argument; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; + +public abstract class BaseCommand { + + protected final SurvivalPlugin plugin; + protected final Config config; + protected final Lang lang; + protected final PlayerManager playerManager; + + public BaseCommand(SurvivalPlugin plugin) { + this.plugin = plugin; + this.config = plugin.getSurvivalConfig(); + this.lang = plugin.getLang(); + this.playerManager = plugin.getPlayerManager(); + } + + abstract Argument register(); + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/DataGenCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/DataGenCommand.java new file mode 100644 index 0000000..6732662 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/DataGenCommand.java @@ -0,0 +1,29 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.LiteralArgument; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.generator.TagFileGenerator; +import com.shanebeestudios.survival.api.util.Utils; + +public class DataGenCommand extends BaseCommand { + + private final TagFileGenerator tagFileGenerator; + + public DataGenCommand(SurvivalPlugin plugin) { + super(plugin); + this.tagFileGenerator = new TagFileGenerator(plugin); + } + + @Override + Argument register() { + return LiteralArgument.literal("datagen") + .withPermission(Permissions.COMMAND_DATA_GEN.permission()) + .executes(info -> { + this.tagFileGenerator.generate(); + Utils.sendColoredMini(info.sender(), "Finished generating block-tags.yml"); + }); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/DebugCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/DebugCommand.java new file mode 100644 index 0000000..cca134a --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/DebugCommand.java @@ -0,0 +1,43 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.Permissions; +import com.shanebeestudios.survival.api.data.Placeholders; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.item.Nutrition; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.LiteralArgument; + +public class DebugCommand extends BaseCommand{ + public DebugCommand(SurvivalPlugin plugin) { + super(plugin); + } + + @Override + Argument register() { + return LiteralArgument.literal("debug") + .withPermission(Permissions.COMMAND_DEBUG.permission()) + .then(LiteralArgument.literal("nutrition") + .executesConsole(info -> { + Nutrition.debug(); + })) + .then(LiteralArgument.literal("items") + .then(LiteralArgument.literal("create") + .executesPlayer(info -> { + Items.debug(info.sender()); + })) + .then(LiteralArgument.literal("remove") + .executesPlayer(info -> { + Items.debug(null); + }))) + .then(LiteralArgument.literal("placeholders") + .executesConsole(info -> { + Placeholders.debug(); + })) + .then(LiteralArgument.literal("permissions") + .executesConsole(info -> { + Permissions.debug(); + })); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/GiveItemCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/GiveItemCommand.java new file mode 100644 index 0000000..f00aa0d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/GiveItemCommand.java @@ -0,0 +1,106 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.ArgumentSuggestions; +import dev.jorel.commandapi.arguments.EntitySelectorArgument; +import dev.jorel.commandapi.arguments.IntegerArgument; +import dev.jorel.commandapi.arguments.LiteralArgument; +import dev.jorel.commandapi.arguments.StringArgument; +import dev.jorel.commandapi.executors.CommandArguments; +import io.papermc.paper.datacomponent.DataComponentTypes; +import net.kyori.adventure.text.Component; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.StringJoiner; + +public class GiveItemCommand extends BaseCommand { + + private final List names = new ArrayList<>(); + + public GiveItemCommand(SurvivalPlugin plugin) { + super(plugin); + Items.allItemKeys().forEach(key -> this.names.add(key.value())); + } + + @SuppressWarnings("unchecked") + @Override + Argument register() { + return LiteralArgument.literal("giveitem") + .withPermission(Permissions.COMMAND_GIVEITEM.permission()) + .then(new EntitySelectorArgument.ManyPlayers("players") + .then(new StringArgument("item") + .includeSuggestions(ArgumentSuggestions.strings(this.names)) + .then(new IntegerArgument("amount", 1, 99) + .setOptional(true) + .executes(info -> { + CommandSender sender = info.sender(); + CommandArguments args = info.args(); + Collection players = (Collection) args.get("players"); + String itemKey = args.getByClass("item", String.class); + int amount = args.getByClassOrDefault("amount", Integer.class, 1); + + assert itemKey != null; + assert players != null; + + Item item = Items.getByKey(itemKey); + + if (item != null) { + ItemStack itemStack = item.getItemStack(amount); + + StringJoiner joiner = new StringJoiner(", "); + players.forEach(player -> { + giveItem(player, itemStack); + joiner.add(player.getName()); + }); + String itemName = getItemName(itemStack); + if (itemName == null) itemName = item.getKey().toString(); + + sendMessage(sender, itemStack, itemName, amount, joiner.toString()); + } else { + Utils.sendColoredMini(sender, this.lang.prefix + "Invalid item %s", itemKey); + } + })))); + } + + private void giveItem(Player player, ItemStack item) { + HashMap returnMap = player.getInventory().addItem(item); + if (!returnMap.isEmpty()) { + World world = player.getWorld(); + Location location = player.getLocation(); + returnMap.values().forEach(itemStack -> world.dropItemNaturally(location, itemStack)); + } + } + + @SuppressWarnings("UnstableApiUsage") + private @Nullable String getItemName(ItemStack itemStack) { + if (itemStack.hasData(DataComponentTypes.CUSTOM_NAME)) { + return Utils.reverseComponent(itemStack.getData(DataComponentTypes.CUSTOM_NAME)); + } else if (itemStack.hasData(DataComponentTypes.ITEM_NAME)) { + return Utils.reverseComponent(itemStack.getData(DataComponentTypes.ITEM_NAME)); + } + return null; + } + + private void sendMessage(CommandSender sender, ItemStack itemStack, String itemName, int amount, String players) { + String who = sender instanceof Player ? "You" : "CONSOLE"; + Component message = Utils.getMini(this.lang.prefix + "%s gave %s of ", who, amount) + .append(Utils.getMini("[%s]", itemName).hoverEvent(itemStack.asHoverEvent())) + .append(Utils.getMini(" to %s", players)); + sender.sendMessage(message); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/HealCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/HealCommand.java new file mode 100644 index 0000000..b3d53ff --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/HealCommand.java @@ -0,0 +1,71 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.EntitySelectorArgument; +import dev.jorel.commandapi.arguments.LiteralArgument; +import org.bukkit.attribute.Attribute; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.Collection; +import java.util.StringJoiner; + +public class HealCommand extends BaseCommand { + + public HealCommand(SurvivalPlugin plugin) { + super(plugin); + } + + @SuppressWarnings("unchecked") + @Override + Argument register() { + return LiteralArgument.literal("heal") + .withPermission(Permissions.COMMAND_HEAL.permission()) + .executesPlayer(info -> { + heal(info.sender()); + Utils.sendColoredMini(info.sender(), this.lang.cmd_heal_self); + }) + .then(new EntitySelectorArgument.ManyPlayers("players") + .withPermission(Permissions.COMMAND_HEAL_OTHERS.permission()) + .executes(info -> { + CommandSender sender = info.sender(); + Collection players = (Collection) info.args().get("players"); + assert players != null; + + StringJoiner joiner = new StringJoiner(", "); + players.forEach(player -> { + joiner.add(player.getName()); + heal(player); + Utils.sendColoredMini(player, lang.cmd_heal_by, sender.getName()); + }); + Utils.sendColoredMini(sender, this.lang.cmd_heal_other, joiner.toString()); + })); + } + + @SuppressWarnings("DataFlowIssue") + private void heal(Player player) { + PlayerData playerData = this.plugin.getPlayerManager().getPlayerData(player); + + player.setHealth(player.getAttribute(Attribute.MAX_HEALTH).getValue()); + playerData.setHunger(this.config.mechanics_hunger_respawn_amount); + + if (this.config.mechanics_thirst_enabled) { + playerData.setThirst(this.config.mechanics_thirst_respawn_amount); + } + if (this.config.mechanics_food_diversity_enabled) { + int carbs = this.config.mechanics_food_respawn_carbs; + int proteins = this.config.mechanics_food_respawn_proteins; + int salts = this.config.mechanics_food_respawn_vitamins; + playerData.setNutrients(carbs, proteins, salts); + } + if (this.config.mechanics_energy_enabled) { + playerData.setEnergy(this.config.mechanics_energy_respawn); + } + player.clearActivePotionEffects(); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/NutritionCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/NutritionCommand.java new file mode 100644 index 0000000..0ce7fcf --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/NutritionCommand.java @@ -0,0 +1,27 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.LiteralArgument; +import org.bukkit.entity.Player; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.gui.NutritionGUI; + +public class NutritionCommand extends BaseCommand { + + public NutritionCommand(SurvivalPlugin plugin) { + super(plugin); + } + + @Override + Argument register() { + return LiteralArgument.literal("nutrition") + .withPermission(Permissions.COMMAND_NUTRITION.permission()) + .executesPlayer(info -> { + Player player = info.sender(); + NutritionGUI gui = new NutritionGUI(this.plugin); + gui.openInventory(player, 0); + }); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/PlayerDataCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/PlayerDataCommand.java new file mode 100644 index 0000000..2315a27 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/PlayerDataCommand.java @@ -0,0 +1,78 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.DoubleArgument; +import dev.jorel.commandapi.arguments.EntitySelectorArgument; +import dev.jorel.commandapi.arguments.LiteralArgument; +import dev.jorel.commandapi.arguments.MultiLiteralArgument; +import org.bukkit.entity.Player; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.Collection; + +public class PlayerDataCommand extends BaseCommand { + + public PlayerDataCommand(SurvivalPlugin plugin) { + super(plugin); + } + + @SuppressWarnings("unchecked") + @Override + Argument register() { + return LiteralArgument.literal("playerdata") + .withPermission(Permissions.COMMAND_PLAYERDATA.permission()) + .then(new EntitySelectorArgument.ManyPlayers("players") + .then(new MultiLiteralArgument("type", PlayerData.DataType.getNames()) + .then(LiteralArgument.literal("get") + .executes(info -> { + Collection players = (Collection) info.args().get("players"); + String type = info.args().getByClass("type", String.class); + PlayerData.DataType dataType = PlayerData.DataType.getByName(type); + if (dataType == null) { + return; + } + assert players != null; + players.forEach(player -> { + PlayerData playerData = this.playerManager.getPlayerData(player); + if (playerData == null) { + Utils.sendColoredMini(info.sender(), "Invalid player data for " + player.getName()); + return; + } + + double data = playerData.getData(dataType); + Utils.sendColoredMini(info.sender(), "Data: %s = %.2f", type, data); + }); + + })) + .then(new MultiLiteralArgument("change", "add", "remove", "set") + .then(new DoubleArgument("amount") + .executes(info -> { + Collection players = (Collection) info.args().get("players"); + String type = info.args().getByClass("type", String.class); + String change = info.args().getByClass("change", String.class); + Double value = info.args().getByClass("amount", Double.class); + PlayerData.DataType dataType = PlayerData.DataType.getByName(type); + + if (dataType == null || players == null || change == null || value == null) return; + + players.forEach(player -> { + double changeValue = value; + PlayerData playerData = this.playerManager.getPlayerData(player); + if (playerData == null) { + Utils.sendColoredMini(info.sender(), "Invalid player data for " + player.getName()); + return; + } + changeValue = switch (change) { + case "add" -> value + playerData.getData(dataType); + case "remove" -> playerData.getData(dataType) - value; + default -> changeValue; + }; + playerData.setData(dataType, changeValue); + }); + }))))); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/ReloadCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/ReloadCommand.java new file mode 100644 index 0000000..fdc195d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/ReloadCommand.java @@ -0,0 +1,25 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.LiteralArgument; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.util.Utils; + +public class ReloadCommand extends BaseCommand { + + public ReloadCommand(SurvivalPlugin plugin) { + super(plugin); + } + + @Override + Argument register() { + return LiteralArgument.literal("reload") + .withPermission(Permissions.COMMAND_RELOAD.permission()) + .executes(info -> { + this.plugin.loadSettings(info.sender()); + Utils.sendColoredMini(info.sender(), this.lang.prefix + "Reload complete"); + }); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/StatCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/StatCommand.java new file mode 100644 index 0000000..50e88d9 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/StatCommand.java @@ -0,0 +1,148 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.BukkitStringTooltip; +import dev.jorel.commandapi.IStringTooltip; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.ArgumentSuggestions; +import dev.jorel.commandapi.arguments.LiteralArgument; +import dev.jorel.commandapi.arguments.StringArgument; +import dev.jorel.commandapi.executors.CommandArguments; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.Info; +import com.shanebeestudios.survival.api.data.Nutrient; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +public class StatCommand extends BaseCommand { + + private final List infoTooltips = new ArrayList<>(); + private final List typeTooltips = new ArrayList<>(); + + public StatCommand(SurvivalPlugin plugin) { + super(plugin); + + setupInfos("all", "Manage all stats"); + setupInfos("hunger", "Manage hunger stat"); + if (this.config.mechanics_thirst_enabled) { + setupInfos("thirst", "Manage thirst stat"); + } + if (this.config.mechanics_energy_enabled) { + setupInfos("energy", "Manage energy stat"); + } + if (this.config.mechanics_food_diversity_enabled) { + setupInfos("nutrients", "Manage nutrient stat"); + } + + if (this.config.mechanics_status_scoreboard) { + setupTypes("toggle", "Toggle a stat"); + setupTypes("on", "Turn a stat on"); + setupTypes("off", "Turn a stat off"); + } + setupTypes("show", "Show a stat in chat"); + } + + @Override + Argument register() { + return LiteralArgument.literal("stats") + .withPermission(Permissions.COMMAND_STATS.permission()) + .then(new StringArgument("info") + .includeSuggestions(ArgumentSuggestions.stringsWithTooltips(this.infoTooltips)) + .then(new StringArgument("type") + .includeSuggestions(ArgumentSuggestions.stringsWithTooltips(this.typeTooltips)) + .executesPlayer(commandInfo -> { + CommandArguments args = commandInfo.args(); + Player player = commandInfo.sender(); + + String infoName = args.getByClassOrDefault("info", String.class, "all"); + String type = args.getByClassOrDefault("type", String.class, "show"); + + Info info = getStat(infoName); + + if (type.equalsIgnoreCase("show")) { + showStat(player, info); + } else { + manageStat(player, info, type); + } + }))) + ; + } + + private void showStat(@NotNull Player player, @Nullable Info info) { + if (info == null) { + for (Info value : Info.values()) { + showStat(player, value); + } + return; + } + + PlayerData playerData = this.playerManager.getPlayerData(player); + String message = switch (info) { + case HUNGER -> String.format("%s: %.2f", this.lang.hunger, playerData.getHunger()); + case THIRST -> String.format("%s: %.2f", this.lang.thirst, playerData.getThirst()); + case ENERGY -> String.format("%s: %.2f", this.lang.energy, playerData.getEnergy()); + case NUTRIENTS -> String.format("%s: " + + "<#A0E853>%s = %s, " + + "<#CE784D>%s = %s, " + + "<#53DDE8>%s = %s", + this.lang.nutrients, + this.lang.carbohydrates, + playerData.getNutrient(Nutrient.CARBS), + this.lang.protein, + playerData.getNutrient(Nutrient.PROTEIN), + this.lang.vitamins, + playerData.getNutrient(Nutrient.VITAMINS)); + + //nutrients.add("<#A0E853>" + this.lang.carbohydrates); + // nutrients.add("<#CE784D>" + this.lang.protein); + // nutrients.add("<#53DDE8>" + this.lang.vitamins); + }; + + Utils.sendColoredMini(player, message); + } + + private void manageStat(@NotNull Player player, @Nullable Info info, @NotNull String type) { + if (!this.config.mechanics_status_scoreboard) return; + PlayerData playerData = this.playerManager.getPlayerData(player); + + if (info == null) { + for (Info value : Info.values()) { + switch (type) { + case "toggle" -> playerData.setInfoDisplayed(value, !playerData.isInfoDisplayed(value)); + case "on" -> playerData.setInfoDisplayed(value, true); + case "off" -> playerData.setInfoDisplayed(value, false); + } + } + } else { + switch (type) { + case "toggle" -> playerData.setInfoDisplayed(info, !playerData.isInfoDisplayed(info)); + case "on" -> playerData.setInfoDisplayed(info, true); + case "off" -> playerData.setInfoDisplayed(info, false); + } + } + } + + private Info getStat(String stat) { + try { + return Info.valueOf(stat.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return null; + } + } + + private void setupInfos(String stat, String tooltip) { + this.infoTooltips.add(BukkitStringTooltip.ofString(stat, tooltip)); + } + + private void setupTypes(String type, String tooltip) { + this.typeTooltips.add(BukkitStringTooltip.ofString(type, tooltip)); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/SurvivalCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/SurvivalCommand.java new file mode 100644 index 0000000..0af3f08 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/SurvivalCommand.java @@ -0,0 +1,41 @@ +package com.shanebeestudios.survival.plugin.commands; + +import dev.jorel.commandapi.CommandTree; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; + +import java.util.ArrayList; +import java.util.List; + +public class SurvivalCommand { + + public SurvivalCommand(SurvivalPlugin plugin, String commandName) { + List arguments = new ArrayList<>(); + + arguments.add(new GiveItemCommand(plugin)); + arguments.add(new HealCommand(plugin)); + arguments.add(new NutritionCommand(plugin)); + arguments.add(new PlayerDataCommand(plugin)); + arguments.add(new ReloadCommand(plugin)); + arguments.add(new StatCommand(plugin)); + + if (plugin.getSurvivalConfig().settings_local_chat_distance >= 0) { + arguments.add(new ToggleChatCommand(plugin)); + } + + // TODO comment out + arguments.add(new DataGenCommand(plugin)); + arguments.add(new DebugCommand(plugin)); + + register(commandName, arguments); + } + + private void register(String commandName, List arguments) { + CommandTree command = new CommandTree(commandName); + for (BaseCommand argument : arguments) { + command.then(argument.register()); + } + + command.register(); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/commands/ToggleChatCommand.java b/src/main/java/com/shanebeestudios/survival/plugin/commands/ToggleChatCommand.java new file mode 100644 index 0000000..0abea12 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/commands/ToggleChatCommand.java @@ -0,0 +1,53 @@ +package com.shanebeestudios.survival.plugin.commands; + +import com.shanebeestudios.survival.api.data.Permissions; +import dev.jorel.commandapi.BukkitStringTooltip; +import dev.jorel.commandapi.IStringTooltip; +import dev.jorel.commandapi.arguments.Argument; +import dev.jorel.commandapi.arguments.ArgumentSuggestions; +import dev.jorel.commandapi.arguments.LiteralArgument; +import dev.jorel.commandapi.arguments.StringArgument; +import org.bukkit.entity.Player; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.ArrayList; +import java.util.List; + +public class ToggleChatCommand extends BaseCommand { + + private final List typeTooltips = new ArrayList<>(); + + public ToggleChatCommand(SurvivalPlugin plugin) { + super(plugin); + setupInfos("global", "Set chat to global chat"); + setupInfos("local", "Set chat to local chat"); + } + + @Override + Argument register() { + return LiteralArgument.literal("chat") + .withPermission(Permissions.COMMAND_CHAT.permission()) + //.then(new StringArgument("type") + .then(new StringArgument("type") + .replaceSuggestions(ArgumentSuggestions.stringsWithTooltips(this.typeTooltips)) + .executesPlayer(info -> { + Player player = info.sender(); + String type = info.args().getByClassOrDefault("type", String.class, "global"); + PlayerData playerData = this.playerManager.getPlayerData(player); + if (type.equalsIgnoreCase("global")) { + Utils.sendColoredMini(player, lang.toggle_chat_global); + playerData.setLocalChat(false); + } else if (type.equalsIgnoreCase("local")) { + Utils.sendColoredMini(player, lang.toggle_chat_local); + playerData.setLocalChat(true); + } + })); + } + + private void setupInfos(String stat, String tooltip) { + this.typeTooltips.add(BukkitStringTooltip.ofString(stat, tooltip)); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/config/Config.java b/src/main/java/com/shanebeestudios/survival/plugin/config/Config.java new file mode 100644 index 0000000..6fe7531 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/config/Config.java @@ -0,0 +1,563 @@ +package com.shanebeestudios.survival.plugin.config; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.goals.AngryWolfGoal; +import com.shanebeestudios.survival.api.util.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.Tag; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Mob; + +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +public class Config { + + private final SurvivalPlugin plugin; + private FileConfiguration settings; + private File configFile; + + public String lang; + + public String settings_resource_pack_url; + public boolean settings_resource_pack_enabled; + + public int settings_local_chat_distance; + + public boolean welcome_guide_enabled; + public boolean welcome_guide_new_players; + public int welcome_guide_delay; + + // SURVIVAL + public boolean survival_enabled; + public boolean survival_unlock_all_recipes; + public boolean survival_remove_wood_tools; + public boolean survival_torch; + public boolean survival_update_merchant_trades; + public boolean survival_update_loot_tables; + + public boolean survival_break_only_with_sickle; + public boolean survival_break_only_with_shovel; + public boolean survival_break_only_with_axe; + public boolean survival_break_only_with_pickaxe; + public boolean survival_break_only_with_shears; + public boolean survival_place_only_with_hammer; + + public boolean survival_sickle_flint; + public boolean survival_sickle_stone; + public boolean survival_sickle_iron; + public boolean survival_sickle_diamond; + + public double survival_drop_rate_stick; + public double survival_drop_rate_flint; + + // MECHANICS + public boolean mechanics_shared_workbench; + + // ENERGY + public boolean mechanics_energy_enabled; + public double mechanics_energy_start; + public double mechanics_energy_respawn; + public int mechanics_energy_immunity_minutes; + public boolean mechanics_energy_warning; + public double mechanics_energy_drain_rate; + public double mechanics_energy_drain_cold_rate; + public double mechanics_energy_refresh_rate_bed; + public double mechanics_energy_refresh_rate_chair; + public double mechanics_energy_exhaustion; + public boolean mechanics_energy_coffee_enabled; + public boolean mechanics_energy_absorption; + public boolean mechanics_energy_haste; + + public boolean mechanics_slow_armor; + public boolean mechanics_reinforced_armor; + public boolean mechanics_bow; + public boolean mechanics_recurved_bow; + public boolean mechanics_grappling_hook; + public boolean mechanics_medic_kit; + public boolean mechanics_reduced_iron_nugget; + public boolean mechanics_reduced_gold_nugget; + + public boolean mechanics_status_scoreboard; + public int MECHANICS_ALERT_INTERVAL; + + public boolean mechanics_raw_meat_hunger; + public boolean mechanics_empty_potion; + public boolean mechanics_poison_potato; + public boolean mechanics_cookie_boost; + public boolean mechanics_beet_strength; + + public boolean mechanics_food_diversity_enabled; + public int mechanics_food_max_level; + public int mechanics_food_start_carbs; + public int mechanics_food_start_protein; + public int mechanics_food_start_vitamins; + public int mechanics_food_immunity_minutes; + public int mechanics_food_respawn_proteins; + public int mechanics_food_respawn_vitamins; + public int mechanics_food_respawn_carbs; + public int mechanics_food_effects_carbs_ex_amp_easy; + public int mechanics_food_effects_carbs_ex_amp_medium; + public int mechanics_food_effects_carbs_ex_amp_hard; + public int mechanics_food_effects_vitamins_ex_amp; + public String mechanics_food_effects_vitamins_se_normal_effect; + public int mechanics_food_effects_vitamins_se_normal_amp; + public int mechanics_food_effects_vitamins_se_normal_duration; + public String mechanics_food_effects_vitamins_se_hard_effect; + public int mechanics_food_effects_vitamins_se_hard_amp; + public int mechanics_food_effects_vitamins_se_hard_duration; + public int mechanics_food_effects_protein_ex_amp; + public String mechanics_food_effects_protein_se_normal_effect; + public int mechanics_food_effects_protein_se_normal_amp; + public int mechanics_food_effects_protein_se_normal_duration; + public String mechanics_food_effects_protein_se_hard_effect; + public int mechanics_food_effects_protein_se_hard_amp; + public int mechanics_food_effects_protein_se_hard_duration; + + // THIRST + public boolean mechanics_thirst_enabled; + public double mechanics_thirst_starting_amount; + public double mechanics_thirst_respawn_amount; + public int mechanics_thirst_immunity_minutes; + public boolean mechanics_thirst_purify_water; + public boolean mechanics_thirst_melt_snow; + public double mechanics_thirst_drain_rate; + public double mechanics_thirst_heat_drain_rate; + public double mechanics_thirst_nether_drain_rate; + public double mechanics_thirst_damage_rate; + public double mechanics_thirst_rep_apple; + public double mechanics_thirst_rep_beetroot_soup; + public double mechanics_thirst_rep_melon_slice; + public double mechanics_thirst_rep_mush_stew; + public double mechanics_thirst_rep_milk_bucket; + public double mechanics_thirst_rep_water; + public double mechanics_thirst_rep_honey_bottle; + public double mechanics_thirst_rep_other_water; + + public int mechanics_hunger_start_amount; + public int mechanics_hunger_respawn_amount; + + public boolean mechanics_compass_waypoint; + public boolean mechanics_compass_waypoint_worlds; + public boolean mechanics_tropical_fish; + public boolean mechanics_fermented_skin; + public boolean mechanics_living_slime; + public boolean mechanics_snowball_revamp; + + public boolean mechanics_farming_products_cookie; + public boolean mechanics_farming_products_bread; + + public boolean mechanics_chairs_enabled; + public int mechanics_chairs_max_width; + public List mechanics_chairs_blocks; + + public boolean mechanics_weather_enabled; + public double mechanics_weather_speed_base; + public double mechanics_weather_speed_rain; + public double mechanics_weather_speed_storm; + public double mechanics_weather_speed_snow; + public double mechanics_weather_speed_snowstorm; + + // ITEM MECHANICS + public int item_mechanics_firestriker_cook_time; + + // ENTITY MECHANICS + public boolean entity_mechanics_pigmen_chest_enabled; + public int entity_mechanics_pigmen_chest_radius; + public double entity_mechanics_pigmen_chest_speed; + public boolean entity_mechanics_beekeeper_suit_enabled; + public boolean entity_mechanics_suspicious_meat_enabled; + public int entity_mechanics_suspicious_meat_chance; + public boolean entity_mechanics_chicken_breeding_enabled; + public int entity_mechanics_chicken_breeding_max_eggs; + public boolean entity_mechanics_chicken_breeding_always_baby; + public int entity_mechanics_chicken_breeding_baby_ticks; + public boolean entity_mechanics_piglin_drop_water; + public boolean entity_mechanics_piglin_alt_drop; + public List entity_mechanics_mobs_avoid_players; + public AngryWolfGoal.Type entity_mechanics_angry_wolves; + + // RECIPES + public boolean recipes_saddle; + public boolean recipes_name_tag; + public boolean recipes_packed_ice; + public boolean recipes_leather_bard; + public boolean recipes_iron_bard; + public boolean recipes_gold_bard; + public boolean recipes_diamond_bard; + public boolean recipes_clay_brick; + public boolean recipes_quartz_block; + public boolean recipes_wool_string; + public boolean recipes_web_string; + public boolean recipes_ice; + public boolean recipes_clay; + public boolean recipes_diorite; + public boolean recipes_granite; + public boolean recipes_andesite; + public boolean recipes_gravel; + public boolean recipes_slimeball; + public boolean recipes_cobweb; + public boolean recipes_sapling_stick; + public boolean recipes_fishing_rod; + public boolean recipes_furnace; + public boolean recipes_workbench; + + // LEGENDARY TOOLS + public boolean legendary_valkyrie; + public boolean legendary_quartz_pickaxe; + public boolean legendary_obsidian_mace; + public boolean legendary_giant_blade; + public boolean legendary_blaze_sword; + public boolean legendary_notch_apple; + public boolean legendary_gold_armor_buff; + + // HIDDEN CONFIG + public int recipe_delay; + + public Config(SurvivalPlugin plugin) { + this.plugin = plugin; + } + + public void loadDefaultSettings() { + if (this.configFile == null) { + this.configFile = new File(plugin.getDataFolder(), "config.yml"); + } + if (!this.configFile.exists()) { + this.plugin.saveResource("config.yml", false); + this.settings = YamlConfiguration.loadConfiguration(this.configFile); + Utils.logMini("new config.yml created"); + } else { + this.settings = YamlConfiguration.loadConfiguration(this.configFile); + } + matchConfig(this.settings, this.configFile); + loadSettings(); + Utils.logMini("config.yml loaded"); + } + + // Used to update config + @SuppressWarnings("ConstantConditions") + private void matchConfig(FileConfiguration config, File file) { + try { + boolean hasUpdated = false; + InputStream is = plugin.getResource(file.getName()); + assert is != null; + InputStreamReader isr = new InputStreamReader(is); + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(isr); + for (String key : defConfig.getConfigurationSection("").getKeys(true)) { + if (!config.contains(key)) { + config.set(key, defConfig.get(key)); + hasUpdated = true; + } + } + for (String key : config.getConfigurationSection("").getKeys(true)) { + if (!defConfig.contains(key) && !key.equalsIgnoreCase("recipe-delay")) { + config.set(key, null); + hasUpdated = true; + } + } + if (hasUpdated) + config.save(file); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("unused") + public FileConfiguration getSettings() { + return this.settings; + } + + private void loadSettings() { + this.lang = this.settings.getString("Language"); + + // SETTINGS + this.settings_resource_pack_enabled = this.settings.getBoolean("settings.enable-resource-pack"); + this.settings_resource_pack_url = this.settings.getString("settings.resource-pack-url"); + this.settings_local_chat_distance = this.settings.getInt("settings.local-chat-distance"); + + // WELCOME GUIDE + this.welcome_guide_enabled = this.settings.getBoolean("welcome-guide.enabled"); + this.welcome_guide_new_players = this.settings.getBoolean("welcome-guide.new-players-only"); + this.welcome_guide_delay = this.settings.getInt("welcome-guide.delay"); + + // SURVIVAL + this.survival_enabled = this.settings.getBoolean("survival.enabled"); + this.survival_unlock_all_recipes = this.settings.getBoolean("survival.unlock-all-recipes-on-join"); + this.survival_remove_wood_tools = this.settings.getBoolean("survival.remove-wooden-tools"); + this.survival_torch = this.settings.getBoolean("survival.torch"); // TODO move to recipes area?!?!? + this.survival_update_merchant_trades = this.settings.getBoolean("survival.update-merchant-trades"); + this.survival_update_loot_tables = this.settings.getBoolean("survival.update-loot-tables"); + + this.survival_break_only_with_sickle = this.settings.getBoolean("survival.break-only-with.sickle"); + this.survival_break_only_with_shovel = this.settings.getBoolean("survival.break-only-with.shovel"); + this.survival_break_only_with_axe = this.settings.getBoolean("survival.break-only-with.axe"); + this.survival_break_only_with_pickaxe = this.settings.getBoolean("survival.break-only-with.pickaxe"); + this.survival_break_only_with_shears = this.settings.getBoolean("survival.break-only-with.shears"); + this.survival_place_only_with_hammer = this.settings.getBoolean("survival.place-only-with.hammer"); + + this.survival_sickle_flint = this.settings.getBoolean("survival.sickles.flint"); + this.survival_sickle_stone = this.settings.getBoolean("survival.sickles.stone"); + this.survival_sickle_iron = this.settings.getBoolean("survival.sickles.iron"); + this.survival_sickle_diamond = this.settings.getBoolean("survival.sickles.diamond"); + + this.survival_drop_rate_stick = this.settings.getDouble("survival.drop-rate.stick"); + this.survival_drop_rate_flint = this.settings.getDouble("survival.drop-rate.flint"); + + // MECHANICS + this.mechanics_slow_armor = this.settings.getBoolean("mechanics.slow-armor"); + this.mechanics_reinforced_armor = this.settings.getBoolean("mechanics.reinforced-leather-armor"); + this.mechanics_bow = this.settings.getBoolean("mechanics.bow"); + this.mechanics_recurved_bow = this.settings.getBoolean("mechanics.recurve-bow"); + this.mechanics_grappling_hook = this.settings.getBoolean("mechanics.grappling-hook"); + this.mechanics_medic_kit = this.settings.getBoolean("mechanics.medical-kit"); + this.mechanics_reduced_iron_nugget = this.settings.getBoolean("mechanics.reduced-iron-nugget"); + this.mechanics_reduced_gold_nugget = this.settings.getBoolean("mechanics.reduced-gold-nugget"); + + this.mechanics_status_scoreboard = this.settings.getBoolean("mechanics.status-scoreboard"); + this.MECHANICS_ALERT_INTERVAL = this.settings.getInt("mechanics.alert-interval"); + + this.mechanics_raw_meat_hunger = this.settings.getBoolean("mechanics.raw-meat-hunger"); + this.mechanics_empty_potion = this.settings.getBoolean("mechanics.empty-potions"); + this.mechanics_poison_potato = this.settings.getBoolean("mechanics.poisonous-potato"); + this.mechanics_cookie_boost = this.settings.getBoolean("mechanics.cookie-health-boost"); + this.mechanics_beet_strength = this.settings.getBoolean("mechanics.beetroot-strength"); + + this.mechanics_food_diversity_enabled = this.settings.getBoolean("mechanics.food-diversity.enabled"); + this.mechanics_food_immunity_minutes = this.settings.getInt("mechanics.food-diversity.immunity-minutes"); + this.mechanics_food_max_level = this.settings.getInt("mechanics.food-diversity.max-level"); + this.mechanics_food_diversity_enabled = this.settings.getBoolean("mechanics.food-diversity.enabled"); + this.mechanics_food_start_carbs = this.settings.getInt("mechanics.food-diversity.start-level.carbs"); + this.mechanics_food_start_vitamins = this.settings.getInt("mechanics.food-diversity.start-level.vitamins"); + this.mechanics_food_start_protein = this.settings.getInt("mechanics.food-diversity.start-level.proteins"); + this.mechanics_food_diversity_enabled = this.settings.getBoolean("mechanics.food-diversity.enabled"); + this.mechanics_food_respawn_carbs = this.settings.getInt("mechanics.food-diversity.respawn-level.carbs"); + this.mechanics_food_respawn_vitamins = this.settings.getInt("mechanics.food-diversity.respawn-level.vitamins"); + this.mechanics_food_respawn_proteins = this.settings.getInt("mechanics.food-diversity.respawn-level.proteins"); + this.mechanics_food_effects_carbs_ex_amp_easy = this.settings.getInt("mechanics.food-diversity.effects.carbs.exhaustion-amplifier.easy"); + this.mechanics_food_effects_carbs_ex_amp_medium = this.settings.getInt("mechanics.food-diversity.effects.carbs.exhaustion-amplifier.normal"); + this.mechanics_food_effects_carbs_ex_amp_hard = this.settings.getInt("mechanics.food-diversity.effects.carbs.exhaustion-amplifier.hard"); + this.mechanics_food_effects_vitamins_ex_amp = this.settings.getInt("mechanics.food-diversity.effects.vitamins.exhaustion-amplifier"); + this.mechanics_food_effects_vitamins_se_normal_effect = this.settings.getString("mechanics.food-diversity.effects.vitamins.status-effects.normal.effect"); + this.mechanics_food_effects_vitamins_se_normal_amp = this.settings.getInt("mechanics.food-diversity.effects.vitamins.status-effects.normal.amplifier"); + this.mechanics_food_effects_vitamins_se_normal_duration = this.settings.getInt("mechanics.food-diversity.effects.vitamins.status-effects.normal.duration"); + this.mechanics_food_effects_vitamins_se_hard_effect = this.settings.getString("mechanics.food-diversity.effects.vitamins.status-effects.hard.effect"); + this.mechanics_food_effects_vitamins_se_hard_amp = this.settings.getInt("mechanics.food-diversity.effects.vitamins.status-effects.hard.amplifier"); + this.mechanics_food_effects_vitamins_se_hard_duration = this.settings.getInt("mechanics.food-diversity.effects.vitamins.status-effects.hard.duration"); + + this.mechanics_food_effects_protein_ex_amp = this.settings.getInt("mechanics.food-diversity.effects.proteins.exhaustion-amplifier"); + this.mechanics_food_effects_protein_se_normal_effect = this.settings.getString("mechanics.food-diversity.effects.proteins.status-effects.normal.effect"); + this.mechanics_food_effects_protein_se_normal_amp = this.settings.getInt("mechanics.food-diversity.effects.proteins.status-effects.normal.amplifier"); + this.mechanics_food_effects_protein_se_normal_duration = this.settings.getInt("mechanics.food-diversity.effects.proteins.status-effects.normal.duration"); + this.mechanics_food_effects_protein_se_hard_effect = this.settings.getString("mechanics.food-diversity.effects.proteins.status-effects.hard.effect"); + this.mechanics_food_effects_protein_se_hard_amp = this.settings.getInt("mechanics.food-diversity.effects.proteins.status-effects.hard.amplifier"); + this.mechanics_food_effects_protein_se_hard_duration = this.settings.getInt("mechanics.food-diversity.effects.proteins.status-effects.hard.duration"); + + this.mechanics_thirst_enabled = this.settings.getBoolean("mechanics.thirst.enabled"); + this.mechanics_thirst_starting_amount = this.settings.getDouble("mechanics.thirst.starting-amount"); + this.mechanics_thirst_respawn_amount = this.settings.getDouble("mechanics.thirst.respawn-amount"); + this.mechanics_thirst_immunity_minutes = this.settings.getInt("mechanics.thirst.immunity-minutes"); + this.mechanics_thirst_purify_water = this.settings.getBoolean("mechanics.thirst.purify-water"); + this.mechanics_thirst_melt_snow = this.settings.getBoolean("mechanics.thirst.melt-snow"); + this.mechanics_thirst_drain_rate = this.settings.getDouble("mechanics.thirst.drain-rate"); + this.mechanics_thirst_heat_drain_rate = this.settings.getDouble("mechanics.thirst.heat-drain-rate"); + this.mechanics_thirst_nether_drain_rate = this.settings.getDouble("mechanics.thirst.nether-drain-rate"); + this.mechanics_thirst_damage_rate = this.settings.getDouble("mechanics.thirst.damage-rate"); + + this.mechanics_thirst_rep_apple = this.settings.getDouble("mechanics.thirst.replenish-level.apple"); + this.mechanics_thirst_rep_beetroot_soup = this.settings.getDouble("mechanics.thirst.replenish-level.beetroot-soup"); + this.mechanics_thirst_rep_melon_slice = this.settings.getDouble("mechanics.thirst.replenish-level.melon-slice"); + this.mechanics_thirst_rep_mush_stew = this.settings.getDouble("mechanics.thirst.replenish-level.mushroom-stew"); + this.mechanics_thirst_rep_milk_bucket = this.settings.getDouble("mechanics.thirst.replenish-level.milk-bucket"); + this.mechanics_thirst_rep_honey_bottle = this.settings.getDouble("mechanics.thirst.replenish-level.honey-bottle"); + this.mechanics_thirst_rep_other_water = this.settings.getDouble("mechanics.thirst.replenish-level.other-water"); + this.mechanics_thirst_rep_water = this.settings.getDouble("mechanics.thirst.replenish-level.water"); + + this.mechanics_shared_workbench = this.settings.getBoolean("mechanics.shared-workbench"); + this.mechanics_energy_enabled = this.settings.getBoolean("mechanics.energy.enabled"); + this.mechanics_energy_start = this.settings.getDouble("mechanics.energy.start-level"); + this.mechanics_energy_respawn = this.settings.getDouble("mechanics.energy.respawn-level"); + this.mechanics_energy_immunity_minutes = this.settings.getInt("mechanics.energy.immunity-minutes"); + this.mechanics_energy_warning = this.settings.getBoolean("mechanics.energy.warning"); + this.mechanics_energy_drain_rate = this.settings.getDouble("mechanics.energy.drain-rate"); + this.mechanics_energy_drain_cold_rate = this.settings.getDouble("mechanics.energy.cold-drain-rate"); + this.mechanics_energy_refresh_rate_bed = this.settings.getDouble("mechanics.energy.sleeping-refresh-rate"); + this.mechanics_energy_refresh_rate_chair = this.settings.getDouble("mechanics.energy.chair-refresh-rate"); + this.mechanics_energy_exhaustion = this.settings.getDouble("mechanics.energy.exhaustion"); + this.mechanics_energy_coffee_enabled = this.settings.getBoolean("mechanics.energy.coffee"); + this.mechanics_energy_absorption = this.settings.getBoolean("mechanics.energy.absorption"); + this.mechanics_energy_haste = this.settings.getBoolean("mechanics.energy.haste"); + + this.mechanics_hunger_start_amount = this.settings.getInt("mechanics.hunger.starting-amount"); + this.mechanics_hunger_respawn_amount = this.settings.getInt("mechanics.hunger.respawn-amount"); + + this.mechanics_compass_waypoint = this.settings.getBoolean("mechanics.compass-waypoint.enabled"); + this.mechanics_compass_waypoint_worlds = this.settings.getBoolean("mechanics.compass-waypoint.per-world"); + + this.mechanics_tropical_fish = this.settings.getBoolean("mechanics.tropical-fish"); + this.mechanics_fermented_skin = this.settings.getBoolean("mechanics.fermented-skin"); + this.mechanics_living_slime = this.settings.getBoolean("mechanics.living-slime"); + + this.mechanics_snowball_revamp = this.settings.getBoolean("mechanics.snowball-revamp"); + + this.mechanics_farming_products_cookie = this.settings.getBoolean("mechanics.farming-products.cookie"); + this.mechanics_farming_products_bread = this.settings.getBoolean("mechanics.farming-products.bread"); + + this.mechanics_chairs_enabled = this.settings.getBoolean("mechanics.chairs.enabled"); + this.mechanics_chairs_max_width = this.settings.getInt("mechanics.chairs.max-chair-width"); + this.mechanics_chairs_blocks = getChairBlocks(); + + this.mechanics_weather_enabled = this.settings.getBoolean("mechanics.weather.enabled"); + this.mechanics_weather_speed_base = this.settings.getDouble("mechanics.weather.speed.base"); + this.mechanics_weather_speed_rain = this.settings.getDouble("mechanics.weather.speed.rain"); + this.mechanics_weather_speed_storm = this.settings.getDouble("mechanics.weather.speed.storm"); + this.mechanics_weather_speed_snow = this.settings.getDouble("mechanics.weather.speed.snow"); + this.mechanics_weather_speed_snowstorm = this.settings.getDouble("mechanics.weather.speed.snowstorm"); + + // ITEM MECHANICS + this.item_mechanics_firestriker_cook_time = this.settings.getInt("item-mechanics.firestriker.cook-time"); + + // ENTITY MECHANICS + this.entity_mechanics_pigmen_chest_enabled = this.settings.getBoolean("entity-mechanics.zombified-piglin-chests.enabled"); + this.entity_mechanics_pigmen_chest_radius = this.settings.getInt("entity-mechanics.zombified-piglin-chests.distance"); + this.entity_mechanics_pigmen_chest_speed = this.settings.getDouble("entity-mechanics.zombified-piglin-chests.speed-modifier"); + this.entity_mechanics_beekeeper_suit_enabled = this.settings.getBoolean("entity-mechanics.beekeeper-suit.enabled"); + this.entity_mechanics_suspicious_meat_enabled = this.settings.getBoolean("entity-mechanics.suspicious-meat.enabled"); + this.entity_mechanics_suspicious_meat_chance = this.settings.getInt("entity-mechanics.suspicious-meat.chance"); + this.entity_mechanics_chicken_breeding_enabled = this.settings.getBoolean("entity-mechanics.chicken-breeding.enabled"); + this.entity_mechanics_chicken_breeding_max_eggs = this.settings.getInt("entity-mechanics.chicken-breeding.max-eggs"); + this.entity_mechanics_chicken_breeding_always_baby = this.settings.getBoolean("entity-mechanics.chicken-breeding.always-baby"); + this.entity_mechanics_chicken_breeding_baby_ticks = this.settings.getInt("entity-mechanics.chicken-breeding.baby-ticks"); + this.entity_mechanics_piglin_drop_water = this.settings.getBoolean("entity-mechanics.piglin-barter.drop-purified-water"); + this.entity_mechanics_piglin_alt_drop = this.settings.getBoolean("entity-mechanics.piglin-barter.alternate-bartering"); + this.entity_mechanics_mobs_avoid_players = getEntityTypes("entity-mechanics.mobs-avoid-players"); + this.entity_mechanics_angry_wolves = AngryWolfGoal.Type.getByKey(this.settings.getString("entity-mechanics.angry-wolves", "night")); + + // RECIPES + this.recipes_saddle = this.settings.getBoolean("recipes.saddle"); + this.recipes_name_tag = this.settings.getBoolean("recipes.nametag"); + this.recipes_packed_ice = this.settings.getBoolean("recipes.packed-ice"); + this.recipes_leather_bard = this.settings.getBoolean("recipes.leather-bard"); + this.recipes_iron_bard = this.settings.getBoolean("recipes.iron-bard"); + this.recipes_gold_bard = this.settings.getBoolean("recipes.gold-bard"); + this.recipes_diamond_bard = this.settings.getBoolean("recipes.diamond-bard"); + this.recipes_clay_brick = this.settings.getBoolean("recipes.clay-brick"); + this.recipes_quartz_block = this.settings.getBoolean("recipes.quartz-block"); + this.recipes_wool_string = this.settings.getBoolean("recipes.wool-string"); + this.recipes_web_string = this.settings.getBoolean("recipes.web-string"); + this.recipes_ice = this.settings.getBoolean("recipes.ice"); + this.recipes_clay = this.settings.getBoolean("recipes.clay"); + this.recipes_diorite = this.settings.getBoolean("recipes.diorite"); + this.recipes_granite = this.settings.getBoolean("recipes.granite"); + this.recipes_andesite = this.settings.getBoolean("recipes.andesite"); + this.recipes_gravel = this.settings.getBoolean("recipes.gravel"); + this.recipes_slimeball = this.settings.getBoolean("recipes.slimeball"); + this.recipes_cobweb = this.settings.getBoolean("recipes.cobweb"); + this.recipes_sapling_stick = this.settings.getBoolean("recipes.sapling-to-sticks"); + this.recipes_fishing_rod = this.settings.getBoolean("recipes.fishing-rod"); + this.recipes_furnace = this.settings.getBoolean("recipes.furnace"); + this.recipes_workbench = this.settings.getBoolean("recipes.workbench"); + + // LEGENDARY ITEMS + this.legendary_valkyrie = this.settings.getBoolean("legendary-items.valkyrie-axe"); + this.legendary_quartz_pickaxe = this.settings.getBoolean("legendary-items.quartz-pickaxe"); + this.legendary_obsidian_mace = this.settings.getBoolean("legendary-items.obsidian-mace"); + this.legendary_giant_blade = this.settings.getBoolean("legendary-items.giant-blade"); + this.legendary_blaze_sword = this.settings.getBoolean("legendary-items.blaze-sword"); + this.legendary_notch_apple = this.settings.getBoolean("legendary-items.notch-apple"); + this.legendary_gold_armor_buff = this.settings.getBoolean("legendary-items.gold-armor-buff"); + + // HIDDEN CONFIG + this.recipe_delay = this.settings.getInt("recipe-delay", 0); + } + + private List getChairBlocks() { + List materials = new ArrayList<>(); + List allowedByStrings = this.settings.getStringList("mechanics.chairs.allowed-blocks"); + for (String string : allowedByStrings) { + if (string.startsWith("#")) { + NamespacedKey key; + if (string.contains(":")) key = NamespacedKey.fromString(string.substring(1)); + else key = NamespacedKey.minecraft(string.substring(1)); + + if (key != null) { + Tag tag = Bukkit.getTag(Tag.REGISTRY_BLOCKS, key, Material.class); + if (tag != null) { + for (Material material : tag.getValues()) { + if (Tag.STAIRS.isTagged(material)) { + materials.add(material); + } else { + Utils.logMini("Invalid chair material: %s", key.toString()); + } + } + } + } + } else { + NamespacedKey key; + if (string.contains(":")) key = NamespacedKey.fromString(string); + else key = NamespacedKey.minecraft(string); + + if (key != null) { + Material material = Registry.MATERIAL.get(key); + if (material != null) { + if (Tag.STAIRS.isTagged(material)) { + materials.add(material); + } else { + Utils.logMini("Invalid chair material: %s", key.toString()); + } + } + + } + } + } + return materials; + } + + @SuppressWarnings("SameParameterValue") + private List getEntityTypes(String path) { + List entityTypes = new ArrayList<>(); + List stringList = this.settings.getStringList(path); + for (String string : stringList) { + if (string.startsWith("#")) { + NamespacedKey key; + if (string.contains(":")) key = NamespacedKey.fromString(string); + else key = NamespacedKey.minecraft(string); + if (key != null) { + Tag tag = Bukkit.getTag(Tag.REGISTRY_ENTITY_TYPES, key, EntityType.class); + if (tag != null) { + for (EntityType entityType : tag.getValues()) { + if (entityType != null) { + Class entityClass = entityType.getEntityClass(); + if (entityClass == null || !Mob.class.isAssignableFrom(entityClass)) continue; + entityTypes.add(entityType); + } + } + } + } + } else { + NamespacedKey key; + if (string.contains(":")) key = NamespacedKey.fromString(string); + else key = NamespacedKey.minecraft(string); + if (key != null) { + EntityType entityType = Registry.ENTITY_TYPE.get(key); + if (entityType != null) { + Class entityClass = entityType.getEntityClass(); + if (entityClass == null || !Mob.class.isAssignableFrom(entityClass)) continue; + entityTypes.add(entityType); + } + } + } + } + + return entityTypes; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/config/ItemConfig.java b/src/main/java/com/shanebeestudios/survival/plugin/config/ItemConfig.java new file mode 100644 index 0000000..da8f851 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/config/ItemConfig.java @@ -0,0 +1,170 @@ +package com.shanebeestudios.survival.plugin.config; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.item.Nutrition; +import com.shanebeestudios.survival.api.util.Utils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; + +public class ItemConfig { + + public static ItemConfig INSTANCE; + private final SurvivalPlugin plugin = SurvivalPlugin.getInstance(); + private FileConfiguration settings; + private File configFile; + + public ItemConfig() { + INSTANCE = this; + loadDefaultSettings(); + Nutrition.setup(); + save(); + Utils.logMini("items.yml loaded"); + } + + private void loadDefaultSettings() { + if (configFile == null) { + configFile = new File(plugin.getDataFolder(), "items.yml"); + } + if (!configFile.exists()) { + plugin.saveResource("items.yml", false); + settings = YamlConfiguration.loadConfiguration(configFile); + Utils.logMini("New items.yml created"); + } else { + settings = YamlConfiguration.loadConfiguration(configFile); + } + matchConfig(this.settings, this.configFile); + } + + private void matchConfig(FileConfiguration config, File file) { + try { + boolean hasUpdated = false; + InputStream is = plugin.getResource(file.getName()); + assert is != null; + InputStreamReader isr = new InputStreamReader(is); + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(isr); + for (String key : defConfig.getConfigurationSection("").getKeys(true)) { + if (!config.contains(key)) { + config.set(key, defConfig.get(key)); + hasUpdated = true; + } + } + if (hasUpdated) + config.save(file); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public int[] getNutritionValues(String key, int carbs, int proteins, int vitamins) { + String path = "nutritions." + key + "."; + String[] paths = new String[]{path + "carbs", path + "proteins", path + "vitamins"}; + int[] nutritions = new int[]{carbs, proteins, vitamins}; + if (settings.contains(paths[0])) { + nutritions[0] = settings.getInt(paths[0]); + } else { + settings.set(paths[0], carbs); + } + if (settings.contains(paths[1])) { + nutritions[1] = settings.getInt(paths[1]); + } else { + settings.set(paths[1], proteins); + } + if (settings.contains(paths[2])) { + nutritions[2] = settings.getInt(paths[2]); + } else { + settings.set(paths[2], vitamins); + } + return nutritions; + } + + public String getName(String key) { + return this.settings.getString("items." + key + ".name"); + } + + public List getLore(String key) { + String path = "items." + key + ".lore"; + if (this.settings.contains(path)) { + return this.settings.getStringList(path); + } + return null; + } + + public int getMaxDamage(String key) { + String path = "items." + key + ".max_damage"; + if (this.settings.contains(path)) { + return this.settings.getInt(path); + } + return 0; + } + + public int getRepairCost(String key) { + String path = "items." + key + ".repair_cost"; + if (this.settings.contains(path)) { + return this.settings.getInt(path); + } + return 0; + } + + public double getRepairPercent(String key) { + String path = "items." + key + ".repair_percent"; + if (this.settings.contains(path)) { + return this.settings.getDouble(path); + } + return 0; + } + + public int getColor(String key) { + String path = "items." + key + ".color"; + if (this.settings.contains(path)) { + return this.settings.getInt(path); + } + return 0; + } + + public int getInt(String itemKey, String valueKey, int defaultValue) { + String path = "items." + itemKey + "." + valueKey; + if (this.settings.contains(path)) { + return this.settings.getInt(path); + } + return defaultValue; + } + + public double getDouble(String itemKey, String valueKey, double defaultValue) { + String path = "items." + itemKey + "." + valueKey; + if (this.settings.contains(path)) { + return this.settings.getDouble(path); + } + return defaultValue; + } + + public String getString(String itemKey, String valueKey, String defaultValue) { + String path = "items." + itemKey + "." + valueKey; + if (this.settings.contains(path)) { + return this.settings.getString(path); + } + return defaultValue; + } + + public boolean getBoolean(String itemKey, String valueKey, boolean defaultValue) { + String path = "items." + itemKey + "." + valueKey; + if (this.settings.contains(path)) { + return this.settings.getBoolean(path); + } + return defaultValue; + } + + void save() { + try { + settings.save(configFile); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/config/Lang.java b/src/main/java/com/shanebeestudios/survival/plugin/config/Lang.java new file mode 100644 index 0000000..2e89fc9 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/config/Lang.java @@ -0,0 +1,254 @@ +package com.shanebeestudios.survival.plugin.config; + +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.util.Utils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class Lang { + + private final SurvivalPlugin plugin; + private final String langFilePath; + private FileConfiguration lang; + + public String prefix; + public String no_perm; + public String survival_guide_msg; + + public String resource_pack_apply; + public String resource_pack_fail_download; + + public String task_must_use_shovel; + public String task_must_use_axe; + public String task_must_use_pick; + public String task_must_use_sickle; + public String task_must_use_shear; + public String task_must_use_hammer; + + public String charge; + public String charge_ready; + public String charge_unable; + + public String lack_of_energy; + public String arrows_off_hand; + public String arrows_off_hand_crossbow; + public String bow_main_hand; + + public String fishing_off_hand; + public String fishing_main_hand; + public String grappling_off_hand; + public String grappling_main_hand; + public String compass_waypoint_set; + public String compass_waypoint_get; + public String compass_waypoint_unset; + public String toggle_chat_local; + public String toggle_chat_global; + + public String starved_eat; + public String dehydrated_drink; + public String healthboard_title; + public String hunger; + public String thirst; + public String energy; + public String nutrients; + public String carbohydrates; + public String carbohydrates_lack; + public String protein; + public String protein_lack; + public String vitamins; + public String vitamins_lack; + public String nutrition_gui; + public String nutrition_gui_next_page; + public String nutrition_gui_last_page; + + public String healing_other; + public String healing_self; + public String healing_being_healed; + public String healing_complete; + public String healing_interrupted; + + public String energy_level_10; + public String energy_level_6_5; + public String energy_level_3_5; + public String energy_level_2; + public String energy_level_1; + + public String right_click_sprinting; + public String right_click_sneaking; + public String decrease_hunger_value; + public String firestriker; + public String poisoned_enemy; + public String poisoned_retain; + public String reduce_50; + public String prevent_dual_wield; + public String valkyrie_axe_spin; + public String valkyrie_axe_cooldown; + public String quartz_breaker; + public String haste; + public String cripple_hit; + public String drain_hit; + public String exhausted_slow; + public String expire_disarm; + public String knockback_resistance; + public String half_shield_resistance; + public String reflecting_coming; + public String blaze_sword_fire_resistance; + public String blaze_sword_fiery; + public String blaze_sword_spread_fire; + public String blaze_sword_cost; + public String hot_milk_drink; + + public String cmd_heal_self; + public String cmd_heal_by; + public String cmd_heal_other; + + public Lang(SurvivalPlugin main, String language) { + this.plugin = main; + this.langFilePath = "lang_" + language + ".yml"; + } + + public void loadLangFile(CommandSender sender) { + String loaded; + File lang_file = new File(plugin.getDataFolder(), langFilePath); + if (!lang_file.exists()) { + plugin.saveResource(langFilePath, true); + loaded = "New " + langFilePath + " created"; + } else { + loaded = "" + langFilePath + " loaded"; + matchConfig(YamlConfiguration.loadConfiguration(lang_file), lang_file); + } + lang = YamlConfiguration.loadConfiguration(lang_file); + + prefix = lang.getString("prefix"); + no_perm = lang.getString("no-perm"); + survival_guide_msg = lang.getString("survival-guide-msg"); + resource_pack_apply = lang.getString("resource-pack-apply"); + resource_pack_fail_download = lang.getString("resource-pack-fail-download"); + task_must_use_shovel = lang.getString("task-must-use-shovel"); + task_must_use_axe = lang.getString("task-must-use-axe"); + task_must_use_pick = lang.getString("task-must-use-pick"); + task_must_use_sickle = lang.getString("task-must-use-sickle"); + task_must_use_shear = lang.getString("task-must-use-shear"); + task_must_use_hammer = lang.getString("task-must-use-hammer"); + charge = lang.getString("charge"); + charge_ready = lang.getString("charge-ready"); + charge_unable = lang.getString("charge-unable"); + lack_of_energy = lang.getString("lack-of-energy"); + arrows_off_hand = lang.getString("arrows-off-hand"); + arrows_off_hand_crossbow = lang.getString("arrows-off-hand-crossbow"); + bow_main_hand = lang.getString("bow-main-hand"); + fishing_off_hand = lang.getString("fishing-off-hand"); + fishing_main_hand = lang.getString("fishing-main-hand"); + grappling_off_hand = lang.getString("grappling-off-hand"); + grappling_main_hand = lang.getString("grappling-main-hand"); + compass_waypoint_set = lang.getString("compass-waypoint-set"); + compass_waypoint_get = lang.getString("compass-waypoint-get"); + compass_waypoint_unset = lang.getString("compass-waypoint-unset"); + toggle_chat_local = lang.getString("toggle-chat-local"); + toggle_chat_global = lang.getString("toggle-chat-global"); + starved_eat = lang.getString("starved-eat"); + dehydrated_drink = lang.getString("dehydrated-drink"); + healthboard_title = lang.getString("healthboard-title"); + hunger = lang.getString("hunger"); + thirst = lang.getString("thirst"); + energy = lang.getString("energy"); + nutrients = lang.getString("nutrients"); + carbohydrates = lang.getString("carbohydrates"); + carbohydrates_lack = lang.getString("carbohydrates-lack"); + protein = lang.getString("protein"); + protein_lack = lang.getString("protein-lack"); + vitamins = lang.getString("vitamins"); + vitamins_lack = lang.getString("vitamins-lack"); + nutrition_gui = lang.getString("nutrition-gui"); + nutrition_gui_next_page = lang.getString("nutrition-gui-next-page"); + nutrition_gui_last_page = lang.getString("nutrition-gui-last-page"); + healing_other = lang.getString("healing-other"); + healing_self = lang.getString("healing-self"); + healing_being_healed = lang.getString("healing-being-healed"); + healing_complete = lang.getString("healing-complete"); + healing_interrupted = lang.getString("healing-interrupted"); + energy_level_10 = lang.getString("energy-level-10"); + energy_level_6_5 = lang.getString("energy-level-6-5"); + energy_level_3_5 = lang.getString("energy-level-3-5"); + energy_level_2 = lang.getString("energy-level-2"); + energy_level_1 = lang.getString("energy-level-1"); + right_click_sneaking = lang.getString("right-click-sneaking"); + right_click_sprinting = lang.getString("right-click-sprinting"); + decrease_hunger_value = lang.getString("decrease-hunger-value"); + firestriker = lang.getString("firestriker"); + poisoned_enemy = lang.getString("poisoned-enemy"); + poisoned_retain = lang.getString("poisoned-retain"); + reduce_50 = lang.getString("reduce-50"); + prevent_dual_wield = lang.getString("prevent-dual-wield"); + valkyrie_axe_spin = lang.getString("valkyrie-axe-spin"); + valkyrie_axe_cooldown = lang.getString("valkyrie-axe-cooldown"); + quartz_breaker = lang.getString("quartz-breaker"); + haste = lang.getString("haste"); + cripple_hit = lang.getString("cripple-hit"); + drain_hit = lang.getString("drain-hit"); + exhausted_slow = lang.getString("exhausted-slow"); + expire_disarm = lang.getString("expire-disarm"); + knockback_resistance = lang.getString("knockback-resistance"); + half_shield_resistance = lang.getString("half-shield-resistance"); + reflecting_coming = lang.getString("reflecting-coming"); + blaze_sword_fire_resistance = lang.getString("blaze-sword-fire-resistance"); + blaze_sword_fiery = lang.getString("blaze-sword-fiery"); + blaze_sword_spread_fire = lang.getString("blaze-sword-spread-fire"); + blaze_sword_cost = lang.getString("blaze-sword-cost"); + hot_milk_drink = lang.getString("hot-milk-drink"); + + cmd_heal_self = lang.getString("cmd-heal-self"); + cmd_heal_by = lang.getString("cmd-heal-by"); + cmd_heal_other = lang.getString("cmd-heal-other"); + + Utils.sendColoredMini(sender, prefix + loaded); + } + + // Used to update config + @SuppressWarnings("ConstantConditions") + private void matchConfig(FileConfiguration config, File file) { + try { + boolean hasUpdated = false; + InputStream test = plugin.getResource(file.getName()); + assert test != null; + InputStreamReader is = new InputStreamReader(test); + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(is); + for (String key : defConfig.getConfigurationSection("").getKeys(true)) { + if (!config.contains(key)) { + config.set(key, defConfig.get(key)); + hasUpdated = true; + } + } + for (String key : config.getConfigurationSection("").getKeys(true)) { + if (!defConfig.contains(key)) { + config.set(key, null); + hasUpdated = true; + } + } + if (hasUpdated) + config.save(file); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void saveLang(YamlConfiguration lang, File file) { + try { + lang.save(file); + Utils.logMini("%s Updated", this.langFilePath); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String getItemName(String key) { + return this.lang.getString("item-name." + key); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/config/PlayerDataConfig.java b/src/main/java/com/shanebeestudios/survival/plugin/config/PlayerDataConfig.java new file mode 100644 index 0000000..fc0b07c --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/config/PlayerDataConfig.java @@ -0,0 +1,58 @@ +package com.shanebeestudios.survival.plugin.config; + +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; + +public class PlayerDataConfig { + + private final SurvivalPlugin plugin; + private File playerDirectory = null; + + public PlayerDataConfig(SurvivalPlugin plugin) { + this.plugin = plugin; + loadPlayerDirectory(); + } + + private void loadPlayerDirectory() { + if (playerDirectory == null) { + playerDirectory = new File(plugin.getDataFolder(), "playerData"); + } + if (!playerDirectory.exists()) { + //noinspection ResultOfMethodCallIgnored + playerDirectory.mkdir(); + } + } + + public boolean hasPlayerDataFile(OfflinePlayer player) { + File file = new File(playerDirectory, player.getUniqueId() + ".yml"); + return file.exists(); + } + + public PlayerData getPlayerDataFromFile(OfflinePlayer player) { + File file = new File(playerDirectory, player.getUniqueId() + ".yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + + return ((PlayerData) config.get("player-data")); + } + + public void savePlayerDataToFile(PlayerData playerData) { + File file = new File(playerDirectory, playerData.getUuid().toString() + ".yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + config.set("player-data", playerData); + saveFile(config, file); + } + + private void saveFile(YamlConfiguration config, File file) { + try { + config.save(file); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/config/package-info.java b/src/main/java/com/shanebeestudios/survival/plugin/config/package-info.java new file mode 100644 index 0000000..f8969f4 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/config/package-info.java @@ -0,0 +1,4 @@ +/** + * Configs for the plugin + */ +package com.shanebeestudios.survival.plugin.config; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/EventManager.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/EventManager.java new file mode 100644 index 0000000..7cdc784 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/EventManager.java @@ -0,0 +1,152 @@ +package com.shanebeestudios.survival.plugin.listeners; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.listeners.block.BlockBreakListener; +import com.shanebeestudios.survival.plugin.listeners.block.BlockPlaceListener; +import com.shanebeestudios.survival.plugin.listeners.block.Campfire; +import com.shanebeestudios.survival.plugin.listeners.block.Chairs; +import com.shanebeestudios.survival.plugin.listeners.block.LootTableListener; +import com.shanebeestudios.survival.plugin.listeners.block.SnowballThrow; +import com.shanebeestudios.survival.plugin.listeners.block.WorkbenchShare; +import com.shanebeestudios.survival.plugin.listeners.entity.BeeKeeperSuit; +import com.shanebeestudios.survival.plugin.listeners.entity.ChestPigmen; +import com.shanebeestudios.survival.plugin.listeners.entity.ChickenSpawn; +import com.shanebeestudios.survival.plugin.listeners.entity.EntityDeath; +import com.shanebeestudios.survival.plugin.listeners.entity.LivingSlime; +import com.shanebeestudios.survival.plugin.listeners.entity.MerchantTrades; +import com.shanebeestudios.survival.plugin.listeners.entity.MobGoalListener; +import com.shanebeestudios.survival.plugin.listeners.entity.PiglinBarter; +import com.shanebeestudios.survival.plugin.listeners.item.BeetrootStrength; +import com.shanebeestudios.survival.plugin.listeners.item.BowListener; +import com.shanebeestudios.survival.plugin.listeners.item.CompassWaypoint; +import com.shanebeestudios.survival.plugin.listeners.item.CookieHealthBoost; +import com.shanebeestudios.survival.plugin.listeners.item.DrinkableItemListener; +import com.shanebeestudios.survival.plugin.listeners.item.DualWieldListener; +import com.shanebeestudios.survival.plugin.listeners.item.FirestrikerListener; +import com.shanebeestudios.survival.plugin.listeners.item.FoodDiversityConsume; +import com.shanebeestudios.survival.plugin.listeners.item.GiantBladeListener; +import com.shanebeestudios.survival.plugin.listeners.item.GrapplingHookListener; +import com.shanebeestudios.survival.plugin.listeners.item.MedicKit; +import com.shanebeestudios.survival.plugin.listeners.item.PoisonousPotato; +import com.shanebeestudios.survival.plugin.listeners.item.RawMeatHunger; +import com.shanebeestudios.survival.plugin.listeners.item.RecurvedBowListener; +import com.shanebeestudios.survival.plugin.listeners.item.RepairCrafting; +import com.shanebeestudios.survival.plugin.listeners.item.ShivPoison; +import com.shanebeestudios.survival.plugin.listeners.item.TropicalFish; +import com.shanebeestudios.survival.plugin.listeners.item.Valkyrie; +import com.shanebeestudios.survival.plugin.listeners.item.WaterBowlListener; +import com.shanebeestudios.survival.plugin.listeners.item.WaterPurifiedListener; +import com.shanebeestudios.survival.plugin.listeners.player.EnergyChange; +import com.shanebeestudios.survival.plugin.listeners.player.PlayerDataListener; +import com.shanebeestudios.survival.plugin.listeners.player.ThirstListener; +import com.shanebeestudios.survival.plugin.listeners.server.Guide; +import com.shanebeestudios.survival.plugin.listeners.server.LocalChat; +import com.shanebeestudios.survival.plugin.listeners.server.RecipeDiscovery; +import com.shanebeestudios.survival.plugin.listeners.server.ResourcePackListener; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; + +/** + * Internal use only + */ +public class EventManager { + + private final SurvivalPlugin plugin; + private final Config config; + + public EventManager(SurvivalPlugin plugin) { + this.plugin = plugin; + this.config = plugin.getSurvivalConfig(); + } + + public void registerEvents() { + PluginManager pluginManager = plugin.getServer().getPluginManager(); + pluginManager.registerEvents(this.plugin, this.plugin); + pluginManager.registerEvents(new RecipeDiscovery(this.plugin), this.plugin); + Bukkit.getPluginManager().registerEvents(new PlayerDataListener(this.plugin), this.plugin); + + if (this.config.survival_enabled) { + pluginManager.registerEvents(new BlockBreakListener(this.plugin), this.plugin); + pluginManager.registerEvents(new BlockPlaceListener(this.plugin), this.plugin); + pluginManager.registerEvents(new FirestrikerListener(this.plugin), this.plugin); + pluginManager.registerEvents(new ShivPoison(this.plugin), this.plugin); + pluginManager.registerEvents(new WaterBowlListener(this.plugin), this.plugin); + pluginManager.registerEvents(new Campfire(this.plugin), this.plugin); + } + if (this.config.mechanics_bow) + pluginManager.registerEvents(new BowListener(this.plugin), this.plugin); + if (this.config.mechanics_grappling_hook) + pluginManager.registerEvents(new GrapplingHookListener(this.plugin), this.plugin); + if (this.config.legendary_valkyrie) + pluginManager.registerEvents(new Valkyrie(this.plugin), this.plugin); + if (this.config.legendary_giant_blade) + pluginManager.registerEvents(new GiantBladeListener(this.plugin), this.plugin); + if (this.config.settings_local_chat_distance > -1) + pluginManager.registerEvents(new LocalChat(this.plugin), this.plugin); + if (this.config.mechanics_compass_waypoint) + pluginManager.registerEvents(new CompassWaypoint(this.plugin), this.plugin); + if (this.config.mechanics_medic_kit) + pluginManager.registerEvents(new MedicKit(this.plugin), this.plugin); + if (this.config.settings_resource_pack_enabled) { + pluginManager.registerEvents(new ResourcePackListener(this.plugin), this.plugin); + } + if (this.config.mechanics_raw_meat_hunger) + pluginManager.registerEvents(new RawMeatHunger(), this.plugin); + if (this.config.mechanics_thirst_enabled) { + pluginManager.registerEvents(new ThirstListener(this.plugin), this.plugin); + pluginManager.registerEvents(new DrinkableItemListener(this.plugin), this.plugin); + if (this.config.mechanics_thirst_purify_water) { + pluginManager.registerEvents(new WaterPurifiedListener(this.plugin), this.plugin); + } + } + if (this.config.mechanics_poison_potato) + pluginManager.registerEvents(new PoisonousPotato(), this.plugin); + if (this.config.mechanics_shared_workbench) + pluginManager.registerEvents(new WorkbenchShare(this.plugin), this.plugin); + if (this.config.mechanics_chairs_enabled) + pluginManager.registerEvents(new Chairs(this.plugin), this.plugin); + if (this.config.mechanics_cookie_boost) + pluginManager.registerEvents(new CookieHealthBoost(), this.plugin); + if (this.config.mechanics_beet_strength) + pluginManager.registerEvents(new BeetrootStrength(), this.plugin); + if (this.config.mechanics_tropical_fish) + pluginManager.registerEvents(new TropicalFish(this.plugin), this.plugin); + if (this.config.mechanics_living_slime) + pluginManager.registerEvents(new LivingSlime(this.plugin), this.plugin); + if (this.config.mechanics_energy_enabled) + pluginManager.registerEvents(new EnergyChange(this.plugin), this.plugin); + if (this.config.mechanics_food_diversity_enabled) + pluginManager.registerEvents(new FoodDiversityConsume(this.plugin), this.plugin); + if (this.config.mechanics_recurved_bow) + pluginManager.registerEvents(new RecurvedBowListener(this.plugin), this.plugin); + if (this.config.mechanics_snowball_revamp) + pluginManager.registerEvents(new SnowballThrow(), this.plugin); + if (this.config.entity_mechanics_chicken_breeding_enabled) + pluginManager.registerEvents(new ChickenSpawn(this.plugin), this.plugin); + if (this.config.welcome_guide_enabled) + pluginManager.registerEvents(new Guide(this.plugin), this.plugin); + + if (this.config.entity_mechanics_pigmen_chest_enabled) + pluginManager.registerEvents(new ChestPigmen(this.plugin), this.plugin); + + if (this.config.entity_mechanics_beekeeper_suit_enabled) { + Bukkit.getPluginManager().registerEvents(new BeeKeeperSuit(), this.plugin); + } + if (this.config.survival_update_merchant_trades) { + pluginManager.registerEvents(new MerchantTrades(this.plugin), this.plugin); + } + if (this.config.survival_update_loot_tables) { + pluginManager.registerEvents(new LootTableListener(this.plugin), this.plugin); + } + pluginManager.registerEvents(new PiglinBarter(this.plugin), this.plugin); + // Config handled within this event + pluginManager.registerEvents(new EntityDeath(this.plugin), this.plugin); + pluginManager.registerEvents(new RepairCrafting(), this.plugin); + pluginManager.registerEvents(new MobGoalListener(this.plugin), this.plugin); + + // TODO config? + pluginManager.registerEvents(new DualWieldListener(this.plugin), this.plugin); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/BlockBreakListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/BlockBreakListener.java new file mode 100644 index 0000000..5b2b75d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/BlockBreakListener.java @@ -0,0 +1,258 @@ +package com.shanebeestudios.survival.plugin.listeners.block; + +import com.shanebeestudios.survival.api.data.Permissions; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.registry.BlockTags; +import com.shanebeestudios.survival.api.util.ItemUtils; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.MessageManager; +import com.shanebeestudios.survival.plugin.managers.MessageManager.MessageType; +import org.bukkit.Effect; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.Tag; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Ageable; +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.BlockPhysicsEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.Random; + +public class BlockBreakListener implements Listener { + + private final Config config; + private final MessageManager messageManager; + + public BlockBreakListener(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + this.messageManager = plugin.getMessageManager(); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onBlockBreak(BlockBreakEvent event) { + Player player = event.getPlayer(); + if (player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR) return; + + ItemStack tool = player.getInventory().getItemInMainHand(); + + Block block = event.getBlock(); + Material material = block.getType(); + + if (Permissions.BYPASS_REQUIRED_TOOLS.has(player)) return; + + if (this.config.survival_break_only_with_shovel) { + if (!Tag.ITEMS_SHOVELS.isTagged(tool.getType())) { + // Gravel drop flint + if (material == Material.GRAVEL) { + event.setDropItems(false); + + Random rand = new Random(); + double chance = rand.nextDouble(); + + if (chance <= this.config.survival_drop_rate_flint) + block.getWorld().dropItemNaturally(block.getLocation().add(0.5, 0.1, 0.5), new ItemStack(Material.FLINT)); + return; + } else if (BlockTags.REQUIRES_SHOVEL.isTagged(material)) { + event.setCancelled(true); + player.updateInventory(); + this.messageManager.sendMessage(player, MessageType.REQUIRES_SHOVEL); + return; + } + } else if (this.config.survival_break_only_with_sickle) { + // Prevent bypassing sickle by breaking block below + Block above = block.getRelative(BlockFace.UP); + if (BlockTags.REQUIRES_SICKLE.isTagged(above.getType())) { + above.setType(Material.AIR); + } + return; + } + } + + if (this.config.survival_break_only_with_sickle && BlockTags.REQUIRES_SICKLE.isTagged(material)) { + if (!Items.Tags.SICKLES.isTagged(tool)) { + event.setCancelled(true); + this.messageManager.sendMessage(player, MessageType.REQUIRES_SICKLE); + } else { + event.setDropItems(false); + Location loc = event.getBlock().getLocation(); + int random = 1; + int damageItemAmount = 1; + boolean isFullyGrown = true; + + if (event.getBlock().getBlockData() instanceof Ageable ageable) { + isFullyGrown = ageable.getAge() == ageable.getMaximumAge(); + } + + // Flint/Stone sickles drop a chance of 0-1 items (not grown) or 1-2 (grown) + if (Items.FLINT_SICKLE.is(tool)) { + damageItemAmount = 4; + random = isFullyGrown ? new Random().nextInt(2) + 1 : new Random().nextInt(2); + } else if (Items.STONE_SICKLE.is(tool)) { + damageItemAmount = 2; + random = isFullyGrown ? new Random().nextInt(2) + 1 : new Random().nextInt(2); + } + // Iron/Diamond sickles drop a chance of 1 (not grown) or 2-4 items (grown) + else if (Items.IRON_SICKLE.is(tool) || Items.DIAMOND_SICKLE.is(tool)) { + random = isFullyGrown ? new Random().nextInt(2) + 3 : 1; + } + + for (Material drop : Utils.getDrops(material, isFullyGrown)) { + if (drop != Material.AIR && random != 0) { + assert loc.getWorld() != null; + if (drop == Material.PUMPKIN) { // prevent duping pumpkins + random = 1; + } + loc.getWorld().dropItemNaturally(loc.add(0.5, 0.1, 0.5), new ItemStack(drop, random)); + } + } + ItemUtils.damageItem(player, tool, damageItemAmount); + } + return; + } + + if (this.config.survival_break_only_with_axe && BlockTags.REQUIRES_AXE.isTagged(material)) { + if (!Tag.ITEMS_AXES.isTagged(tool.getType())) { + event.setCancelled(true); + player.updateInventory(); + this.messageManager.sendMessage(player, MessageType.REQUIRES_AXE); + return; + } + } + + if (this.config.survival_break_only_with_pickaxe && BlockTags.REQUIRES_PICKAXE.isTagged(material)) { + if (!Tag.ITEMS_PICKAXES.isTagged(tool.getType())) { + event.setCancelled(true); + player.updateInventory(); + this.messageManager.sendMessage(player, MessageType.REQUIRES_PICKAXE); + return; + } + } + + if (this.config.survival_break_only_with_shears && tool.getType() != Material.SHEARS) { + //Sticks - Maybe this should be removed since 1.14+ leaves drop sticks?!?!? + if (Tag.LEAVES.isTagged(material)) { + Random rand = new Random(); + double chance = rand.nextDouble(); + + if (chance <= this.config.survival_drop_rate_stick) + event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation().add(0.5, 0.1, 0.5), new ItemStack(Material.STICK)); + return; + } + if (BlockTags.REQUIRES_SHEARS.isTagged(material)) { + event.setCancelled(true); + player.updateInventory(); + this.messageManager.sendMessage(player, MessageType.REQUIRES_SHEARS); + return; + } + } + + if (this.config.recipes_workbench && material == Material.CRAFTING_TABLE && !event.isCancelled()) { + event.setDropItems(false); + ItemStack workbench = Items.WORKBENCH.getItemStack(); + block.getWorld().dropItem(block.getLocation(), workbench); + } + } + + @SuppressWarnings("deprecation") + @EventHandler + private void onHarvest(PlayerInteractEvent e) { + if (e.isCancelled()) return; + if (!this.config.survival_break_only_with_sickle) return; + if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK) + return; + Player player = e.getPlayer(); + Block block = e.getClickedBlock(); + ItemStack tool = player.getInventory().getItemInMainHand(); + assert block != null; + if (block.getType() == Material.SWEET_BERRY_BUSH) { + Ageable bush = ((Ageable) block.getBlockData()); + if (e.getItem() != null && e.getItem().getType() == Material.BONE_MEAL) { + if (bush.getAge() == 3) { + e.setCancelled(true); + return; + } else return; + } + if (!Items.Tags.SICKLES.isTagged(tool)) { + e.setCancelled(true); + this.messageManager.sendMessage(player, MessageType.REQUIRES_SICKLE); + } else { + if (bush.getAge() >= 2) { + int berries = 0; + Location loc = block.getLocation(); + assert loc.getWorld() != null; + e.setCancelled(true); + int random = new Random().nextInt(5) + 1; + + if (Items.FLINT_SICKLE.is(tool)) { + if (bush.getAge() == 3) { + berries = 1; + } + } else if (Items.STONE_SICKLE.is(tool)) { + if (bush.getAge() == 2) { + if (random <= 4) berries = 1; + } else if (bush.getAge() == 3) { + if (random <= 3) berries = 1; + else berries = 2; + } + } else if (Items.IRON_SICKLE.is(tool) || Items.DIAMOND_SICKLE.is(tool)) { + if (bush.getAge() == 2) { + if (random <= 3) berries = 1; + else berries = 2; + } else if (bush.getAge() == 3) { + if (random <= 4) berries = 2; + else berries = 4; + } + } + if (berries != 0) + loc.getWorld().dropItemNaturally(loc.add(0.5, 0.1, 0.5), new ItemStack(Material.SWEET_BERRIES, berries)); + + bush.setAge(1); + block.setBlockData(bush); + player.playSound(loc, Sound.BLOCK_SWEET_BERRY_BUSH_PICK_BERRIES, 1, 1); + ItemUtils.damageItem(player, tool, 1); + } + } + } + } + + @EventHandler + private void onWaterBreakCrops(BlockPhysicsEvent event) { + if (!this.config.survival_break_only_with_sickle) return; + if (event.getSourceBlock().getType() == Material.WATER) { + Material type = event.getBlock().getType(); + if (BlockTags.REQUIRES_SICKLE.isTagged(type)) { + if (type == Material.MELON || type == Material.PUMPKIN) return; + event.getBlock().setType(Material.AIR); + } + } + } + + @SuppressWarnings("deprecation") + @EventHandler(priority = EventPriority.HIGHEST) + private void onTrample(PlayerInteractEvent event) { + if (event.isCancelled()) return; + if (!this.config.survival_break_only_with_sickle) return; + if (event.getAction() == Action.PHYSICAL) { + if (event.getClickedBlock() == null) return; + if (event.getClickedBlock().getType() == Material.FARMLAND) { + Location loc = event.getClickedBlock().getLocation(); + assert loc.getWorld() != null; + loc.getWorld().playEffect(loc, Effect.STEP_SOUND, event.getClickedBlock().getRelative(BlockFace.UP).getType()); + event.getClickedBlock().getRelative(BlockFace.UP).setType(Material.AIR); + } + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/BlockPlaceListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/BlockPlaceListener.java new file mode 100644 index 0000000..ee2e9bd --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/BlockPlaceListener.java @@ -0,0 +1,49 @@ +package com.shanebeestudios.survival.plugin.listeners.block; + +import com.shanebeestudios.survival.api.data.Permissions; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.registry.BlockTags; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.MessageManager; +import com.shanebeestudios.survival.plugin.managers.MessageManager.MessageType; +import org.bukkit.GameMode; +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.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + +public class BlockPlaceListener implements Listener { + + private final Config config; + private final MessageManager messageManager; + + public BlockPlaceListener(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + this.messageManager = plugin.getMessageManager(); + } + + @SuppressWarnings("ConstantConditions") + @EventHandler(priority = EventPriority.HIGHEST) + private void onBlockPlace(BlockPlaceEvent event) { + if (event.isCancelled()) return; + if (!config.survival_place_only_with_hammer) return; + + Player player = event.getPlayer(); + if (Permissions.BYPASS_REQUIRED_TOOLS.has(player)) return; + if (player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR) return; + if (!BlockTags.REQUIRES_HAMMER.isTagged(event.getBlock().getType())) return; + + ItemStack offTool = player.getInventory().getItemInOffHand(); + if (Items.HAMMER.is(offTool)) { + offTool.damage(1, player); + } else { + event.setCancelled(true); + player.updateInventory(); + this.messageManager.sendMessage(player, MessageType.REQUIRES_HAMMER); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/Campfire.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/Campfire.java new file mode 100644 index 0000000..d98e288 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/Campfire.java @@ -0,0 +1,65 @@ +package com.shanebeestudios.survival.plugin.listeners.block; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.data.Lightable; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockCookEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; + +import java.util.Random; + +public class Campfire implements Listener { + + private final SurvivalPlugin plugin; + + public Campfire(SurvivalPlugin plugin) { + this.plugin = plugin; + } + + // Hit an unlit campfire with a stick to light it + @EventHandler + private void lightFire(PlayerInteractEvent event) { + if (event.getClickedBlock() == null) return; + if (event.getClickedBlock().getType() == Material.CAMPFIRE) { + if (event.getItem() != null && event.getItem().getType() == Material.STICK) { + Block block = event.getClickedBlock(); + Lightable camp = ((Lightable) block.getBlockData()); + if (camp.isLit()) return; + event.setCancelled(true); + int i = new Random().nextInt(20); + if (i == 10) { + camp.setLit(true); + block.setBlockData(camp); + ItemStack tool = event.getItem(); + tool.setAmount(tool.getAmount() - 1); + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_GENERIC_BURN, 1, 1), 1); + + } + } + } + } + + // Randomly put out the fire when cooking food + @EventHandler + private void fireFinishedCooking(BlockCookEvent event) { + if (event.getBlock().getType() != Material.CAMPFIRE) return; + int i = new Random().nextInt(8); + + if (i == 5) { + Block block = event.getBlock(); + Lightable camp = ((Lightable) block.getBlockData()); + camp.setLit(false); + block.setBlockData(camp); + block.getLocation().getWorld().playSound(block.getLocation(), Sound.BLOCK_FIRE_EXTINGUISH, 1, 1); + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/block/Chairs.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/Chairs.java similarity index 83% rename from src/main/java/tk/shanebee/survival/listeners/block/Chairs.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/block/Chairs.java index ee04d95..edfbfb9 100644 --- a/src/main/java/tk/shanebee/survival/listeners/block/Chairs.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/Chairs.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.block; +package com.shanebeestudios.survival.plugin.listeners.block; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -21,18 +21,19 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.util.Vector; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; import java.util.ArrayList; import java.util.List; +@SuppressWarnings("deprecation") public class Chairs implements Listener { - private final Survival plugin; + private final SurvivalPlugin plugin; private final Config config; - public Chairs(Survival plugin) { + public Chairs(SurvivalPlugin plugin) { this.plugin = plugin; this.config = plugin.getSurvivalConfig(); } @@ -43,7 +44,7 @@ private void onPlayerInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock(); assert block != null; - if (plugin.getChairBlocks().contains(block.getType())) { + if (this.config.mechanics_chairs_blocks.contains(block.getType())) { Player player = event.getPlayer(); Stairs stairs = (Stairs) block.getBlockData(); int chairwidth = 1; @@ -58,7 +59,7 @@ private void onPlayerInteract(PlayerInteractEvent event) { return; } - // Check for distance distance between player and chair. + // Check for distance between player and chair. if (player.getLocation().distance(block.getLocation().add(0.5, 0, 0.5)) > 2) return; @@ -86,7 +87,7 @@ private void onPlayerInteract(PlayerInteractEvent event) { chairwidth += getChairWidth(block, BlockFace.SOUTH); } - if (chairwidth > config.MECHANICS_CHAIRS_MAX_WIDTH) + if (chairwidth > this.config.mechanics_chairs_max_width) return; // Sit-down process. @@ -152,7 +153,7 @@ public void run() { @EventHandler(priority = EventPriority.HIGHEST) private void onBlockBreak(BlockBreakEvent event) { if (event.isCancelled()) return; - if (plugin.getChairBlocks().contains(event.getBlock().getType())) { + if (this.config.mechanics_chairs_blocks.contains(event.getBlock().getType())) { ArmorStand drop = dropSeat(event.getBlock(), ((Stairs) event.getBlock().getBlockData())); for (Entity e : drop.getNearbyEntities(0.5, 0.5, 0.5)) { @@ -239,10 +240,10 @@ private int getChairWidth(Block block, BlockFace face) { int width = 0; // Go through the blocks next to the clicked block and check if there are any further stairs. - for (int i = 1; i <= config.MECHANICS_CHAIRS_MAX_WIDTH; i++) { + for (int i = 1; i <= this.config.mechanics_chairs_max_width; i++) { Block relative = block.getRelative(face, i); - if (plugin.getChairBlocks().contains(relative.getType()) && ((Stairs) relative.getBlockData()).getFacing() == ((Stairs) block.getBlockData()).getFacing()) + if (this.config.mechanics_chairs_blocks.contains(relative.getType()) && ((Stairs) relative.getBlockData()).getFacing() == ((Stairs) block.getBlockData()).getFacing()) width++; else break; @@ -255,22 +256,16 @@ private boolean checkSign(Block block, BlockFace face) { // Go through the blocks next to the clicked block and check if are signs on the end. for (int i = 1; true; i++) { Block relative = block.getRelative(face, i); - if (!(plugin.getChairBlocks().contains(relative.getType())) || (block.getBlockData() instanceof Stairs && ((Stairs) relative.getBlockData()).getFacing() != ((Stairs) block.getBlockData()).getFacing())) { - if (Tag.SIGNS.isTagged(relative.getType())) return true; - switch (relative.getType()) { - case ITEM_FRAME: - case PAINTING: - case ACACIA_TRAPDOOR: - case BIRCH_TRAPDOOR: - case JUNGLE_TRAPDOOR: - case OAK_TRAPDOOR: - case SPRUCE_TRAPDOOR: - case DARK_OAK_TRAPDOOR: - case IRON_TRAPDOOR: - return true; - default: - return false; - } + if (!(this.config.mechanics_chairs_blocks.contains(relative.getType())) || + (block.getBlockData() instanceof Stairs && + ((Stairs) relative.getBlockData()).getFacing() != ((Stairs) block.getBlockData()).getFacing())) { + Material relativeType = relative.getType(); + if (Tag.SIGNS.isTagged(relativeType)) return true; + if (Tag.TRAPDOORS.isTagged(relativeType)) return true; + return switch (relativeType) { + case ITEM_FRAME, PAINTING -> true; + default -> false; + }; } } } diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/LootTableListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/LootTableListener.java new file mode 100644 index 0000000..d85ff24 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/LootTableListener.java @@ -0,0 +1,27 @@ +package com.shanebeestudios.survival.plugin.listeners.block; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.managers.LootManager; +import org.bukkit.block.Container; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.world.LootGenerateEvent; +import org.bukkit.inventory.InventoryHolder; + +public class LootTableListener implements Listener { + + private final LootManager lootManager; + + public LootTableListener(SurvivalPlugin plugin) { + this.lootManager = plugin.getLootManager(); + } + + @EventHandler + private void onLootGenerate(LootGenerateEvent event) { + InventoryHolder holder = event.getInventoryHolder(); + if (holder instanceof Container) { + this.lootManager.updateLoot(event.getLoot()); + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/block/SnowballThrow.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/SnowballThrow.java similarity index 91% rename from src/main/java/tk/shanebee/survival/listeners/block/SnowballThrow.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/block/SnowballThrow.java index db61da1..03bbf8c 100644 --- a/src/main/java/tk/shanebee/survival/listeners/block/SnowballThrow.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/SnowballThrow.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.block; +package com.shanebeestudios.survival.plugin.listeners.block; import org.bukkit.GameMode; import org.bukkit.Material; @@ -20,11 +20,10 @@ public class SnowballThrow implements Listener { @EventHandler - private void onThrowingSnowball(ProjectileHitEvent e) { - if (e.getEntity() instanceof Snowball) { - Snowball snowball = (Snowball) e.getEntity(); + private void onThrowingSnowball(ProjectileHitEvent event) { + if (event.getEntity() instanceof Snowball snowball) { - BlockIterator iterator = new BlockIterator(snowball.getWorld(), snowball.getLocation().toVector(), + BlockIterator iterator = new BlockIterator(snowball.getWorld(), snowball.getLocation().toVector(), snowball.getVelocity().normalize(), 0.0D, 4); Block actual = null; while (iterator.hasNext()) { diff --git a/src/main/java/tk/shanebee/survival/listeners/block/WorkbenchShare.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/WorkbenchShare.java similarity index 73% rename from src/main/java/tk/shanebee/survival/listeners/block/WorkbenchShare.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/block/WorkbenchShare.java index b30b1e7..2e76fee 100644 --- a/src/main/java/tk/shanebee/survival/listeners/block/WorkbenchShare.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/block/WorkbenchShare.java @@ -1,6 +1,7 @@ -package tk.shanebee.survival.listeners.block; +package com.shanebeestudios.survival.plugin.listeners.block; import com.google.common.collect.ImmutableSet; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; @@ -11,26 +12,33 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.inventory.*; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.inventory.InventoryInteractEvent; +import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; -import tk.shanebee.survival.Survival; -import java.util.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.UUID; public class WorkbenchShare implements Listener { - - private Survival plugin; - - public WorkbenchShare(Survival plugin) { + + private final SurvivalPlugin plugin; + + public WorkbenchShare(SurvivalPlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGHEST) - @SuppressWarnings("deprecation") + @SuppressWarnings({"deprecation", "unchecked"}) private void onPlayerInteract(PlayerInteractEvent e) { if (e.isCancelled()) return; final Player p = e.getPlayer(); @@ -47,7 +55,7 @@ private void onPlayerInteract(PlayerInteractEvent e) { if (!block.hasMetadata("shared_players")) block.setMetadata("shared_players", new FixedMetadataValue(plugin, new ArrayList())); - final List list = (block.getMetadata("shared_players").get(0).value() instanceof List) ? (List) block.getMetadata("shared_players").get(0).value() : new ArrayList<>(); + final List list = (block.getMetadata("shared_players").getFirst().value() instanceof List) ? (List) block.getMetadata("shared_players").getFirst().value() : new ArrayList<>(); final Inventory open = p.getOpenInventory().getTopInventory(); @@ -55,7 +63,7 @@ private void onPlayerInteract(PlayerInteractEvent e) { return; // Workaround to get the accessed WorkBench - final Block workbench = p.getTargetBlock(ImmutableSet.of(Material.GRASS, Material.SNOW, Material.AIR), 8); + final Block workbench = p.getTargetBlock(ImmutableSet.of(Material.SHORT_GRASS, Material.SNOW, Material.AIR), 8); if (workbench.getType() != Material.CRAFTING_TABLE) { // Close Inventory if player managed to access the workbench without actually use one. @@ -70,7 +78,7 @@ private void onPlayerInteract(PlayerInteractEvent e) { Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> { if (list.isEmpty()) return; - Player first = Bukkit.getPlayer(list.get(0)); + Player first = Bukkit.getPlayer(list.getFirst()); assert first != null; Inventory pInv = first.getOpenInventory().getTopInventory(); if (pInv.getType() != InventoryType.WORKBENCH) @@ -92,32 +100,30 @@ private void onInventoryDrag(InventoryDragEvent e) { onInventoryInteract(e); } - private void onInventoryInteract(InventoryInteractEvent e) { + @SuppressWarnings("unchecked") + private void onInventoryInteract(InventoryInteractEvent e) { if (e.isCancelled()) return; - if (!(e.getWhoClicked() instanceof Player)) + if (!(e.getWhoClicked() instanceof Player player)) return; - final Player p = (Player) e.getWhoClicked(); - - if (!p.hasMetadata("shared_workbench")) + if (!player.hasMetadata("shared_workbench")) return; if (e.getInventory().getType() == InventoryType.WORKBENCH) { // Workaround to get the accessed WorkBench - final Block workbench = (p.getMetadata("shared_workbench").get(0).value() instanceof Block) ? (Block) p.getMetadata("shared_workbench").get(0).value() : null; + final Block workbench = (player.getMetadata("shared_workbench").getFirst().value() instanceof Block) ? (Block) player.getMetadata("shared_workbench").getFirst().value() : null; assert workbench != null; if (!workbench.hasMetadata("shared_players") || workbench.getType() != Material.CRAFTING_TABLE) { - if (p.getOpenInventory().getTopInventory() != null) - p.getOpenInventory().getTopInventory().clear(); - p.closeInventory(); - p.removeMetadata("shared_workbench", plugin); + player.getOpenInventory().getTopInventory().clear(); + player.closeInventory(); + player.removeMetadata("shared_workbench", plugin); return; } - List list = (workbench.getMetadata("shared_players").get(0).value() instanceof List) ? (List) workbench.getMetadata("shared_players").get(0).value() : new ArrayList(); + List list = (workbench.getMetadata("shared_players").getFirst().value() instanceof List) ? (List) workbench.getMetadata("shared_players").getFirst().value() : new ArrayList(); - final Inventory pInv = p.getOpenInventory().getTopInventory(); + final Inventory pInv = player.getOpenInventory().getTopInventory(); if (pInv.getType() != InventoryType.WORKBENCH) { workbench.removeMetadata("shared_players", plugin); return; @@ -128,7 +134,7 @@ private void onInventoryInteract(InventoryInteractEvent e) { while (iterator.hasNext()) { UUID next = iterator.next(); - if (p.getUniqueId().equals(next)) + if (player.getUniqueId().equals(next)) continue; final Player idPlayer = Bukkit.getPlayer(next); @@ -143,14 +149,14 @@ private void onInventoryInteract(InventoryInteractEvent e) { if (open.getType() != InventoryType.WORKBENCH) { // Close Inventory if player managed to access the workbench without actually use one. iterator.remove(); - p.closeInventory(); + player.closeInventory(); continue; } Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> { open.setContents(pInv.getContents()); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> { - p.updateInventory(); + player.updateInventory(); idPlayer.updateInventory(); }, 1); }, 1); @@ -158,7 +164,8 @@ private void onInventoryInteract(InventoryInteractEvent e) { } } - @EventHandler + @SuppressWarnings("unchecked") + @EventHandler private void onInventoryClose(InventoryCloseEvent e) { if (!(e.getPlayer() instanceof Player)) return; @@ -178,7 +185,7 @@ private void onInventoryClose(InventoryCloseEvent e) { return; } - List list = (workbench.getMetadata("shared_players").get(0).value() instanceof List) ? (List) workbench.getMetadata("shared_players").get(0).value() : new ArrayList(); + List list = (workbench.getMetadata("shared_players").getFirst().value() instanceof List) ? (List) workbench.getMetadata("shared_players").getFirst().value() : new ArrayList(); assert list != null; list.remove(p.getUniqueId()); @@ -192,17 +199,18 @@ private void onInventoryClose(InventoryCloseEvent e) { } } - @EventHandler + @SuppressWarnings("unchecked") + @EventHandler private void onPlayerQuit(PlayerQuitEvent e) { final Player p = e.getPlayer(); if (!p.hasMetadata("shared_workbench")) return; - Block workbench = (p.getMetadata("shared_workbench").get(0).value() instanceof Block) ? (Block) p.getMetadata("shared_workbench").get(0).value() : null; + Block workbench = (p.getMetadata("shared_workbench").getFirst().value() instanceof Block) ? (Block) p.getMetadata("shared_workbench").getFirst().value() : null; if (workbench != null && workbench.hasMetadata("shared_players") && workbench.getType() == Material.CRAFTING_TABLE) { - List list = (workbench.getMetadata("shared_players").get(0).value() instanceof List) ? (List) workbench.getMetadata("shared_players").get(0).value() : new ArrayList(); + List list = (workbench.getMetadata("shared_players").getFirst().value() instanceof List) ? (List) workbench.getMetadata("shared_players").getFirst().value() : new ArrayList(); assert list != null; list.remove(p.getUniqueId()); @@ -216,7 +224,8 @@ private void onPlayerQuit(PlayerQuitEvent e) { p.removeMetadata("shared_workbench", plugin); } - @EventHandler(priority = EventPriority.HIGHEST) + @SuppressWarnings("unchecked") + @EventHandler(priority = EventPriority.HIGHEST) private void onBreakWorkbench(BlockBreakEvent e) { if (e.isCancelled()) return; if (e.getPlayer().getGameMode() == GameMode.CREATIVE) return; @@ -225,7 +234,7 @@ private void onBreakWorkbench(BlockBreakEvent e) { if (!workbench.hasMetadata("shared_players") || workbench.getType() != Material.CRAFTING_TABLE) return; - List list = (workbench.getMetadata("shared_players").get(0).value() instanceof List) ? (List) workbench.getMetadata("shared_players").get(0).value() : new ArrayList(); + List list = (workbench.getMetadata("shared_players").getFirst().value() instanceof List) ? (List) workbench.getMetadata("shared_players").getFirst().value() : new ArrayList(); assert list != null; Iterator iterator = list.iterator(); @@ -263,4 +272,4 @@ private void onBreakWorkbench(BlockBreakEvent e) { workbench.removeMetadata("shared_players", plugin); } -} \ No newline at end of file +} diff --git a/src/main/java/tk/shanebee/survival/listeners/entity/BeeKeeperSuit.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/BeeKeeperSuit.java similarity index 65% rename from src/main/java/tk/shanebee/survival/listeners/entity/BeeKeeperSuit.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/BeeKeeperSuit.java index 28b5929..eea0a86 100644 --- a/src/main/java/tk/shanebee/survival/listeners/entity/BeeKeeperSuit.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/BeeKeeperSuit.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.entity; +package com.shanebeestudios.survival.plugin.listeners.entity; import org.bukkit.entity.Bee; import org.bukkit.entity.Entity; @@ -12,9 +12,8 @@ import org.bukkit.event.entity.EntityTargetLivingEntityEvent; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffectType; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.Utils; public class BeeKeeperSuit implements Listener { @@ -22,9 +21,8 @@ public class BeeKeeperSuit implements Listener { private void onSting(EntityDamageByEntityEvent event) { Entity entity = event.getEntity(); Entity damager = event.getDamager(); - if (entity instanceof Player && damager instanceof Bee && !Utils.isCitizensNPC(entity)) { - if (hasBeekeeperSuit((Player) entity)) { - Bee bee = (Bee) damager; + if (entity instanceof Player player && damager instanceof Bee bee && !Utils.isCitizensNPC(player)) { + if (hasBeekeeperSuit(player)) { event.setCancelled(true); bee.setTarget(null); bee.setAnger(0); @@ -35,11 +33,11 @@ private void onSting(EntityDamageByEntityEvent event) { @EventHandler private void onPoison(EntityPotionEffectEvent event) { Entity entity = event.getEntity(); - if (entity instanceof Player && !Utils.isCitizensNPC(entity)) { + if (entity instanceof Player player && !Utils.isCitizensNPC(player)) { if (event.getCause() != Cause.ATTACK) return; if (event.getModifiedType() != PotionEffectType.POISON) return; if (event.getAction() != Action.ADDED) return; - if (hasBeekeeperSuit((Player) entity)) { + if (hasBeekeeperSuit(player)) { event.setCancelled(true); } } @@ -49,8 +47,8 @@ private void onPoison(EntityPotionEffectEvent event) { private void onTarget(EntityTargetLivingEntityEvent event) { Entity target = event.getTarget(); Entity entity = event.getEntity(); - if (target instanceof Player && entity instanceof Bee && !Utils.isCitizensNPC(target)) { - if (hasBeekeeperSuit((Player) target)) { + if (target instanceof Player player && entity instanceof Bee && !Utils.isCitizensNPC(player)) { + if (hasBeekeeperSuit(player)) { event.setCancelled(true); } } @@ -61,8 +59,10 @@ private boolean hasBeekeeperSuit(Player player) { if (inv.getHelmet() == null || inv.getChestplate() == null || inv.getLeggings() == null || inv.getBoots() == null) { return false; } - return ItemManager.compare(inv.getHelmet(), Item.BEEKEEPER_HELMET) && ItemManager.compare(inv.getChestplate(), Item.BEEKEEPER_CHESTPLATE) && - ItemManager.compare(inv.getLeggings(), Item.BEEKEEPER_LEGGINGS) && ItemManager.compare(inv.getBoots(), Item.BEEKEEPER_BOOTS); - } + return Items.BEEKEEPER_HELMET.is(inv.getHelmet()) && + Items.BEEKEEPER_CHESTPLATE.is(inv.getChestplate()) && + Items.BEEKEEPER_LEGGINGS.is(inv.getLeggings()) && + Items.BEEKEEPER_BOOTS.is(inv.getBoots()); + } } diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/ChestPigmen.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/ChestPigmen.java new file mode 100644 index 0000000..1c10705 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/ChestPigmen.java @@ -0,0 +1,95 @@ +package com.shanebeestudios.survival.plugin.listeners.entity; + +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.block.Chest; +import org.bukkit.entity.Mob; +import org.bukkit.entity.PigZombie; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; + +import java.util.ArrayList; +import java.util.List; + +public class ChestPigmen implements Listener { + + private final List goldItems; + private final int radius; + private final NamespacedKey key = NamespacedKey.fromString("survival_plus:chest_pigmen"); + private final AttributeModifier mod; + + + public ChestPigmen(SurvivalPlugin plugin) { + this.goldItems = new ArrayList<>(); + for (Material material : Registry.MATERIAL) { + if (material.isItem() && material.getKey().toString().contains("gold")) { + this.goldItems.add(material); + } + } + this.radius = plugin.getSurvivalConfig().entity_mechanics_pigmen_chest_radius; + double speedModifier = plugin.getSurvivalConfig().entity_mechanics_pigmen_chest_speed; + assert this.key != null; + this.mod = speedModifier > 0 ? new AttributeModifier(this.key, speedModifier, Operation.ADD_SCALAR) : null; + + } + + @EventHandler + private void onOpenChest(PlayerInteractEvent event) { + Player player = event.getPlayer(); + //if (player.getWorld().getEnvironment() != World.Environment.NETHER) return; + if (event.getClickedBlock() == null) return; + if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock().getType() != Material.CHEST) + return; + Chest chest = ((Chest) event.getClickedBlock().getState()); + if (chestContainsGold(chest)) { + player.getNearbyEntities(this.radius, this.radius, this.radius).forEach(entity -> { + if (entity instanceof PigZombie pigZombie) { + pigZombie.setTarget(player); + moveFaster(pigZombie); + } + }); + } + } + + private boolean chestContainsGold(Chest block) { + for (ItemStack item : block.getInventory().getContents()) { + if (item == null) continue; + if (this.goldItems.contains(item.getType())) return true; + } + return false; + } + + @SuppressWarnings("DataFlowIssue") + private void moveFaster(Mob mob) { + if (this.mod == null) return; + + AttributeInstance attribute = mob.getAttribute(Attribute.MOVEMENT_SPEED); + if (attribute != null && attribute.getModifier(this.key.key()) == null) { + attribute.addTransientModifier(this.mod); + } + } + + @SuppressWarnings("DataFlowIssue") + @EventHandler + private void onStopTarget(EntityTargetEvent event) { + // Remove speed when they stop targeting the player + if (event.getEntity() instanceof PigZombie pigZombie && event.getTarget() == null) { + AttributeInstance attribute = pigZombie.getAttribute(Attribute.MOVEMENT_SPEED); + if (attribute != null && attribute.getModifier(this.key.key()) != null) { + attribute.removeModifier(this.mod); + } + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/ChickenSpawn.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/ChickenSpawn.java new file mode 100644 index 0000000..4212b29 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/ChickenSpawn.java @@ -0,0 +1,65 @@ +package com.shanebeestudios.survival.plugin.listeners.entity; + +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.entity.Chicken; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.bukkit.event.player.PlayerEggThrowEvent; +import org.bukkit.inventory.ItemStack; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.item.Items; + +import java.util.Random; + +public class ChickenSpawn implements Listener { + + private final Config config; + private final Random random = new Random(); + + public ChickenSpawn(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + } + + @EventHandler + private void onChickenSpawn(CreatureSpawnEvent event) { + if (event.getEntity() instanceof Chicken chicken) { + SpawnReason reason = event.getSpawnReason(); + if (reason == SpawnReason.BREEDING) { + event.setCancelled(true); + Location loc = event.getLocation(); + World world = loc.getWorld(); + assert world != null; + world.dropItem(loc, getEgg()); + world.playSound(loc, Sound.ENTITY_CHICKEN_EGG, 1.0F, this.random.nextFloat() * 0.4F + 0.8F); + } else if (reason == SpawnReason.EGG) { + int babyTicks = this.config.entity_mechanics_chicken_breeding_baby_ticks; + if (this.config.entity_mechanics_chicken_breeding_always_baby) { + chicken.setBaby(); + chicken.setAge(-babyTicks); + } else if (!chicken.isAdult()) { + chicken.setAge(-babyTicks); + } + } + } + } + + @EventHandler + private void onEggThrown(PlayerEggThrowEvent event) { + if (Items.BREEDING_EGG.is(event.getEgg().getItem())) { + event.setHatching(true); + event.setNumHatches((byte) 1); + } + } + + private ItemStack getEgg() { + int maxEggs = this.config.entity_mechanics_chicken_breeding_max_eggs; + int ran = maxEggs > 1 ? this.random.nextInt(maxEggs) + 1 : 1; + return Items.BREEDING_EGG.getItemStack(ran); + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/entity/EntityDeath.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/EntityDeath.java similarity index 65% rename from src/main/java/tk/shanebee/survival/listeners/entity/EntityDeath.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/EntityDeath.java index 34beed6..1efdc6d 100644 --- a/src/main/java/tk/shanebee/survival/listeners/entity/EntityDeath.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/EntityDeath.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.entity; +package com.shanebeestudios.survival.plugin.listeners.entity; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; @@ -7,9 +7,9 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.item.Item; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.item.Items; import java.util.List; import java.util.Random; @@ -17,21 +17,19 @@ public class EntityDeath implements Listener { private final Config config; - private final int SUSPICIOUS_MEAT_CHANCE; - public EntityDeath(Survival plugin) { + public EntityDeath(SurvivalPlugin plugin) { this.config = plugin.getSurvivalConfig(); - this.SUSPICIOUS_MEAT_CHANCE = Math.max(0, this.config.ENTITY_MECHANICS_SUSPICIOUS_MEAT_CHANCE); } @EventHandler private void onEntityDeath(EntityDeathEvent event) { - if (!this.config.ENTITY_MECHANICS_SUSPICIOUS_MEAT_ENABLED) return; // May need to move if we add more items to drop in the future + if (!this.config.entity_mechanics_suspicious_meat_enabled) return; // May need to move if we add more items to drop in the future LivingEntity entity = event.getEntity(); Player killer = entity.getKiller(); if (killer != null) { int random = new Random().nextInt(100) + 1; - if (random > this.SUSPICIOUS_MEAT_CHANCE) return; + if (random > this.config.entity_mechanics_suspicious_meat_chance) return; switch (entity.getType()) { case ZOMBIE: case DROWNED: @@ -45,7 +43,7 @@ private void onEntityDeath(EntityDeathEvent event) { private void replaceDrops(List items) { items.removeIf(item -> item.getType() == Material.ROTTEN_FLESH); - items.add(Item.SUSPICIOUS_MEAT.getItem()); + items.add(Items.SUSPICIOUS_MEAT.getItemStack()); } } diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/LivingSlime.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/LivingSlime.java new file mode 100644 index 0000000..90c8f0a --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/LivingSlime.java @@ -0,0 +1,80 @@ +package com.shanebeestudios.survival.plugin.listeners.entity; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.block.Block; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Item; +import org.bukkit.entity.Slime; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.ItemSpawnEvent; +import org.bukkit.inventory.ItemStack; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class LivingSlime implements Listener { + + private final SurvivalPlugin plugin; + + public LivingSlime(SurvivalPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + private void onGhastTearSlimeBlock(ItemSpawnEvent e) { + if (e.getEntityType() == EntityType.ITEM) { + Item itemEntity = e.getEntity(); + if (itemEntity.getItemStack().getType() == Material.GHAST_TEAR) { + Bukkit.getScheduler().runTaskLater(this.plugin, initRunnable(itemEntity), 20); + } + } + } + + private Runnable initRunnable(Item itemEntity) { + return () -> { + List slimeBlocks = new ArrayList<>(); + slimeBlocks.add(itemEntity.getLocation().add(0, -1, 0).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(0, -1, 1).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(0, -1, -1).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(1, -1, 0).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(-1, -1, 0).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(0, 0, 1).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(0, 0, -1).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(1, 0, 0).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(-1, 0, 0).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(1, 0, 1).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(1, 0, -1).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(-1, 0, 1).getBlock()); + slimeBlocks.add(itemEntity.getLocation().add(-1, 0, -1).getBlock()); + + ItemStack itemStack = itemEntity.getItemStack(); + Iterator blockIterator = slimeBlocks.iterator(); + Block slimeBlock; + while (blockIterator.hasNext()) { + slimeBlock = blockIterator.next(); + if (slimeBlock != null && slimeBlock.getType() == Material.SLIME_BLOCK && itemEntity.isOnGround()) { + if (itemStack.getAmount() > 1) + itemStack.setAmount(itemStack.getAmount() - 1); + + if (itemStack.getAmount() <= 0) + itemEntity.remove(); + + slimeBlock.setType(Material.AIR); + + Slime slime = itemEntity.getWorld().spawn(slimeBlock.getLocation(), Slime.class); + slime.setSize(2); + + Utils.spawnParticle(slimeBlock.getLocation().add(0.5, 0.5, 0.5), Particle.CLOUD, 20, 0.5, 0.5, 0.5); + break; + } + } + }; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/MerchantTrades.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/MerchantTrades.java new file mode 100644 index 0000000..32199c0 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/MerchantTrades.java @@ -0,0 +1,27 @@ +package com.shanebeestudios.survival.plugin.listeners.entity; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.managers.LootManager; +import org.bukkit.entity.Entity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.inventory.Merchant; + +public class MerchantTrades implements Listener { + + private final LootManager lootManager; + + public MerchantTrades(SurvivalPlugin plugin) { + this.lootManager = plugin.getLootManager(); + } + + @EventHandler + private void onClickVillager(PlayerInteractEntityEvent event) { + Entity entity = event.getRightClicked(); + if (entity instanceof Merchant merchant) { + this.lootManager.updateMerchant(merchant); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/MobGoalListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/MobGoalListener.java new file mode 100644 index 0000000..0753a50 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/MobGoalListener.java @@ -0,0 +1,45 @@ +package com.shanebeestudios.survival.plugin.listeners.entity; + +import com.destroystokyo.paper.entity.ai.MobGoals; +import com.destroystokyo.paper.event.entity.EntityAddToWorldEvent; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.goals.AngryWolfGoal; +import com.shanebeestudios.survival.api.goals.AvoidPlayerGoal; +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Wolf; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class MobGoalListener implements Listener { + + private final Config config; + private final MobGoals mobGoals; + + public MobGoalListener(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + this.mobGoals = Bukkit.getMobGoals(); + } + + @EventHandler + private void onEntityJoinWorld(EntityAddToWorldEvent event) { + Entity entity = event.getEntity(); + + if (entity instanceof Mob mob && this.config.entity_mechanics_mobs_avoid_players.contains(entity.getType())) { + avoidPlayers(mob); + } else if (entity instanceof Wolf wolf && this.config.entity_mechanics_angry_wolves != AngryWolfGoal.Type.DISABLED) { + angryWolves(wolf); + } + } + + private void avoidPlayers(Mob mob) { + this.mobGoals.addGoal(mob, 0, new AvoidPlayerGoal(mob)); + } + + private void angryWolves(Wolf wolf) { + this.mobGoals.addGoal(wolf, 0, new AngryWolfGoal(wolf, this.config.entity_mechanics_angry_wolves)); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/PiglinBarter.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/PiglinBarter.java new file mode 100644 index 0000000..8eb7078 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/entity/PiglinBarter.java @@ -0,0 +1,77 @@ +package com.shanebeestudios.survival.plugin.listeners.entity; + +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDropItemEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionType; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.item.Items; + +import java.util.Random; + +public class PiglinBarter implements Listener { + + private final Config config; + private final Random random = new Random(); + + public PiglinBarter(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + } + + @EventHandler + private void onPiglinDrop(EntityDropItemEvent event) { + if (event.getEntityType() != EntityType.PIGLIN) return; + + org.bukkit.entity.Item itemDrop = event.getItemDrop(); + ItemStack itemDropStack = itemDrop.getItemStack(); + Material itemDropMaterial = itemDropStack.getType(); + + // If water bottle is dropped, let's change it + if (itemDropMaterial == Material.POTION && this.config.mechanics_thirst_enabled && this.config.entity_mechanics_piglin_drop_water) { + PotionMeta meta = ((PotionMeta) itemDropStack.getItemMeta()); + assert meta != null; + if (meta.getBasePotionType() == PotionType.WATER) { + if (this.random.nextFloat() < 0.25f) { + itemDrop.setItemStack(Items.PURIFIED_WATER.getItemStack()); + } else { + itemDrop.setItemStack(Items.CLEAN_WATER.getItemStack()); + } + return; + } + } + + // If alt drops are disabled let's get out of here + if (!this.config.entity_mechanics_piglin_alt_drop) return; + + // If slow armor is enabled let's always drop custom iron boots + if (itemDropMaterial == Material.IRON_BOOTS && this.config.mechanics_slow_armor) { + ItemStack boots = Items.IRON_BOOTS.getItemStack(); + boots.addEnchantment(Enchantment.SOUL_SPEED, this.random.nextInt(3) + 1); + itemDrop.setItemStack(boots); + return; + } + + // If anything else we have some random drops + + if (this.random.nextFloat() > 0.5f) { + ItemStack altItem = switch (itemDropMaterial) { + case LEATHER -> Items.SUSPICIOUS_MEAT.getItemStack(); + case NETHER_BRICK -> Items.COFFEE_BEAN.getItemStack(this.random.nextInt(4) + 1); + case GRAVEL -> Items.FIRESTRIKER.getItemStack(); + case SOUL_SAND -> Items.CAMPFIRE.getItemStack(); + case POTION -> Items.MEDIC_KIT.getItemStack(); + case SPLASH_POTION -> Items.GRAPPLING_HOOK.getItemStack(); + case ENCHANTED_BOOK -> Items.RECURVED_CROSSBOW.getItemStack(); + default -> null; + }; + if (altItem != null) itemDrop.setItemStack(altItem); + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/BeetrootStrength.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/BeetrootStrength.java similarity index 80% rename from src/main/java/tk/shanebee/survival/listeners/item/BeetrootStrength.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/BeetrootStrength.java index 6d4fc25..cea9843 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/BeetrootStrength.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/BeetrootStrength.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -19,13 +19,13 @@ private void onConsume(PlayerItemConsumeEvent event) { int amp = 0; int dur = 200; for (PotionEffect effect : player.getActivePotionEffects()) { - if (effect.getType().equals(PotionEffectType.INCREASE_DAMAGE)) { + if (effect.getType().equals(PotionEffectType.STRENGTH)) { dur += effect.getDuration(); if (dur > 600) dur = 600; player.removePotionEffect(effect.getType()); } } - player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, dur, amp)); + player.addPotionEffect(new PotionEffect(PotionEffectType.STRENGTH, dur, amp)); } } diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/BowListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/BowListener.java new file mode 100644 index 0000000..bbe949a --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/BowListener.java @@ -0,0 +1,67 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.managers.MessageManager; +import com.shanebeestudios.survival.plugin.managers.MessageManager.MessageType; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityShootBowEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.CrossbowMeta; + +public class BowListener implements Listener { + + private final MessageManager messageManager; + + public BowListener(SurvivalPlugin plugin) { + this.messageManager = plugin.getMessageManager(); + } + + @EventHandler + private void onShootWithoutArrows(EntityShootBowEvent event) { + if (event.getEntity() instanceof Player player) { + ItemStack mainHand = player.getInventory().getItemInMainHand(); + if (event.getBow() != null && mainHand.getType() == event.getBow().getType()) { + if (SurvivalPlugin.getInstance().getPlayerManager().isArrowOffHand(player)) { + event.setCancelled(false); + } else { + if (mainHand.getType() != Material.CROSSBOW) { + event.setCancelled(true); + this.messageManager.sendMessage(player, MessageType.ARROWS_OFFHAND); + player.updateInventory(); + } + } + } else { + event.setCancelled(true); + this.messageManager.sendMessage(player, MessageType.BOW_MAIN_HAND); + player.updateInventory(); + } + } + } + + @EventHandler + private void onLoadCrossbow(PlayerInteractEvent event) { + Player player = event.getPlayer(); + ItemStack mainHand = player.getInventory().getItemInMainHand(); + ItemStack offHand = player.getInventory().getItemInOffHand(); + if (mainHand.getType() == Material.CROSSBOW && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { + if (event.getHand() == EquipmentSlot.OFF_HAND) return; + if (mainHand.getItemMeta() != null && ((CrossbowMeta) mainHand.getItemMeta()).hasChargedProjectiles()) + return; + if (!SurvivalPlugin.getInstance().getPlayerManager().isArrowOffHand(player)) { + event.setCancelled(true); + this.messageManager.sendMessage(player, MessageType.ARROWS_OFFHAND_CROSSBOW); + } + } else if (offHand.getType() == Material.CROSSBOW) { + if (event.getHand() == EquipmentSlot.HAND) return; + event.setCancelled(true); + this.messageManager.sendMessage(player, MessageType.BOW_MAIN_HAND); + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/CompassWaypoint.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/CompassWaypoint.java similarity index 51% rename from src/main/java/tk/shanebee/survival/listeners/item/CompassWaypoint.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/CompassWaypoint.java index 348af93..01df51e 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/CompassWaypoint.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/CompassWaypoint.java @@ -1,8 +1,9 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Tag; +import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -11,18 +12,19 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import com.shanebeestudios.survival.api.registry.BlockTags; +import com.shanebeestudios.survival.api.util.Utils; public class CompassWaypoint implements Listener { private final Lang lang; private final PlayerManager playerManager; - public CompassWaypoint(Survival plugin) { + public CompassWaypoint(SurvivalPlugin plugin) { this.lang = plugin.getLang(); this.playerManager = plugin.getPlayerManager(); } @@ -40,10 +42,11 @@ private void onItemClick(PlayerInteractEvent event) { else if (offItem.getType() == Material.COMPASS && event.getHand() == EquipmentSlot.HAND) return; if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { + Block clickedBlock = event.getClickedBlock(); if (!player.isSneaking()) return; // To prevent accidentally resetting waypoint, player needs to sneak - assert event.getClickedBlock() != null; - switch (event.getClickedBlock().getType()) { + assert clickedBlock != null; + switch (clickedBlock.getType()) { case HOPPER: case CRAFTING_TABLE: case DROPPER: @@ -51,22 +54,29 @@ private void onItemClick(PlayerInteractEvent event) { return; default: } - if (Tag.BEDS.isTagged(event.getClickedBlock().getType())) return; - if (Utils.isWoodGate(event.getClickedBlock().getType())) return; - if (Tag.DOORS.isTagged(event.getClickedBlock().getType())) return; - if (Utils.isCookingBlock(event.getClickedBlock().getType())) return; - if (Utils.isStorageBlock(event.getClickedBlock().getType())) return; - if (Utils.isUtilityBlock(event.getClickedBlock().getType())) return; + if (Tag.BEDS.isTagged(clickedBlock.getType())) return; + if (Tag.FENCE_GATES.isTagged(clickedBlock.getType())) return; + if (Tag.DOORS.isTagged(clickedBlock.getType())) return; + if (BlockTags.COOKING_BLOCK.isTagged(clickedBlock.getType())) return; + if (BlockTags.STORAGE_BLOCK.isTagged(clickedBlock.getType())) return; + if (BlockTags.UTILITY_BLOCK.isTagged(clickedBlock.getType())) return; - Location loc = event.getClickedBlock().getRelative(event.getBlockFace()).getLocation(); - player.sendMessage(Utils.getColoredString("&d" + lang.compass_pointed + locToString(loc))); + Location loc = clickedBlock.getRelative(event.getBlockFace()).getLocation(); + Utils.sendColoredMini(player, lang.compass_waypoint_set, locToString(loc)); loc.add(0.5, 0.5, 0.5); - playerManager.setWaypoint(player, loc, true); + this.playerManager.setWaypoint(player, loc, true); } if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) { - Location loc = player.getLocation().getBlock().getLocation(); - player.sendMessage(Utils.getColoredString("&d" + lang.compass_coords + locToString(loc))); + PlayerData playerData = this.playerManager.getPlayerData(player); + Location waypoint = playerData.getCompassWaypoint(player.getWorld()); + if (waypoint != null) { + int distance = (int) player.getLocation().distance(waypoint); + String s = locToString(waypoint); + Utils.sendColoredMini(player, lang.compass_waypoint_get, distance, s); + } else { + Utils.sendColoredMini(player, lang.compass_waypoint_unset); + } } } } @@ -76,7 +86,10 @@ private void onItemClick(PlayerInteractEvent event) { private void onWorldChange(PlayerChangedWorldEvent event) { Player player = event.getPlayer(); PlayerData playerData = this.playerManager.getPlayerData(player); - player.setCompassTarget(playerData.getCompassWaypoint(player.getWorld())); + Location waypoint = playerData.getCompassWaypoint(player.getWorld()); + if (waypoint != null) { + player.setCompassTarget(waypoint); + } } private String locToString(Location loc) { diff --git a/src/main/java/tk/shanebee/survival/listeners/item/CookieHealthBoost.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/CookieHealthBoost.java similarity index 95% rename from src/main/java/tk/shanebee/survival/listeners/item/CookieHealthBoost.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/CookieHealthBoost.java index 19c7e4f..a2f54c3 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/CookieHealthBoost.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/CookieHealthBoost.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/DrinkableItemListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/DrinkableItemListener.java new file mode 100644 index 0000000..6cfe200 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/DrinkableItemListener.java @@ -0,0 +1,81 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.item.items.drinks.DrinkItem; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.Bukkit; +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.PlayerItemConsumeEvent; +import org.bukkit.inventory.ItemStack; + +public class DrinkableItemListener implements Listener { + + private final SurvivalPlugin plugin; + private final Config config; + private final PlayerManager playerManager; + + public DrinkableItemListener(SurvivalPlugin plugin) { + this.plugin = plugin; + this.config = plugin.getSurvivalConfig(); + this.playerManager = plugin.getPlayerManager(); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onConsume(PlayerItemConsumeEvent event) { + final Player player = event.getPlayer(); + + PlayerData playerData = playerManager.getPlayerData(player); + ItemStack itemStack = event.getItem(); + double change = 0; + Item item = Items.getFromStack(itemStack); + if (item instanceof DrinkItem drinkItem) { + change = drinkItem.getThirstLevel(); + } else { + switch (event.getItem().getType()) { + case APPLE: + change = this.config.mechanics_thirst_rep_apple; + break; + case BEETROOT_SOUP: + change = this.config.mechanics_thirst_rep_beetroot_soup; + break; + case POTION: + if (this.config.mechanics_thirst_purify_water) { + change = this.config.mechanics_thirst_rep_other_water; + } else { + change = this.config.mechanics_thirst_rep_water; + } + break; + case MILK_BUCKET: + change = this.config.mechanics_thirst_rep_milk_bucket; + break; + case MELON_SLICE: + change = this.config.mechanics_thirst_rep_melon_slice; + break; + case MUSHROOM_STEW: + change = this.config.mechanics_thirst_rep_mush_stew; + break; + case HONEY_BOTTLE: + change = this.config.mechanics_thirst_rep_honey_bottle; + break; + } + } + if (change <= 0) return; + + playerData.increaseThirst(change); + + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { + if (!this.config.mechanics_status_scoreboard) { + player.sendMessage(this.plugin.getPlayerManager().getHungerVisual(player).get(1) + this.plugin.getPlayerManager().getHungerVisual(player).get(2) + " " + plugin.getPlayerManager().getHungerVisual(player).get(0).toUpperCase()); + player.sendMessage(this.plugin.getPlayerManager().getThirstVisual(player).get(1) + this.plugin.getPlayerManager().getThirstVisual(player).get(2) + " " + plugin.getPlayerManager().getThirstVisual(player).get(0).toUpperCase()); + } + }, 1L); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/DualWieldListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/DualWieldListener.java new file mode 100644 index 0000000..22817e0 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/DualWieldListener.java @@ -0,0 +1,103 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.data.Stat; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.registry.ItemTags; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.managers.MessageManager; +import com.shanebeestudios.survival.plugin.managers.MessageManager.MessageType; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import io.papermc.paper.event.player.PlayerInventorySlotChangeEvent; +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.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerItemHeldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.jetbrains.annotations.Nullable; + +public class DualWieldListener implements Listener { + + private final PlayerManager playerManager; + private final MessageManager messageManager; + + public DualWieldListener(SurvivalPlugin plugin) { + this.playerManager = plugin.getPlayerManager(); + this.messageManager = plugin.getMessageManager(); + } + + @EventHandler + private void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + PlayerInventory inventory = player.getInventory(); + checkDuelWield(player, inventory.getItemInMainHand(), inventory.getItemInOffHand()); + } + + @EventHandler + private void onPlayerInvSlotChange(PlayerInventorySlotChangeEvent event) { + int slot = event.getSlot(); + Player player = event.getPlayer(); + PlayerInventory inventory = player.getInventory(); + if (slot == player.getInventory().getHeldItemSlot()) { + checkDuelWield(player, event.getNewItemStack(), inventory.getItemInOffHand()); + } else if (slot == 40) { + checkDuelWield(player, inventory.getItemInMainHand(), event.getNewItemStack()); + } + } + + @EventHandler + private void onPlayerSwapHandItem(PlayerSwapHandItemsEvent event) { + checkDuelWield(event.getPlayer(), event.getMainHandItem(), event.getOffHandItem()); + } + + @EventHandler + private void onPlayerChangeHand(PlayerItemHeldEvent event) { + Player player = event.getPlayer(); + PlayerInventory inventory = player.getInventory(); + checkDuelWield(player, inventory.getItem(event.getNewSlot()), inventory.getItemInOffHand()); + } + + // Prevent dual wielding + @EventHandler(priority = EventPriority.LOWEST) + private void onPlayerDamageEntity(EntityDamageByEntityEvent event) { + if (event.getDamager() instanceof Player player) { + PlayerData playerData = this.playerManager.getPlayerData(player); + if (playerData.getStat(Stat.DUAL_WIELD) > 0) { + event.setCancelled(true); + PlayerInventory inventory = player.getInventory(); + Item main = Items.getFromStack(inventory.getItemInMainHand()); + Item off = Items.getFromStack(inventory.getItemInOffHand()); + String name = "this item"; + if (main != null) { + name = main.getName(); + } else if (off != null) { + name = off.getName(); + } + this.messageManager.sendMessage(player, MessageType.DUAL_WIELD_NO, name); + } + } + } + + private void checkDuelWield(Player player, @Nullable ItemStack mainStack, @Nullable ItemStack offStack) { + Item mainItem = mainStack != null ? Items.getFromStack(mainStack) : null; + Item offItem = offStack != null ? Items.getFromStack(offStack) : null; + + int duelWield = 0; + if (mainItem != null && mainItem.isPreventDuelWield() && + offStack != null && ItemTags.PREVENT_DUAL_WIELD.isTagged(offStack.getType())) { + duelWield = 1; + } else if (offItem != null && offItem.isPreventDuelWield() && + mainStack != null && ItemTags.PREVENT_DUAL_WIELD.isTagged(mainStack.getType())) { + duelWield = 1; + } + PlayerData playerData = this.playerManager.getPlayerData(player); + playerData.setStat(Stat.DUAL_WIELD, duelWield); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/FirestrikerListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/FirestrikerListener.java new file mode 100644 index 0000000..a01d9b2 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/FirestrikerListener.java @@ -0,0 +1,169 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.Tag; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.block.data.Lightable; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.LivingEntity; +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.BlockIgniteEvent; +import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.gui.FireStrikerGUI; +import com.shanebeestudios.survival.api.item.Items; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +public class FirestrikerListener implements Listener { + + private final Map firestrikerViewMap = new HashMap<>(); + private final Random random = new Random(); + + @SuppressWarnings("unused") + public FirestrikerListener(SurvivalPlugin plugin) { + } + + @EventHandler + private void onItemClick(PlayerInteractEvent event) { + if (event.hasItem()) { + Player player = event.getPlayer(); + ItemStack tool = event.getItem(); + Action action = event.getAction(); + EquipmentSlot hand = event.getHand(); + if (tool == null || hand == null) return; + + if (Items.FIRESTRIKER.is(tool)) { + if (player.isSneaking() && (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK)) { + event.setCancelled(true); + FireStrikerGUI fireStriker = FireStrikerGUI.create(player, tool.clone()); + if (fireStriker != null) { + player.getLocation().getWorld().playSound(player.getLocation(), Sound.ITEM_AXE_WAX_OFF, 5.0F, this.random.nextFloat() * 0.4F + 0.8F); + this.firestrikerViewMap.put(fireStriker.getFurnaceView(), fireStriker); + fireStriker.open(); + tool.setAmount(0); + player.updateInventory(); + } else { + tool.setAmount(0); + player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 5.0F, this.random.nextFloat() * 0.4F + 0.8F); + } + } else if (action == Action.RIGHT_CLICK_BLOCK) { + Block clickedBlock = event.getClickedBlock(); + if (clickedBlock == null) return; + + Material blockType = clickedBlock.getType(); + switch (blockType) { + case ENCHANTING_TABLE: + case ANVIL: + case BREWING_STAND: + case TRAPPED_CHEST: + case CHEST: + case NOTE_BLOCK: + case FURNACE: + case HOPPER: + case CRAFTING_TABLE: + case DROPPER: + case DISPENSER: + case REDSTONE_WALL_TORCH: + case REDSTONE_TORCH: + return; + } + if (Tag.BEDS.isTagged(blockType)) return; + if (Tag.FENCE_GATES.isTagged(blockType)) return; + if (Tag.DOORS.isTagged(blockType)) return; + if (Tag.TRAPDOORS.isTagged(blockType)) return; + if (blockType == Material.CAMPFIRE || blockType == Material.SOUL_CAMPFIRE) { + Lightable campfire = ((Lightable) clickedBlock.getBlockData()); + if (!campfire.isLit()) { + player.swingHand(hand); + campfire.setLit(true); + clickedBlock.setBlockData(campfire); + damageItem(player, tool); + } + return; + } + Location loc = clickedBlock.getRelative(event.getBlockFace()).getLocation(); + if (ignite(player, loc)) { + player.swingHand(hand); + damageItem(player, tool); + } + } + } + } + } + + private boolean ignite(Player igniter, Location loc) { + Random rand = new Random(); + + loc.add(0.5, 0.5, 0.5); + + BlockIgniteEvent igniteEvent = new BlockIgniteEvent(loc.getBlock(), IgniteCause.FLINT_AND_STEEL, igniter); + if (!igniteEvent.callEvent()) { + return false; + } + + BlockState blockState = loc.getBlock().getState(); + + BlockPlaceEvent placeEvent = new BlockPlaceEvent(loc.getBlock(), + blockState, loc.getBlock(), igniter.getInventory().getItemInMainHand(), igniter, true, EquipmentSlot.HAND); + Bukkit.getServer().getPluginManager().callEvent(placeEvent); + + if (placeEvent.isCancelled() || !placeEvent.canBuild()) { + placeEvent.getBlockPlaced().getState().setType(Material.AIR); + return false; + } + + + loc.getWorld().playSound(loc, Sound.ITEM_FLINTANDSTEEL_USE, 1.0F, rand.nextFloat() * 0.4F + 0.8F); + loc.getBlock().setType(Material.FIRE); + + return true; + } + + private void damageItem(Player player, ItemStack itemStack) { + if (player.damageItemStack(itemStack, 1).isEmpty()) { + player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 5.0F, this.random.nextFloat() * 0.4F + 0.8F); + } + } + + @EventHandler + private void onCloseInventory(InventoryCloseEvent event) { + HumanEntity player = event.getPlayer(); + InventoryView openInventory = player.getOpenInventory(); + FireStrikerGUI fireStrikerGUI = this.firestrikerViewMap.get(openInventory); + if (fireStrikerGUI != null) { + fireStrikerGUI.close(); + this.firestrikerViewMap.remove(openInventory); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + private void onAttack(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getDamager() instanceof Player player && event.getEntity() instanceof LivingEntity && event.getCause() == DamageCause.ENTITY_ATTACK) { + ItemStack itemStack = player.getInventory().getItemInMainHand(); + if (Items.FIRESTRIKER.is(itemStack)) { + player.damageItemStack(itemStack, 1); + } + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/FoodDiversityConsume.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/FoodDiversityConsume.java similarity index 71% rename from src/main/java/tk/shanebee/survival/listeners/item/FoodDiversityConsume.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/FoodDiversityConsume.java index 4816414..72586e3 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/FoodDiversityConsume.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/FoodDiversityConsume.java @@ -1,5 +1,12 @@ -package tk.shanebee.survival.listeners.item; - +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.api.data.Nutrient; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.item.Nutrition; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; @@ -11,30 +18,37 @@ import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityExhaustionEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.data.Nutrient; -import tk.shanebee.survival.item.Nutrition; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.util.Utils; public class FoodDiversityConsume implements Listener { private final PlayerManager playerManager; private final int RESPAWN_PROTEIN, RESPAWN_CARBS, RESPAWN_SALTS; - public FoodDiversityConsume(Survival plugin) { + public FoodDiversityConsume(SurvivalPlugin plugin) { this.playerManager = plugin.getPlayerManager(); Config config = plugin.getSurvivalConfig(); - RESPAWN_PROTEIN = config.MECHANICS_FOOD_RESPAWN_PROTEINS; - RESPAWN_CARBS = config.MECHANICS_FOOD_RESPAWN_CARBS; - RESPAWN_SALTS = config.MECHANICS_FOOD_RESPAWN_SALTS; + RESPAWN_PROTEIN = config.mechanics_food_respawn_proteins; + RESPAWN_CARBS = config.mechanics_food_respawn_carbs; + RESPAWN_SALTS = config.mechanics_food_respawn_vitamins; } + @EventHandler // Decrease nutrients when player does exhaustive tasks + private void onExhausted(EntityExhaustionEvent event) { + Player player = (Player) event.getEntity(); + + float exhaustion = event.getExhaustion(); + if (player.getExhaustion() + exhaustion < 4.0f) return; + + PlayerData playerData = playerManager.getPlayerData(player); + playerData.increaseNutrient(Nutrient.CARBS, -8); + playerData.increaseNutrient(Nutrient.PROTEIN, -2); + playerData.increaseNutrient(Nutrient.VITAMINS, -3); + } + @EventHandler(priority = EventPriority.HIGHEST) private void onConsume(PlayerItemConsumeEvent event) { if (event.isCancelled()) return; @@ -90,14 +104,14 @@ private void addStats(Player player, Nutrient nutrient, int point) { private void addStats(Player player, Nutrition nutrition) { addStats(player, Nutrient.CARBS, nutrition.getCarbs()); addStats(player, Nutrient.PROTEIN, nutrition.getProteins()); - addStats(player, Nutrient.SALTS, nutrition.getVitamins()); + addStats(player, Nutrient.VITAMINS, nutrition.getVitamins()); } private void setStats(Player player, int carbs, int proteins, int vitamins) { PlayerData playerData = playerManager.getPlayerData(player); playerData.setNutrient(Nutrient.CARBS, carbs); playerData.setNutrient(Nutrient.PROTEIN, proteins); - playerData.setNutrient(Nutrient.SALTS, vitamins); + playerData.setNutrient(Nutrient.VITAMINS, vitamins); } private double addMultiplier(Player player) { @@ -118,7 +132,7 @@ private double addMultiplier(Player player) { default: } } - if (playerData.getNutrient(Nutrient.SALTS) <= 100) { + if (playerData.getNutrient(Nutrient.VITAMINS) <= 100) { switch (player.getWorld().getDifficulty()) { case EASY: damageMultiplier *= 1.25; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/GiantBladeListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/GiantBladeListener.java new file mode 100644 index 0000000..606d6d0 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/GiantBladeListener.java @@ -0,0 +1,113 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.api.registry.DamageTypes; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.data.Stat; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.damage.DamageSource; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.Collection; +import java.util.Random; + +public class GiantBladeListener implements Listener { + + private final SurvivalPlugin plugin; + private final Lang lang; + private final PlayerManager playerManager; + private final Random random = new Random(); + + public GiantBladeListener(SurvivalPlugin plugin) { + this.plugin = plugin; + this.lang = plugin.getLang(); + this.playerManager = plugin.getPlayerManager(); + } + + @EventHandler + private void onItemClick(PlayerInteractEvent event) { + Action action = event.getAction(); + if (action != Action.RIGHT_CLICK_BLOCK && action != Action.RIGHT_CLICK_AIR) return; + if (event.getHand() != EquipmentSlot.HAND) return; + + Player player = event.getPlayer(); + ItemStack mainItem = player.getInventory().getItemInMainHand(); + if (!player.isSprinting()) return; + if (player.hasCooldown(mainItem)) return; + + PlayerData playerData = playerManager.getPlayerData(player); + if (playerData.getStat(Stat.DUAL_WIELD) > 0) return; + if (!Items.ENDER_GIANT_BLADE.is(mainItem)) return; + + chargeForward(player, mainItem); + } + + private void chargeForward(Player player, ItemStack itemStack) { + if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) + player.setFoodLevel(player.getFoodLevel() - 1); + + PlayerData playerData = playerManager.getPlayerData(player); + Utils.sendColoredMini(player, "" + this.lang.charge); + + player.setCooldown(itemStack, 200); + playerData.setStat(Stat.CHARGING, 10); + + final Runnable task = new Runnable() { + public void run() { + push(player); + damageNearbyEnemies(player); + effects(player); + + int times = playerData.getStat(Stat.CHARGING); + if (--times > 0) { + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, this, 1L); + } + playerData.setStat(Stat.CHARGING, times); + } + }; + + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, task, 0); + } + + private void push(Player player) { + Location playerLocation = player.getLocation(); + if (playerLocation.getPitch() < 0) playerLocation.setPitch(0); + Vector newVelocity = playerLocation.getDirection().clone().multiply(2); + player.setVelocity(newVelocity); + } + + private void effects(Player player) { + Location location = player.getLocation(); + location.getWorld().playSound(location, Sound.ENTITY_SHULKER_BULLET_HIT, 1.5F, this.random.nextFloat() * 0.4F + 0.8F); + Utils.spawnParticle(location, Particle.EXPLOSION, 10, 0, 0, 0); + } + + @SuppressWarnings("UnstableApiUsage") + private void damageNearbyEnemies(Player player) { + Collection enemies = player.getLocation().getWorld().getNearbyLivingEntities(player.getLocation(), 2, 2, 2); + for (LivingEntity enemy : enemies) { + if (enemy == player) continue; + DamageSource damageSource = DamageSource.builder(DamageTypes.ENDER_POWER) + .withDirectEntity(player) + .build(); + enemy.damage(Items.ENDER_GIANT_BLADE.getChargeDamage(), damageSource); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/GrapplingHookListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/GrapplingHookListener.java new file mode 100644 index 0000000..5a5b683 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/GrapplingHookListener.java @@ -0,0 +1,124 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.plugin.managers.MessageManager; +import com.shanebeestudios.survival.plugin.managers.MessageManager.MessageType; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerFishEvent.State; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.List; + +public class GrapplingHookListener implements Listener { + + private final MessageManager messageManager; + + public GrapplingHookListener(SurvivalPlugin plugin) { + this.messageManager = plugin.getMessageManager(); + } + + @EventHandler + private void onPlayerFish(PlayerFishEvent event) { + Player player = event.getPlayer(); + ItemStack mainHand = player.getInventory().getItemInMainHand(); + ItemStack offHand = player.getInventory().getItemInOffHand(); + + if (mainHand.getType() == Material.FISHING_ROD) { + player.getInventory().getItemInOffHand(); + if (offHand.getType() == Material.AIR) { + + if (Items.GRAPPLING_HOOK.is(mainHand)) { + if (event.getState() == State.IN_GROUND) { + List nearbyEntities = player.getNearbyEntities(50, 50, 50); + + Entity hook = null; + + for (Entity e : nearbyEntities) // loop through entities + { + if (e.getType() == EntityType.FISHING_BOBBER) //Hook found + { + hook = e; + break; + } + } + + if (hook != null) { + Location hookLoc = hook.getLocation(); + Location playerLoc = player.getLocation(); + + playerLoc.setY(playerLoc.getY() + 0.5); + + + Vector vector = hookLoc.toVector().subtract(playerLoc.toVector()); + if (vector.getY() > 0) + vector.setY(Math.sqrt(vector.getY())); + + player.teleport(playerLoc); + player.setVelocity(vector.multiply(0.5)); + } + } else if (event.getState() == State.CAUGHT_ENTITY) { + if (event.getCaught() != null) { + Location playerLoc = player.getLocation(); + Location entityLoc = event.getCaught().getLocation(); + + playerLoc.setY(playerLoc.getY() + 0.5); + entityLoc.setY(entityLoc.getY() + 0.5); + + if (event.getCaught().getType() != EntityType.ITEM) { + Vector vector = entityLoc.toVector().subtract(playerLoc.toVector()); + if (vector.getY() > 0) + vector.setY(Math.sqrt(vector.getY()) * 4); + + player.teleport(playerLoc); + player.setVelocity(vector.multiply(0.5).multiply(0.25)); + } + + Vector reverseVector = playerLoc.toVector().subtract(entityLoc.toVector()); + + if (reverseVector.getY() > 0) + reverseVector.setY(Math.sqrt(reverseVector.getY())); + + if (event.getCaught().getType() != EntityType.ITEM) { + event.getCaught().teleport(entityLoc); + event.getCaught().setVelocity(reverseVector.multiply(0.5).multiply(0.125)); + } else { + if (reverseVector.getY() > 0) + reverseVector.setY(Math.sqrt(reverseVector.getY()) * 0.5); + + event.getCaught().teleport(entityLoc); + event.getCaught().setVelocity(reverseVector.multiply(0.5).multiply(0.00625)); + } + } + } else if (event.getState() == State.BITE || event.getState() == State.CAUGHT_FISH) { + event.setCancelled(true); + player.updateInventory(); + } + } + } else { + event.setCancelled(true); + if (Items.GRAPPLING_HOOK.is(mainHand)) + this.messageManager.sendMessage(player, MessageType.GRAPPLING_HOOK_OFF_HAND); + else + this.messageManager.sendMessage(player, MessageType.FISH_OFF_HAND); + player.updateInventory(); + } + } else { + event.setCancelled(true); + if (Items.GRAPPLING_HOOK.is(offHand)) + this.messageManager.sendMessage(player, MessageType.GRAPPLING_HOOK_MAIN_HAND); + else + this.messageManager.sendMessage(player, MessageType.FISH_MAIN_HAND); + player.updateInventory(); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/MedicKit.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/MedicKit.java new file mode 100644 index 0000000..bfab92a --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/MedicKit.java @@ -0,0 +1,169 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import io.papermc.paper.entity.LookAnchor; +import org.bukkit.Bukkit; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +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.entity.EntityDamageByEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.data.Stat; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import com.shanebeestudios.survival.api.util.ItemUtils; +import com.shanebeestudios.survival.api.util.PlayerUtils; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.Random; + +@SuppressWarnings("BooleanMethodIsAlwaysInverted") +public class MedicKit implements Listener { + + private final SurvivalPlugin plugin; + private final Lang lang; + private final PlayerManager playerManager; + private final Random random = new Random(); + + public MedicKit(SurvivalPlugin plugin) { + this.plugin = plugin; + this.lang = plugin.getLang(); + this.playerManager = plugin.getPlayerManager(); + } + + @EventHandler(priority = EventPriority.HIGHEST) + private void onDamaged(EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (event.getEntity() instanceof Player player) { + PlayerData playerData = this.playerManager.getPlayerData(player); + playerData.setStat(Stat.HEALING, 0); + } + } + + @SuppressWarnings("deprecation") + @EventHandler(priority = EventPriority.HIGHEST) + private void onClickEntity(PlayerInteractEntityEvent event) { + if (event.isCancelled()) return; + final Player player = event.getPlayer(); + PlayerData playerData = this.playerManager.getPlayerData(player); + ItemStack mainItem = player.getInventory().getItemInMainHand(); + + if (!Items.MEDIC_KIT.is(mainItem) || !Items.MEDIC_KIT.canHeal(mainItem)) return; + if (playerData.getStat(Stat.HEALING) > 0) return; + if (player.isSneaking()) return; + if (!(event.getRightClicked() instanceof Player patient)) return; + if (!canBeHealed(patient)) return; + + PlayerData patientData = this.playerManager.getPlayerData(patient); + + if (patientData.getStat(Stat.HEALING) > 0) return; + + playerData.setStat(Stat.HEALING, 1); + patientData.setStat(Stat.HEALING, 1); + + Utils.sendColoredMini(player, this.lang.healing_other, patient.getDisplayName()); + Utils.sendColoredMini(patient, this.lang.healing_being_healed, player.getDisplayName()); + + Bukkit.getServer().getScheduler().runTaskLater(this.plugin, new Runnable() { + @Override + public void run() { + heal(player, patient, playerData, patientData, this); + } + }, 20); + } + + @EventHandler + private void onSelfClick(PlayerInteractEvent event) { + if (event.getHand() != EquipmentSlot.HAND) return; + if (event.hasItem() && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { + final Player player = event.getPlayer(); + ItemStack mainItem = player.getInventory().getItemInMainHand(); + if (!canBeHealed(player)) return; + if (!Items.MEDIC_KIT.is(mainItem) || !Items.MEDIC_KIT.canHeal(mainItem)) return; + + PlayerData playerData = this.playerManager.getPlayerData(player); + if (playerData.getStat(Stat.HEALING) > 0) return; + if (!player.isSneaking()) return; + + playerData.setStat(Stat.HEALING, 1); + Utils.sendColoredMini(player, this.lang.healing_self); + + Bukkit.getServer().getScheduler().runTaskLater(this.plugin, new Runnable() { + @Override + public void run() { + heal(player, player, playerData, playerData, this); + } + }, 20); + } + } + + private void heal(@NotNull Player doctor, @NotNull Player patient, @NotNull PlayerData doctorData, @NotNull PlayerData patientData, @NotNull Runnable task) { + int times = doctorData.getStat(Stat.HEAL_TIMES); + boolean healingOther = doctor != patient; + ItemStack medicKitItemStack = doctor.getInventory().getItemInMainHand(); + if (Items.MEDIC_KIT.is(medicKitItemStack) && Items.MEDIC_KIT.canHeal(medicKitItemStack) && canBeHealed(patient)) { + World world = doctor.getWorld(); + if (healingOther) { + doctor.lookAt(patient, LookAnchor.EYES, LookAnchor.EYES); + patient.lookAt(doctor, LookAnchor.EYES, LookAnchor.EYES); + } + PlayerUtils.freezePlayer(doctor, true); + PlayerUtils.freezePlayer(patient, true); + float volume = healingOther ? (float) doctor.getLocation().distance(patient.getLocation()) : 1f; + world.playSound(doctor.getLocation(), Sound.ENTITY_BREEZE_CHARGE, volume, this.random.nextFloat() * 0.4F + 0.8F); + + healPlayer(patient, 2.0); + ItemUtils.damageItem(doctor, medicKitItemStack, 1); + + Utils.spawnParticle(patient.getLocation(), Particle.HAPPY_VILLAGER, 10, 0.25, 2, 0.25); + if (healingOther) { + Utils.spawnParticle(doctor.getLocation(), Particle.HAPPY_VILLAGER, 10, 0.25, 2, 0.25); + } + + // Repeat + Bukkit.getServer().getScheduler().runTaskLater(this.plugin, task, 20L); + doctorData.setStat(Stat.HEAL_TIMES, times); + } else { + doctorData.setStat(Stat.HEALING, 0); + if (healingOther) { + patientData.setStat(Stat.HEALING, 0); + Utils.sendColoredMini(patient, this.lang.healing_complete); + PlayerUtils.freezePlayer(patient, false); + } + + Utils.sendColoredMini(doctor, this.lang.healing_complete); + PlayerUtils.freezePlayer(doctor, false); + + doctor.getInventory().removeItem(Items.MEDIC_KIT.getItemStack()); + } + } + + @SuppressWarnings("SameParameterValue") + private void healPlayer(Player player, double amount) { + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + assert attribute != null; + if (attribute.getValue() - player.getHealth() > amount) { + player.setHealth(player.getHealth() + amount); + } + } + + private boolean canBeHealed(Player player) { + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + assert attribute != null; + return player.getHealth() < (attribute.getValue() * 0.9); + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/PoisonousPotato.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/PoisonousPotato.java similarity index 85% rename from src/main/java/tk/shanebee/survival/listeners/item/PoisonousPotato.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/PoisonousPotato.java index d7407d4..322f849 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/PoisonousPotato.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/PoisonousPotato.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import java.util.Random; @@ -23,10 +23,10 @@ private void onConsume(PlayerItemConsumeEvent event) { Random rand = new Random(); if (rand.nextInt(10) + 1 <= 6) { - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 100, 0), true); - player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 200, 0), true); + player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 100, 0)); + player.addPotionEffect(new PotionEffect(PotionEffectType.NAUSEA, 200, 0)); } } } -} \ No newline at end of file +} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/RawMeatHunger.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RawMeatHunger.java similarity index 95% rename from src/main/java/tk/shanebee/survival/listeners/item/RawMeatHunger.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RawMeatHunger.java index e33b223..fd7e3fc 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/RawMeatHunger.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RawMeatHunger.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import java.util.Random; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RecurvedBowListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RecurvedBowListener.java new file mode 100644 index 0000000..45b06f8 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RecurvedBowListener.java @@ -0,0 +1,72 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.events.ShootRecurvedBowEvent; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.item.items.tools.RecurvedBow; +import com.shanebeestudios.survival.api.util.Utils; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityShootBowEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.Random; + +public class RecurvedBowListener implements Listener { + + private final SurvivalPlugin plugin; + private final Random random = new Random(); + + public RecurvedBowListener(SurvivalPlugin plugin) { + this.plugin = plugin; + } + + @EventHandler + private void onShoot(EntityShootBowEvent event) { + if (!(event.getEntity() instanceof Player player)) return; + if (Utils.isCitizensNPC(player)) return; + + ItemStack mainItem = event.getBow(); + + assert mainItem != null; + if (!(Items.getFromStack(mainItem) instanceof RecurvedBow recurvedBow)) return; + + if (event.getForce() >= 3F) { // Max = 3 + final Entity arrow = event.getProjectile(); + final Vector velocity = player.getLocation().getDirection().add(new Vector(0, 0.025, 0)).multiply(4); + // Call new ShootRecurvedBowEvent + ShootRecurvedBowEvent shootEvent = new ShootRecurvedBowEvent(player, mainItem, recurvedBow); + if (!shootEvent.callEvent()) { + event.setCancelled(true); + return; + } + + arrow.setVelocity(velocity); + + player.getWorld().playSound(player.getLocation(), Sound.BLOCK_LEVER_CLICK, 1.0F, this.random.nextFloat() * 0.4F + 0.8F); + player.getWorld().playSound(player.getLocation(), Sound.ENTITY_SHULKER_BULLET_HURT, 0.5F, this.random.nextFloat() * 0.4F + 0.8F); + + Bukkit.getScheduler().runTask(this.plugin, new Runnable() { + int times = 4; + + public void run() { + if (!arrow.isOnGround()) { + arrow.setVelocity(velocity); + if (times-- > 0) + Bukkit.getScheduler().runTaskLater(plugin, this, 5); + } + } + }); + } else { + event.setCancelled(true); + player.updateInventory(); + player.getWorld().playSound(player.getLocation(), Sound.BLOCK_LEVER_CLICK, 0.5F, this.random.nextFloat() * 0.4F + 0.8F); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RepairCrafting.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RepairCrafting.java new file mode 100644 index 0000000..96b95e1 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/RepairCrafting.java @@ -0,0 +1,112 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.ItemUtils; +import io.papermc.paper.datacomponent.DataComponentTypes; +import org.bukkit.Keyed; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.inventory.PrepareAnvilEvent; +import org.bukkit.event.inventory.PrepareItemCraftEvent; +import org.bukkit.inventory.AnvilInventory; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; + +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings("UnstableApiUsage") +public class RepairCrafting implements Listener { + + @EventHandler + private void onCraft(PrepareItemCraftEvent event) { + Recipe recipe = event.getRecipe(); + if (recipe instanceof Keyed keyed && keyed.getKey().getNamespace().equalsIgnoreCase("survival_plus")) { + // If this is a legit recipe, let's get outta here + return; + } + CraftingInventory inventory = event.getInventory(); + + List items = new ArrayList<>(); + for (ItemStack itemStack : inventory.getMatrix()) { + if (itemStack != null) { + items.add(itemStack); + } + } + + if (items.size() == 2) { + ItemStack iOne = items.get(0); + ItemStack iTwo = items.get(1); + Item itemOne = Items.getFromStack(iOne); + Item itemTwo = Items.getFromStack(iTwo); + if (itemOne != null && itemOne == itemTwo) { + ItemStack result = repair(iOne, iTwo, itemOne.getRepairPercent()); + if (inventory.getType() == InventoryType.CRAFTING || itemOne.getRepairCost() > 0) { + // No repairing in player inventory + // Cost > 0 signifies it requires an anvil + result = null; + } + if (result != null) { + // Since we're using a crafting table we're going to reset defaults + // ie: remove enchantments + result = resetItem(itemOne, result); + } + inventory.setResult(result); + + } else if ((itemOne != null && itemTwo == null) || (itemOne == null && itemTwo != null)) { + // Prevent repairing custom items with vanilla items + inventory.setResult(null); + + } + } + items.clear(); + } + + @EventHandler + private void onAnvilRepair(PrepareAnvilEvent event) { + AnvilInventory inventory = event.getInventory(); + ItemStack slotOne = inventory.getContents()[0]; + ItemStack slotTwo = inventory.getContents()[1]; + if (slotOne != null && slotTwo != null) { + if (slotOne.getType() != slotTwo.getType()) { + // If two different items, lets get outta here + // ie: enchanting + return; + } + Item itemOne = Items.getFromStack(slotOne); + Item itemTwo = Items.getFromStack(slotTwo); + // Let's make sure we're joining two of the same item + if (itemOne != null && itemOne == itemTwo) { + ItemStack result = repair(slotOne, slotTwo, itemOne.getRepairPercent()); + event.setResult(result); + } + } + } + + private ItemStack repair(ItemStack itemStackOne, ItemStack itemStackTwo, double repairPercent) { + if (repairPercent <= 0) return null; + + ItemStack result = itemStackOne.clone(); + int max = ItemUtils.getMaxDamage(itemStackOne); + int dura1 = ItemUtils.getDurability(itemStackOne); + int dura2 = ItemUtils.getDurability(itemStackTwo); + int repair = (int) Math.min((dura1 + dura2 + Math.floor((double) max / 20)) * repairPercent, max); + + result.setData(DataComponentTypes.DAMAGE, max - repair); + return result; + } + + @SuppressWarnings("DataFlowIssue") + private ItemStack resetItem(Item baseItem, ItemStack itemStack) { + if (!itemStack.hasData(DataComponentTypes.DAMAGE)) return null; + + ItemStack newItemStack = baseItem.getItemStack(); + newItemStack.setData(DataComponentTypes.DAMAGE, itemStack.getData(DataComponentTypes.DAMAGE)); + + return newItemStack; + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/ShivPoison.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/ShivPoison.java similarity index 86% rename from src/main/java/tk/shanebee/survival/listeners/item/ShivPoison.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/ShivPoison.java index 9dc9143..2bddd41 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/ShivPoison.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/ShivPoison.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import org.bukkit.Sound; import org.bukkit.entity.LivingEntity; @@ -15,11 +15,10 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.Utils; import java.util.Random; @@ -27,7 +26,7 @@ public class ShivPoison implements Listener { private Config config; - public ShivPoison(Survival plugin) { + public ShivPoison(SurvivalPlugin plugin) { this.config = plugin.getSurvivalConfig(); } @@ -43,7 +42,7 @@ private void onAttack(EntityDamageByEntityEvent event) { Random rand = new Random(); - if (ItemManager.compare(mainItem, Item.SHIV)) { + if (Items.SHIV.is(mainItem)) { ItemMeta mainItemMeta = mainItem.getItemMeta(); enemy.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 80, 0, false)); assert mainItemMeta != null; @@ -53,7 +52,7 @@ private void onAttack(EntityDamageByEntityEvent event) { } } - if (ItemManager.compare(offItem, Item.SHIV)) { + if (Items.SHIV.is(offItem)) { int chance_poison = rand.nextInt(4) + 1; switch (chance_poison) { case 1: @@ -81,7 +80,7 @@ private void onInteractBlock(PlayerInteractEvent event) { ItemStack tool = event.getItem(); if (event.getClickedBlock() == null || tool == null) return; - if (config.SURVIVAL_ENABLED && ItemManager.compare(tool, Item.SHIV)) { + if (config.survival_enabled && Items.SHIV.is(tool)) { switch (event.getClickedBlock().getType()) { case DIRT: case GRASS_BLOCK: diff --git a/src/main/java/tk/shanebee/survival/listeners/item/StarBattleaxeWither.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/StarBattleaxeWither.java similarity index 92% rename from src/main/java/tk/shanebee/survival/listeners/item/StarBattleaxeWither.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/StarBattleaxeWither.java index fa42409..1c3b7ce 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/StarBattleaxeWither.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/StarBattleaxeWither.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import java.util.Random; @@ -14,7 +14,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import tk.shanebee.survival.util.Utils; +import com.shanebeestudios.survival.api.util.Utils; public class StarBattleaxeWither implements Listener { diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/TropicalFish.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/TropicalFish.java new file mode 100644 index 0000000..5255e7b --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/TropicalFish.java @@ -0,0 +1,59 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import java.util.Random; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.Sound; +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.PlayerItemConsumeEvent; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; + +public class TropicalFish implements Listener { + + private final PlayerManager playerManager; + private final Random random = new Random(); + + public TropicalFish(SurvivalPlugin plugin) { + this.playerManager = plugin.getPlayerManager(); + } + + @EventHandler(priority = EventPriority.HIGHEST) + private void onConsume(PlayerItemConsumeEvent event) { + if (event.isCancelled()) return; + Player player = event.getPlayer(); + if (event.getItem().getType() == Material.TROPICAL_FISH) { + Location originLoc = player.getLocation(); + playSoundAndParticle(originLoc, Sound.ITEM_CHORUS_FRUIT_TELEPORT); + + PlayerData playerData = this.playerManager.getPlayerData(player); + Location waypoint = playerData.getCompassWaypoint(player.getWorld()); + + if (waypoint != null) { + player.teleport(waypoint); + playSoundAndParticle(waypoint, Sound.BLOCK_PORTAL_TRAVEL); + } else { + Location respawnLocation = player.getRespawnLocation(); + if (respawnLocation == null || respawnLocation.getWorld() != player.getWorld()) { + // Only teleport in the same world + respawnLocation = player.getWorld().getSpawnLocation(); + } + player.teleport(respawnLocation); + playSoundAndParticle(respawnLocation, Sound.BLOCK_PORTAL_TRAVEL); + } + } + } + + private void playSoundAndParticle(Location location, Sound sound) { + location.getWorld().spawnParticle(Particle.PORTAL, location, 200, 0.5, 0.5, 0.5); + location.getWorld().playSound(location, sound, 1.0F, this.random.nextFloat() * 0.4F + 0.8F); + + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/Valkyrie.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/Valkyrie.java similarity index 78% rename from src/main/java/tk/shanebee/survival/listeners/item/Valkyrie.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/item/Valkyrie.java index 7286e7c..723aef9 100644 --- a/src/main/java/tk/shanebee/survival/listeners/item/Valkyrie.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/Valkyrie.java @@ -1,14 +1,13 @@ -package tk.shanebee.survival.listeners.item; +package com.shanebeestudios.survival.plugin.listeners.item; import java.util.Collection; import java.util.Random; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.data.Stat; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.data.Stat; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.api.util.Utils; import org.bukkit.*; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -23,14 +22,14 @@ import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; -import tk.shanebee.survival.Survival; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; public class Valkyrie implements Listener { - private Survival plugin; - private Lang lang; + private final SurvivalPlugin plugin; + private final Lang lang; - public Valkyrie(Survival plugin) { + public Valkyrie(SurvivalPlugin plugin) { this.plugin = plugin; this.lang = plugin.getLang(); } @@ -43,7 +42,7 @@ private void onItemClick(PlayerInteractEvent event) { ItemMeta mainItemMeta = mainItem.getItemMeta(); assert mainItemMeta != null; - if (ItemManager.compare(mainItem, Item.VALKYRIES_AXE)) { + if (Items.VALKYRIES_AXE.is(mainItem)) { if (playerData.getStat(Stat.DUAL_WIELD) == 0) { if (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_AIR) { if (playerData.getStat(Stat.SPIN) == 0) { @@ -67,18 +66,10 @@ private void onItemClick(PlayerInteractEvent event) { } player.updateInventory(); } else { - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.lack_of_energy)); + Utils.sendColoredMini(player,"" + this.lang.lack_of_energy); } } } - } else { - if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) - playerData.setStat(Stat.DUAL_WIELD_MSG, playerData.getStat(Stat.DUAL_WIELD_MSG) + 1); - else if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) - playerData.setStat(Stat.DUAL_WIELD_MSG, playerData.getStat(Stat.DUAL_WIELD_MSG) + 2); - if (playerData.getStat(Stat.DUAL_WIELD_MSG) == 2) { - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.valkyrie_axe_unable_dual)); - } } } playerData.setStat(Stat.DUAL_WIELD_MSG, 0); @@ -96,7 +87,7 @@ private void onAttack(EntityDamageByEntityEvent event) { assert mainItemMeta != null; if (playerData.getStat(Stat.DUAL_WIELD) == 0) { - if (ItemManager.compare(mainItem, Item.VALKYRIES_AXE)) { + if (Items.VALKYRIES_AXE.is(mainItem)) { if (playerData.getStat(Stat.SPIN) == 0) { if (player.getFoodLevel() > 6) { Random rand = new Random(); @@ -119,12 +110,10 @@ private void onAttack(EntityDamageByEntityEvent event) { } player.updateInventory(); } else { - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.lack_of_energy)); + Utils.sendColoredMini(player,"" + this.lang.lack_of_energy); } } } - } else { - event.setCancelled(true); } } } @@ -135,7 +124,7 @@ private void spin(final Player player) { particleCircle(player, 50, 2.5f, Particle.CRIT); particleCircle(player, 25, 2f, Particle.CRIT); - particleCircle(player, 10, 2.5f, Particle.CRIT_MAGIC); + particleCircle(player, 10, 2.5f, Particle.CRIT); Random rand = new Random(); assert player.getLocation().getWorld() != null; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/WaterBowlListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/WaterBowlListener.java new file mode 100644 index 0000000..deead9b --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/WaterBowlListener.java @@ -0,0 +1,119 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import org.bukkit.Bukkit; +import org.bukkit.Keyed; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.Tag; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.data.Lightable; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.ItemSpawnEvent; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.util.Vector; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.events.WaterBowlFillEvent; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.item.Recipes; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.Random; + +public class WaterBowlListener implements Listener { + + private final SurvivalPlugin plugin; + private final boolean thirstEnabled; + private final boolean clayEnabled; + private final BukkitScheduler scheduler = Bukkit.getScheduler(); + private final Random random = new Random(); + + public WaterBowlListener(SurvivalPlugin plugin) { + this.plugin = plugin; + this.thirstEnabled = plugin.getSurvivalConfig().mechanics_thirst_enabled; + this.clayEnabled = plugin.getSurvivalConfig().recipes_clay; + } + + @EventHandler // Leave an empty bow in the crafting grid after crafting clay + private void onCraft(CraftItemEvent event) { + if (!(event.getRecipe() instanceof Keyed keyed) || !keyed.getKey().equals(Recipes.CLAY.getKeys().getFirst())) + return; + + final Player player = (Player) event.getWhoClicked(); + final CraftingInventory inventory = event.getInventory(); + + ItemStack[] ingredients = inventory.getMatrix(); + ItemStack result = inventory.getResult(); + + if (result != null && result.getType() == Material.CLAY) { + for (int i = 0; i < ingredients.length; i++) { + if (ingredients[i] != null && Items.WATER_BOWL.is(ingredients[i])) { + int slot = i + 1; + Bukkit.getServer().getScheduler().runTaskLater(this.plugin, () -> { + inventory.setItem(slot, new ItemStack(Material.BOWL)); + player.updateInventory(); + }, 1); + } + } + } + } + + @EventHandler // Extinguish a campfire + private void onExtinguishCampfire(PlayerInteractEvent event) { + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + Block clickedBlock = event.getClickedBlock(); + ItemStack tool = event.getItem(); + EquipmentSlot hand = event.getHand(); + Player player = event.getPlayer(); + + if (clickedBlock == null) return; + if (!Tag.CAMPFIRES.isTagged(clickedBlock.getType())) return; + if (tool == null || !Items.WATER_BOWL.is(tool) || hand == null) return; + + if (!(clickedBlock.getBlockData() instanceof Lightable lightable)) return; + if (!lightable.isLit()) return; + + lightable.setLit(false); + clickedBlock.setBlockData(lightable); + player.swingHand(hand); + player.getInventory().setItem(hand, new ItemStack(Material.BOWL)); + player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXTINGUISH_FIRE, 1.0F, this.random.nextFloat() * 0.4F + 0.8F); + Utils.spawnParticle(clickedBlock.getLocation().add(0.5, 0.5, 0.5), Particle.FALLING_WATER, 100, 0.25, 0.2, 0.25); + } + + @EventHandler // Drop bowl into water to fill bowl + private void onDrop(ItemSpawnEvent event) { + if (event.isCancelled()) return; + if (!this.thirstEnabled && !this.clayEnabled) return; + + final org.bukkit.entity.Item itemDrop = event.getEntity(); + if (itemDrop.getItemStack().getType() == Material.BOWL) { + this.scheduler.runTaskLater(this.plugin, () -> { + Location itemLocation = itemDrop.getLocation(); + if (itemLocation.getBlock().getType() != Material.WATER) return; + + WaterBowlFillEvent bowlFillEvent = new WaterBowlFillEvent(itemDrop.getItemStack()); + if (!bowlFillEvent.callEvent()) return; + + World world = itemDrop.getWorld(); + int amount = itemDrop.getItemStack().getAmount(); + itemDrop.remove(); + for (int i = 0; i < amount; i++) { + world.dropItem(itemLocation, Items.WATER_BOWL.getItemStack(), item -> + item.setVelocity(new Vector(0, 0.2, 0))); + } + }, 20); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/WaterPurifiedListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/WaterPurifiedListener.java new file mode 100644 index 0000000..59a9acf --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/item/WaterPurifiedListener.java @@ -0,0 +1,151 @@ +package com.shanebeestudios.survival.plugin.listeners.item; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.item.Items; +import org.bukkit.FluidCollisionMode; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Levelled; +import org.bukkit.block.data.Waterlogged; +import org.bukkit.entity.Entity; +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.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ItemType; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.PotionMeta; + + +@SuppressWarnings("UnstableApiUsage") +public class WaterPurifiedListener implements Listener { + + @SuppressWarnings("unused") + public WaterPurifiedListener(SurvivalPlugin plugin) { + } + + @EventHandler // Fill a bottle resulting in a water bottle + private void onFillWaterBottle(PlayerInteractEvent event) { + Player player = event.getPlayer(); + ItemStack item = event.getItem(); + EquipmentSlot hand = event.getHand(); + Action action = event.getAction(); + if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) return; + if (item == null || hand == null || item.getType() != Material.GLASS_BOTTLE) return; + + Block targetBlock = player.getTargetBlockExact(5, FluidCollisionMode.ALWAYS); + if (targetBlock == null || !isWaterBlock(targetBlock)) return; + event.setCancelled(true); + + ItemStack waterBottle = Items.getBiomeBasedWaterBottle(targetBlock.getBiome()).getItemStack(); + if (item.getAmount() > 1) { + if (!player.getInventory().addItem(waterBottle).isEmpty()) { + player.getWorld().dropItem(player.getLocation(), waterBottle); + } + if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) + item.setAmount(item.getAmount() - 1); + } else { + player.getInventory().setItem(hand, waterBottle); + } + } + + @EventHandler // if player catches a water bottle/potion give them dirty water instead + private void onFish(PlayerFishEvent event) { + if (event.isCancelled()) return; + if (event.getState() != PlayerFishEvent.State.CAUGHT_FISH) return; + + Entity caught = event.getCaught(); + if (caught instanceof org.bukkit.entity.Item item) { + ItemStack stack = item.getItemStack(); + if (stack.getType() == Material.POTION && checkWaterBottle(stack)) { + item.setItemStack(Items.getBiomeBasedWaterBottle(caught.getLocation().getBlock().getBiome()).getItemStack()); + } + } + } + + private boolean checkWaterBottle(ItemStack bottle) { + ItemMeta meta = bottle.getItemMeta(); + assert meta != null; + return switch (((PotionMeta) meta).getBasePotionType()) { + case WATER, MUNDANE, THICK, AWKWARD -> true; + case null, default -> false; + }; + } + + private boolean isWaterBlock(Block block) { + if (block.getType() == Material.WATER) { + return true; + } + return block.getBlockData() instanceof Waterlogged waterlogged && waterlogged.isWaterlogged(); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + private void onItemClick(PlayerInteractEvent event) { + if (!event.hasItem() || event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + + Player player = event.getPlayer(); + + EquipmentSlot hand = event.getHand(); + ItemStack mainItem = player.getInventory().getItemInMainHand(); + Block clickedBlock = event.getClickedBlock(); + if (hand == null || clickedBlock == null) return; + + Material clickedBlockType = clickedBlock.getType(); + + // Click cauldron with bottle to extract water + if (clickedBlockType == Material.WATER_CAULDRON && mainItem.getType() == Material.GLASS_BOTTLE) { + event.setCancelled(true); + + Levelled cauldronData = (Levelled) clickedBlock.getBlockData(); + if (cauldronData.getLevel() == 1) { + clickedBlock.setType(Material.CAULDRON); + } else { + cauldronData.setLevel(cauldronData.getLevel() - 1); + clickedBlock.setBlockData(cauldronData); + } + + ItemStack waterBottle; + if (clickedBlock.getRelative(BlockFace.DOWN).getType() == Material.FIRE) { + waterBottle = Items.PURIFIED_WATER.getItemStack(); + } else { + waterBottle = Items.getBiomeBasedWaterBottle(clickedBlock.getBiome()).getItemStack(); + } + + player.playSound(clickedBlock.getLocation(), Sound.ITEM_BOTTLE_FILL, 1, 1); + + if (mainItem.getAmount() > 1) { + mainItem.setAmount(mainItem.getAmount() - 1); + if (player.getInventory().firstEmpty() != -1) + player.getInventory().addItem(waterBottle); + else + player.getWorld().dropItem(player.getLocation(), waterBottle); + } else { + player.getInventory().setItemInMainHand(waterBottle); + } + } + + // Click cauldron with water bottle to fill + else if (clickedBlockType == Material.WATER_CAULDRON || clickedBlockType == Material.CAULDRON && Items.Tags.WATER_BOTTLE.isTagged(mainItem)) { + if (clickedBlockType == Material.WATER_CAULDRON) { + Levelled cauldronData = (Levelled) clickedBlock.getBlockData(); + if (cauldronData.getLevel() >= cauldronData.getMaximumLevel()) return; + cauldronData.setLevel(cauldronData.getLevel() + 1); + clickedBlock.setBlockData(cauldronData); + } else { + clickedBlock.setType(Material.WATER_CAULDRON); + } + event.setCancelled(true); + mainItem.setAmount(0); + player.getInventory().addItem(ItemType.GLASS_BOTTLE.createItemStack()); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/EnergyChange.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/EnergyChange.java new file mode 100644 index 0000000..520bcad --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/EnergyChange.java @@ -0,0 +1,119 @@ +package com.shanebeestudios.survival.plugin.listeners.player; + +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.events.EnergyLevelChangeEvent; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityExhaustionEvent; +import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.world.TimeSkipEvent; +import org.bukkit.inventory.ItemStack; + +public class EnergyChange implements Listener { + + private final PlayerManager playerManager; + private final Config config; + private final Lang lang; + + public EnergyChange(SurvivalPlugin plugin) { + this.playerManager = plugin.getPlayerManager(); + this.config = plugin.getSurvivalConfig(); + this.lang = plugin.getLang(); + } + + @EventHandler // Reset energy on respawn + private void onRespawn(PlayerRespawnEvent event) { + if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) return; + + Player player = event.getPlayer(); + if (Utils.isCitizensNPC(player)) return; + + PlayerData playerData = this.playerManager.getPlayerData(player); + + double respawnAmount = this.config.mechanics_energy_respawn; + double change = respawnAmount - playerData.getEnergy(); + EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, change, respawnAmount); + if (!energyEvent.callEvent()) return; + playerData.setEnergy(respawnAmount); + } + + @EventHandler // Give energy when drinking coffee + private void onDrinkCoffee(PlayerItemConsumeEvent event) { + ItemStack item = event.getItem(); + Player player = event.getPlayer(); + + PlayerData playerData = this.playerManager.getPlayerData(player); + + if (Items.COFFEE.is(item)) { + EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, 20.0 - playerData.getEnergy(), 20.0); + if (!energyEvent.callEvent()) return; + playerData.setEnergy(20.0); + } + } + + @EventHandler // Decrease energy when player does exhaustive tasks + private void onExhausted(EntityExhaustionEvent event) { + Player player = (Player) event.getEntity(); + + float exhaustion = event.getExhaustion(); + if (player.getExhaustion() + exhaustion < 4.0f) return; + + double modifier = this.config.mechanics_energy_exhaustion; + if (modifier <= 0) return; + + this.playerManager.getPlayerData(player).increaseEnergy(-modifier); + } + + // Send messages when energy level decreases + @EventHandler(ignoreCancelled = true) + private void onEnergyDrop(EnergyLevelChangeEvent event) { + if (!this.config.mechanics_energy_warning) return; + if (event.getChanged() > 0) { + Player player = event.getPlayer(); + PlayerData playerData = playerManager.getPlayerData(player); + double level = event.getEnergyLevel(); + double newLevel = playerData.getEnergy(); + + if (targetMatch(10.0, level, newLevel)) { + Utils.sendColoredMini(player, this.lang.energy_level_10); + } else if (targetMatch(6.5, level, newLevel)) { + Utils.sendColoredMini(player, this.lang.energy_level_6_5); + } else if (targetMatch(3.5, level, newLevel)) { + Utils.sendColoredMini(player, this.lang.energy_level_3_5); + } else if (targetMatch(2, level, newLevel)) { + Utils.sendColoredMini(player, this.lang.energy_level_2); + } else if (targetMatch(1, level, newLevel)) { + Utils.sendColoredMini(player, this.lang.energy_level_1); + } + } + } + + // Check if the change passed a certain amount + private boolean targetMatch(double target, double level, double newLevel) { + return level <= target && newLevel > target; + } + + // Increase players energy when they wake up after the night skips + @EventHandler + private void onSkipNight(TimeSkipEvent event) { + if (event.getSkipReason() != TimeSkipEvent.SkipReason.NIGHT_SKIP) return; + + for (Player player : event.getWorld().getPlayers()) { + if (!player.isSleeping()) continue; + PlayerData playerData = this.playerManager.getPlayerData(player); + + EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, 20.0 - playerData.getEnergy(), 20.0); + if (!energyEvent.callEvent()) return; + playerData.setEnergy(20); + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/player/PlayerDataListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/PlayerDataListener.java similarity index 56% rename from src/main/java/tk/shanebee/survival/listeners/player/PlayerDataListener.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/player/PlayerDataListener.java index 4867a57..f25b2d2 100644 --- a/src/main/java/tk/shanebee/survival/listeners/player/PlayerDataListener.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/PlayerDataListener.java @@ -1,27 +1,32 @@ -package tk.shanebee.survival.listeners.player; +package com.shanebeestudios.survival.plugin.listeners.player; +import org.bukkit.Bukkit; +import org.bukkit.Location; 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.PlayerQuitEvent; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.PlayerDataConfig; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.managers.ScoreBoardManager; +import org.bukkit.scheduler.BukkitScheduler; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.PlayerDataConfig; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import com.shanebeestudios.survival.plugin.managers.ScoreBoardManager; + +import java.util.Objects; public class PlayerDataListener implements Listener { - private final Survival plugin; + private final SurvivalPlugin plugin; private final PlayerManager playerManager; private final PlayerDataConfig playerDataConfig; private final ScoreBoardManager scoreboardManager; private final Config config; + private final BukkitScheduler scheduler = Bukkit.getScheduler(); - public PlayerDataListener(Survival plugin) { + public PlayerDataListener(SurvivalPlugin plugin) { this.plugin = plugin; this.playerManager = plugin.getPlayerManager(); this.playerDataConfig = plugin.getPlayerDataConfig(); @@ -38,17 +43,15 @@ private void onJoin(PlayerJoinEvent event) { } else { playerData = playerManager.loadPlayerData(player); } - if (config.MECHANICS_STATUS_SCOREBOARD) + if (config.mechanics_status_scoreboard) scoreboardManager.setupScoreboard(player); // Appears you can only set a compass target after a delay - if (config.MECHANICS_COMPASS_WAYPOINT) { - new BukkitRunnable() { - @Override - public void run() { - player.setCompassTarget(playerData.getCompassWaypoint(player.getWorld())); - } - }.runTaskLater(this.plugin, 1); + if (config.mechanics_compass_waypoint) { + this.scheduler.runTaskLater(this.plugin, () -> { + Location waypoint = playerData.getCompassWaypoint(player.getWorld()); + player.setCompassTarget(Objects.requireNonNullElseGet(waypoint, () -> player.getWorld().getSpawnLocation())); + }, 1); } } diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/ThirstListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/ThirstListener.java new file mode 100644 index 0000000..f001f12 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/player/ThirstListener.java @@ -0,0 +1,58 @@ +package com.shanebeestudios.survival.plugin.listeners.player; + +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityExhaustionEvent; +import org.bukkit.event.player.PlayerRespawnEvent; + +public class ThirstListener implements Listener { + + private final SurvivalPlugin plugin; + private final Config config; + private final PlayerManager playerManager; + + public ThirstListener(SurvivalPlugin plugin) { + this.plugin = plugin; + this.config = plugin.getSurvivalConfig(); + this.playerManager = plugin.getPlayerManager(); + } + + @EventHandler + private void onExhaustionReached(EntityExhaustionEvent event) { + Player player = (Player) event.getEntity(); + + float exhaustion = event.getExhaustion(); + if (player.getExhaustion() + exhaustion < 4.0f) return; + + PlayerData playerData = this.playerManager.getPlayerData(player); + + double change = this.config.mechanics_thirst_drain_rate; + + // Prevent calling thirst event if there is no change + if (change == 0) return; + + playerData.increaseThirst(-change); + } + + + @EventHandler + private void onRespawn(PlayerRespawnEvent event) { + if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) return; + + Player player = event.getPlayer(); + + PlayerData playerData = this.playerManager.getPlayerData(player); + double thirst = this.config.mechanics_thirst_respawn_amount; + playerData.setThirst(thirst); + + double hunger = this.config.mechanics_hunger_respawn_amount; + Bukkit.getScheduler().runTaskLater(this.plugin, () -> playerData.setHunger(hunger), 1); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/Guide.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/Guide.java new file mode 100644 index 0000000..ae08233 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/Guide.java @@ -0,0 +1,42 @@ +package com.shanebeestudios.survival.plugin.listeners.server; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.api.util.Utils; + +public class Guide implements Listener { + + private final SurvivalPlugin plugin; + private final Lang lang; + private final Config config; + + public Guide(SurvivalPlugin plugin) { + this.plugin = plugin; + this.lang = plugin.getLang(); + this.config = plugin.getSurvivalConfig(); + } + + @EventHandler + private void onJoin(PlayerJoinEvent e) { + if (e.getPlayer().hasPlayedBefore() && this.config.welcome_guide_new_players) return; + + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { + Player player = e.getPlayer(); + +// Component component = Utils.getMini(this.lang.survival_guide_msg); +// Component hover = Utils.getMini(this.lang.survival_guide_hover_msg); +// Component link = Utils.getMini(this.lang.survival_guide_click_msg) +// .hoverEvent(HoverEvent.showText(hover)) +// .clickEvent(ClickEvent.openUrl(this.lang.survival_guide_link)); +// player.sendMessage(component); + Utils.sendColoredMini(player, this.lang.survival_guide_msg); + }, 20L * this.config.welcome_guide_delay); + } + +} diff --git a/src/main/java/tk/shanebee/survival/listeners/server/LocalChat.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/LocalChat.java similarity index 73% rename from src/main/java/tk/shanebee/survival/listeners/server/LocalChat.java rename to src/main/java/com/shanebeestudios/survival/plugin/listeners/server/LocalChat.java index ed9f1e0..867dc71 100644 --- a/src/main/java/tk/shanebee/survival/listeners/server/LocalChat.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/LocalChat.java @@ -1,4 +1,4 @@ -package tk.shanebee.survival.listeners.server; +package com.shanebeestudios.survival.plugin.listeners.server; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -9,21 +9,23 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Config; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import com.shanebeestudios.survival.plugin.config.Config; +@SuppressWarnings("deprecation") public class LocalChat implements Listener { - private Config config; - private PlayerManager playerManager; + private final Config config; + private final PlayerManager playerManager; - public LocalChat(Survival plugin) { + public LocalChat(SurvivalPlugin plugin) { this.config = plugin.getSurvivalConfig(); this.playerManager = plugin.getPlayerManager(); } + // TODO cleanup?!?! @EventHandler(priority = EventPriority.HIGHEST) private void onChat(AsyncPlayerChatEvent event) { if (event.isCancelled()) return; @@ -31,7 +33,7 @@ private void onChat(AsyncPlayerChatEvent event) { PlayerData playerData = playerManager.getPlayerData(player); String msg = event.getMessage(); - if (config.LEGENDARY_GOLDARMORBUFF) { + if (config.legendary_gold_armor_buff) { if (player.getInventory().getHelmet() != null) { if (player.getInventory().getHelmet().getType() == Material.GOLDEN_HELMET) { event.setCancelled(false); @@ -51,7 +53,7 @@ private void onChat(AsyncPlayerChatEvent event) { event.setCancelled(true); Bukkit.getConsoleSender().sendMessage("<" + player.getDisplayName() + "> " + msg); - double maxDist = config.LOCAL_CHAT_DISTANCE; + double maxDist = config.settings_local_chat_distance; for (Player other : Bukkit.getServer().getOnlinePlayers()) { if (other.getLocation().getWorld() == player.getLocation().getWorld()) { if (other.getLocation().distance(player.getLocation()) <= maxDist) { @@ -61,4 +63,4 @@ private void onChat(AsyncPlayerChatEvent event) { } } -} \ No newline at end of file +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/RecipeDiscovery.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/RecipeDiscovery.java new file mode 100644 index 0000000..a8b6a49 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/RecipeDiscovery.java @@ -0,0 +1,227 @@ +package com.shanebeestudios.survival.plugin.listeners.server; + +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.item.Recipes; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.inventory.FurnaceExtractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; + +public class RecipeDiscovery implements Listener { + + private final SurvivalPlugin plugin; + private final boolean unlockAllRecipes; + + public RecipeDiscovery(SurvivalPlugin plugin) { + this.plugin = plugin; + this.unlockAllRecipes = plugin.getSurvivalConfig().survival_unlock_all_recipes; + } + + // When a player first joins, give them a few recipes after 10 seconds + @EventHandler + private void onFirstJoin(PlayerJoinEvent e) { + Player player = e.getPlayer(); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { + if (this.unlockAllRecipes) { + this.plugin.getRecipeManager().unlockAllRecipes(player); + } else { + Recipes.HATCHET.unlock(player); + Recipes.MATTOCK.unlock(player); + Recipes.SHIV.unlock(player); + Recipes.HAMMER.unlock(player); + Recipes.GLASS_BOTTLE.unlock(player); + Recipes.STICK.unlock(player); + Recipes.BREAD.unlock(player); + Recipes.STRING_FROM_WEB.unlock(player); + Recipes.CLEAN_WATER_BOTTLES.unlock(player); + } + player.discoverRecipe(NamespacedKey.minecraft("bowl")); + }, 100); + } + + // When a player picks up items, unlock different item based recipes + @EventHandler + private void onPickupItems(EntityPickupItemEvent e) { + if (this.unlockAllRecipes) return; + if (!(e.getEntity() instanceof Player player)) return; + Material item = e.getItem().getItemStack().getType(); + switch (item) { + case DIAMOND: + Recipes.DIAMOND_BOOTS.unlock(player); + Recipes.DIAMOND_CHESTPLATE.unlock(player); + Recipes.DIAMOND_LEGGINGS.unlock(player); + Recipes.DIAMOND_HELMET.unlock(player); + Recipes.DIAMOND_HORSE_ARMOR.unlock(player); + Recipes.VALKYRIES_AXE.unlock(player); + Recipes.QUARTZ_PICKAXE.unlock(player); + Recipes.ENDER_GIANT_BLADE.unlock(player); + Recipes.DIAMOND_SICKLE.unlock(player); + break; + case FLINT: + Recipes.FIRESTRIKER.unlock(player); + Recipes.GRAVEL.unlock(player); + Recipes.FLINT_SICKLE.unlock(player); + break; + case FEATHER: + Recipes.MEDIC_KIT.unlock(player); + Recipes.FISHING_ROD.unlock(player); + break; + case BLAZE_POWDER, BLAZE_ROD: + Recipes.BLAZE_SWORD.unlock(player); + break; + case LEATHER: + Recipes.SADDLE.unlock(player); + Recipes.LEATHER_HORSE_ARMOR.unlock(player); + break; + case GRAVEL: + Recipes.FLINT.unlock(player); + break; + case ROTTEN_FLESH: + Recipes.FERMENTED_SKIN.unlock(player); + break; + case STRING: + Recipes.COBWEB.unlock(player); + Recipes.RECURVED_BOW.unlock(player); + break; + case SPIDER_EYE: + Recipes.FERMENTED_SPIDER_EYE.unlock(player); + break; + case POTATO: + Recipes.POISONOUS_POTATO.unlock(player); + break; + case COBBLESTONE: + Recipes.ANDESITE.unlock(player); + Recipes.DIORITE.unlock(player); + Recipes.GRANITE.unlock(player); + Recipes.STONE_SICKLE.unlock(player); + break; + case QUARTZ: + Recipes.QUARTZ.unlock(player); + break; + case DIRT: + Recipes.CLAY.unlock(player); + break; + case EGG: + Recipes.COOKIE.unlock(player); + break; + case VINE: + Recipes.SLIMEBALL.unlock(player); + break; + case REDSTONE: + Recipes.COMPASS.unlock(player); + break; + case HONEYCOMB: + Recipes.BEEKEEPER_SUIT.unlock(player); + } + if (Items.WATER_BOWL.is(e.getItem().getItemStack())) { + Recipes.BOWL.unlock(player); + } + } + + // When a player smelts items, unlock different item based recipes + @EventHandler + private void onFurnaceExtract(FurnaceExtractEvent event) { + if (this.unlockAllRecipes) return; + Player player = event.getPlayer(); + Material itemType = event.getItemType(); + switch (itemType) { + case IRON_INGOT: + Recipes.IRON_BOOTS.unlock(player); + Recipes.IRON_CHESTPLATE.unlock(player); + Recipes.IRON_HELMET.unlock(player); + Recipes.IRON_LEGGINGS.unlock(player); + Recipes.IRON_HORSE_ARMOR.unlock(player); + Recipes.IRON_INGOT.unlock(player); + Recipes.IRON_SICKLE.unlock(player); + Recipes.IRON_NUGGET.unlock(player); + break; + case GOLD_INGOT: + Recipes.GOLD_NUGGET.unlock(player); + Recipes.GOLD_INGOT.unlock(player); + Recipes.GOLD_CROWN.unlock(player); + Recipes.GOLD_GREAVES.unlock(player); + Recipes.GOLD_GUARD.unlock(player); + Recipes.GOLD_SABATONS.unlock(player); + Recipes.GOLD_HORSE_ARMOR.unlock(player); + Recipes.ENCHANTED_GOLDEN_APPLE.unlock(player); + break; + case NETHERITE_INGOT: + Recipes.NETHERITE_HELMET.unlock(player); + Recipes.NETHERITE_CHESTPLATE.unlock(player); + Recipes.NETHERITE_LEGGINGS.unlock(player); + Recipes.NETHERITE_BOOTS.unlock(player); + } + } + + // When a player breaks a block, unlock different item based recipes + @EventHandler + private void onPlayerBreakBlock(BlockBreakEvent e) { + if (this.unlockAllRecipes) return; + Player player = e.getPlayer(); + Material blockType = e.getBlock().getType(); + if (e.isCancelled()) return; + if (Tag.LOGS.isTagged(blockType)) { + Recipes.WORKBENCH.unlock(player); + Recipes.CHEST.unlock(player); + Recipes.UNLIT_CAMPFIRE.unlock(player); + } else if (blockType == Material.OBSIDIAN) { + Recipes.OBSIDIAN_MACE.unlock(player); + } else if (blockType == Material.ICE || blockType == Material.BLUE_ICE || blockType == Material.FROSTED_ICE || blockType == Material.PACKED_ICE) { + Recipes.ICE.unlock(player); + Recipes.PACKED_ICE.unlock(player); + } + } + + // When a player crafts an item, unlock different item based recipes + @EventHandler + private void onCraft(CraftItemEvent e) { + if (this.unlockAllRecipes) return; + if (!(e.getWhoClicked() instanceof Player player)) return; + + ItemStack result = e.getRecipe().getResult(); + if (Items.FIRESTRIKER.is(result)) { + Recipes.TORCH.unlock(player); + Recipes.FURNACE.unlock(player); + } else if (result.getType() == Material.FURNACE) { + Recipes.FURNACE_GOLD_INGOT.unlock(player); + Recipes.FURNACE_IRON_INGOT.unlock(player); + } else if (result.getType() == Material.BLAST_FURNACE) { + Recipes.BLAST_GOLD_INGOT.unlock(player); + Recipes.BLAST_IRON_INGOT.unlock(player); + } else if (result.getType() == Material.CROSSBOW) { + Recipes.RECURVED_CROSSBOW.unlock(player); + } else if (result.getType() == Material.LEATHER_HELMET || result.getType() == Material.LEATHER_CHESTPLATE + || result.getType() == Material.LEATHER_LEGGINGS || result.getType() == Material.LEATHER_BOOTS) { + Recipes.REINFORCED_LEATHER_HELMET.unlock(player); + Recipes.REINFORCED_LEATHER_CHESTPLATE.unlock(player); + Recipes.REINFORCED_LEATHER_LEGGINGS.unlock(player); + Recipes.REINFORCED_LEATHER_BOOTS.unlock(player); + } else if (result.getType() == Material.PAPER) { + Recipes.NAMETAG.unlock(player); + Recipes.MEDIC_KIT.unlock(player); + } else if (result.getType() == Material.STRING) { + Recipes.COBWEB.unlock(player); + Recipes.RECURVED_BOW.unlock(player); + } else if (result.getType() == Material.BRICK || result.getType() == Material.BRICKS) { + Recipes.CLAY_BRICK.unlock(player); + } else if (result.getType() == Material.FISHING_ROD) { + Recipes.GRAPPLING_HOOK.unlock(player); + } else if (result.getType() == Material.GLASS_BOTTLE) { + Recipes.COFFEE.unlock(player); + Recipes.COFFEE_BEAN.unlock(player); + Recipes.HOT_MILK.unlock(player); + Recipes.COLD_MILK.unlock(player); + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/ResourcePackListener.java b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/ResourcePackListener.java new file mode 100644 index 0000000..4e32288 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/listeners/server/ResourcePackListener.java @@ -0,0 +1,69 @@ +package com.shanebeestudios.survival.plugin.listeners.server; + +import net.kyori.adventure.text.Component; +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.PlayerResourcePackStatusEvent; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.UUID; + +public class ResourcePackListener implements Listener { + + private final String resourcePackUrl; + private final UUID resourcePackID = UUID.fromString("cd60c108-b291-4d5a-a9e8-1404defeed1b"); + private final Component kickMessage; + private final Component resourcePackMessage; + + public ResourcePackListener(SurvivalPlugin plugin) { + Config config = plugin.getSurvivalConfig(); + Lang lang = plugin.getLang(); + this.resourcePackUrl = config.settings_resource_pack_url; + this.kickMessage = Utils.getMini(lang.resource_pack_fail_download); + this.resourcePackMessage = Utils.getMini( lang.resource_pack_apply); + } + + + @EventHandler + private void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + try { + player.setResourcePack(this.resourcePackID, this.resourcePackUrl, "", this.resourcePackMessage, true); + } catch (IllegalArgumentException ex) { + Utils.logMini("[ResourcePackListener] Invalid resource pack URL: %s", this.resourcePackUrl); + Utils.logMini("[ResourcePackListener] Error Message: %s", ex.getMessage()); + kick(player); + } + } + + @EventHandler + private void resourcePackEvent(PlayerResourcePackStatusEvent event) { + Player player = event.getPlayer(); + switch (event.getStatus()) { + case DECLINED: + Utils.logMini("Player '%s' denied the resource pack and was kicked!", player.getName()); + break; + case FAILED_DOWNLOAD, FAILED_RELOAD: + Utils.logMini("Player '%s' failed to download the resource pack!", player.getName()); + kick(player); + break; + case INVALID_URL: + Utils.logMini("Player '%s' failed to download the resource pack due to invalid url: '%s'", + player.getName(), this.resourcePackUrl); + kick(player); + break; + case DISCARDED: + + } + } + + private void kick(Player player) { + player.kick(this.kickMessage); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/EffectManager.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/EffectManager.java new file mode 100644 index 0000000..46e440d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/EffectManager.java @@ -0,0 +1,35 @@ +package com.shanebeestudios.survival.plugin.managers; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.tasks.tool.Valkyrie; + +public class EffectManager { + + private final SurvivalPlugin plugin; + private final Config config; + + // Effect Tasks + private Valkyrie valkyrie = null; + + public EffectManager(SurvivalPlugin plugin) { + this.plugin = plugin; + this.config = plugin.getSurvivalConfig(); + loadEffects(); + } + + private void loadEffects() { + if (config.legendary_valkyrie) + this.valkyrie = new Valkyrie(plugin); + } + + /** + * Stop all effect tasks + */ + @SuppressWarnings("unused") + public void cancelTasks() { + if (valkyrie != null) + valkyrie.cancel(); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/LootManager.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/LootManager.java new file mode 100644 index 0000000..e3d933b --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/LootManager.java @@ -0,0 +1,154 @@ +package com.shanebeestudios.survival.plugin.managers; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.item.Item; +import com.shanebeestudios.survival.api.item.Items; +import com.shanebeestudios.survival.api.util.ItemUtils; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Merchant; +import org.bukkit.inventory.MerchantRecipe; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Manager for Merchant Recipes + */ +public class LootManager { + + private final Config config; + + public LootManager(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + } + + /** + * Update a merchants recipes + *

Replaces existing MerchantRecipes with ones that use custom {@link Items}

+ * + * @param merchant Merchant to update + */ + public void updateMerchant(Merchant merchant) { + for (int i = 0; i < merchant.getRecipes().size(); i++) { + MerchantRecipe merchantRecipe = merchant.getRecipe(i); + Material result = merchantRecipe.getResult().getType(); + LootReplacements lootReplacements = LootReplacements.getByMaterial(result); + if (lootReplacements != null && canUpdate(result)) { + merchant.setRecipe(i, lootReplacements.updateRecipe(merchantRecipe)); + } + } + } + + public void updateLoot(List loot) { + for (int i = 0; i < loot.size(); i++) { + ItemStack itemStack = loot.get(i); + Material type = itemStack.getType(); + LootReplacements replacement = LootReplacements.getByMaterial(type); + if (replacement != null && canUpdate(type)) { + loot.set(i, replacement.items.getItemStack()); + } + } + } + + private boolean canUpdate(Material material) { + return switch (material) { + case CHAINMAIL_HELMET, CHAINMAIL_CHESTPLATE, CHAINMAIL_LEGGINGS, CHAINMAIL_BOOTS -> + this.config.mechanics_reinforced_armor; + case GOLDEN_HELMET, GOLDEN_CHESTPLATE, GOLDEN_LEGGINGS, GOLDEN_BOOTS, + IRON_HELMET, IRON_CHESTPLATE, IRON_LEGGINGS, IRON_BOOTS, + DIAMOND_HELMET, DIAMOND_CHESTPLATE, DIAMOND_LEGGINGS, DIAMOND_BOOTS, + NETHERITE_HELMET, NETHERITE_CHESTPLATE, NETHERITE_LEGGINGS, NETHERITE_BOOTS -> + this.config.mechanics_slow_armor; + case WOODEN_HOE -> this.config.survival_sickle_flint; + case IRON_HOE -> this.config.survival_sickle_iron; + case STONE_HOE -> this.config.survival_sickle_stone; + case DIAMOND_HOE -> this.config.survival_sickle_diamond; + case WOODEN_AXE, WOODEN_PICKAXE -> this.config.survival_enabled; + default -> false; + }; + } + + /** + * Loot/Merchant overrides + *

These will take vanilla LootTables/MerchantRecipes and replace them with custom {@link Items}s

+ */ + public enum LootReplacements { + GOLDEN_HELMET(Material.GOLDEN_HELMET, Items.GOLDEN_CROWN), + GOLDEN_CHESTPLATE(Material.GOLDEN_CHESTPLATE, Items.GOLDEN_GUARD), + GOLDEN_LEGGINGS(Material.GOLDEN_LEGGINGS, Items.GOLDEN_GREAVES), + GOLDEN_BOOTS(Material.GOLDEN_BOOTS, Items.GOLDEN_SABATONS), + IRON_HELMET(Material.IRON_HELMET, Items.IRON_HELMET), + IRON_CHESTPLATE(Material.IRON_CHESTPLATE, Items.IRON_CHESTPLATE), + IRON_LEGGINGS(Material.IRON_LEGGINGS, Items.IRON_LEGGINGS), + IRON_BOOTS(Material.IRON_BOOTS, Items.IRON_BOOTS), + DIAMOND_HELMET(Material.DIAMOND_HELMET, Items.DIAMOND_HELMET), + DIAMOND_CHESTPLATE(Material.DIAMOND_CHESTPLATE, Items.DIAMOND_CHESTPLATE), + DIAMOND_LEGGINGS(Material.DIAMOND_LEGGINGS, Items.DIAMOND_LEGGINGS), + DIAMOND_BOOTS(Material.DIAMOND_BOOTS, Items.DIAMOND_BOOTS), + NETHERITE_HELMET(Material.NETHERITE_HELMET, Items.NETHERITE_HELMET), + NETHERITE_CHESTPLATE(Material.NETHERITE_CHESTPLATE, Items.NETHERITE_CHESTPLATE), + NETHERITE_LEGGINGS(Material.NETHERITE_LEGGINGS, Items.NETHERITE_LEGGINGS), + NETHERITE_BOOTS(Material.NETHERITE_BOOTS, Items.NETHERITE_BOOTS), + REINFORCED_LEATHER_HELMET(Material.CHAINMAIL_HELMET, Items.REINFORCED_LEATHER_HELMET), + REINFORCED_LEATHER_TUNIC(Material.CHAINMAIL_CHESTPLATE, Items.REINFORCED_LEATHER_TUNIC), + REINFORCED_LEATHER_TROUSERS(Material.CHAINMAIL_LEGGINGS, Items.REINFORCED_LEATHER_TROUSERS), + REINFORCED_LEATHER_BOOTS(Material.CHAINMAIL_BOOTS, Items.REINFORCED_LEATHER_BOOTS), + FLINT_SICKLE(Material.WOODEN_HOE, Items.FLINT_SICKLE), + STONE_SICKLE(Material.STONE_HOE, Items.STONE_SICKLE), + IRON_SICKLE(Material.IRON_HOE, Items.IRON_SICKLE), + DIAMOND_SICKLE(Material.DIAMOND_HOE, Items.DIAMOND_SICKLE), + HATCHET(Material.WOODEN_AXE, Items.HATCHET), + MATTOCK(Material.WOODEN_PICKAXE, Items.MATTOCK); + + private final Material material; + private final Item items; + private static final Map recipeByMaterialMap; + + static { + recipeByMaterialMap = new HashMap<>(); + for (LootReplacements lootReplacements : values()) { + recipeByMaterialMap.put(lootReplacements.material, lootReplacements); + } + } + + LootReplacements(Material material, Item items) { + this.material = material; + this.items = items; + } + + /** + * Get an updated MerchantRecipe based on an existing MerchantRecipe + * + * @param oldRecipe Old MerchantRecipe to replace + * @return Updated MerchantRecipe using custom items + */ + public MerchantRecipe updateRecipe(MerchantRecipe oldRecipe) { + ItemStack old = oldRecipe.getResult().clone(); + + ItemUtils.applyEnchantments(old, this.items); + MerchantRecipe recipe = new MerchantRecipe(old, oldRecipe.getUses(), oldRecipe.getMaxUses(), + oldRecipe.hasExperienceReward(), oldRecipe.getVillagerExperience(), + oldRecipe.getPriceMultiplier()); + recipe.setIngredients(oldRecipe.getIngredients()); + return recipe; + } + + /** + * Get a Recipe by material + * + * @param material Material to get recipe from + * @return Recipe based on material + */ + public static LootReplacements getByMaterial(Material material) { + if (recipeByMaterialMap.containsKey(material)) { + return recipeByMaterialMap.get(material); + } + return null; + } + + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/MessageManager.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/MessageManager.java new file mode 100644 index 0000000..1d75576 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/MessageManager.java @@ -0,0 +1,139 @@ +package com.shanebeestudios.survival.plugin.managers; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.api.util.Utils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Manager for sending delayed messages to players + *

Messages are sent at most every 5 seconds, + * preventing players from being bombarded with the + * same message repeatedly

+ */ +public class MessageManager { + + public enum MessageType { + ARROWS_OFFHAND { + @Override + String getMessage(Lang lang) { + return "" + lang.arrows_off_hand; + } + }, + ARROWS_OFFHAND_CROSSBOW { + @Override + String getMessage(Lang lang) { + return "" + lang.arrows_off_hand_crossbow; + } + }, + BOW_MAIN_HAND { + @Override + String getMessage(Lang lang) { + return "" + lang.bow_main_hand; + } + }, + DUAL_WIELD_NO { + @Override + String getMessage(Lang lang) { + return "" + lang.prevent_dual_wield; + } + }, + FISH_MAIN_HAND { + @Override + String getMessage(Lang lang) { + return "" + lang.fishing_main_hand; + } + }, + FISH_OFF_HAND { + @Override + String getMessage(Lang lang) { + return "" + lang.fishing_off_hand; + } + }, + GRAPPLING_HOOK_MAIN_HAND { + @Override + String getMessage(Lang lang) { + return "" + lang.grappling_main_hand; + } + }, + GRAPPLING_HOOK_OFF_HAND { + @Override + String getMessage(Lang lang) { + return "" + lang.grappling_off_hand; + } + }, + REQUIRES_AXE { + @Override + String getMessage(Lang lang) { + return "" + lang.task_must_use_axe; + } + }, + REQUIRES_HAMMER { + @Override + String getMessage(Lang lang) { + return "" + lang.task_must_use_hammer; + } + }, + REQUIRES_PICKAXE { + @Override + String getMessage(Lang lang) { + return "" + lang.task_must_use_pick; + } + }, + REQUIRES_SHEARS { + @Override + String getMessage(Lang lang) { + return "" + lang.task_must_use_shear; + } + }, + REQUIRES_SHOVEL { + @Override + String getMessage(Lang lang) { + return "" + lang.task_must_use_shovel; + } + }, + REQUIRES_SICKLE { + @Override + String getMessage(Lang lang) { + return "" + lang.task_must_use_sickle; + } + }; + + MessageType() { + } + + abstract String getMessage(Lang lang); + } + + private final Lang lang; + private final Map> messages = new HashMap<>(); + + public MessageManager(SurvivalPlugin plugin) { + this.lang = plugin.getLang(); + for (MessageType value : MessageType.values()) { + this.messages.put(value, new ArrayList<>()); + } + Bukkit.getScheduler().runTaskTimer(plugin, () -> + this.messages.forEach((key, playerList) -> playerList.clear()), + 100, 100); + } + + public void sendMessage(Player player, MessageType messageType) { + if (this.messages.get(messageType).contains(player)) return; + this.messages.get(messageType).add(player); + Utils.sendColoredMini(player, messageType.getMessage(this.lang)); + } + + public void sendMessage(Player player, MessageType messageType, Object... args) { + if (this.messages.get(messageType).contains(player)) return; + this.messages.get(messageType).add(player); + Utils.sendColoredMini(player, messageType.getMessage(this.lang), args); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/PapiPlaceholders.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/PapiPlaceholders.java new file mode 100644 index 0000000..a499ce1 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/PapiPlaceholders.java @@ -0,0 +1,125 @@ +package com.shanebeestudios.survival.plugin.managers; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.Placeholders; +import com.shanebeestudios.survival.api.data.Nutrient; +import com.shanebeestudios.survival.api.data.PlayerData; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +@SuppressWarnings({"unused", "UnstableApiUsage"}) +public class PapiPlaceholders extends PlaceholderExpansion { + + private final SurvivalPlugin plugin; + private final PlayerManager playerManager; + + public PapiPlaceholders(SurvivalPlugin plugin) { + this.plugin = plugin; + this.playerManager = plugin.getPlayerManager(); + } + + @Override + public boolean persist() { + return true; + } + + @Override + public boolean canRegister() { + return true; + } + + @Override + public @NotNull String getIdentifier() { + return "survival_plus"; + } + + @Override + public @NotNull String getAuthor() { + return plugin.getPluginMeta().getAuthors().toString(); + } + + @Override + public @NotNull String getVersion() { + return plugin.getPluginMeta().getVersion(); + } + + @Override + public String onPlaceholderRequest(Player player, @NotNull String identifier) { + PlayerData playerData = playerManager.getPlayerData(player); + + // Shows player's health, kinda useless but here it is + if (Placeholders.PLAYER_HEALTH.is(identifier)) { + return String.format("%.2f", player.getHealth()); + } + // Shows a player's total hunger (including saturation) + if (Placeholders.PLAYER_HUNGER_TOTAL.is(identifier)) { + return String.valueOf(player.getFoodLevel() + player.getSaturation()); + } + // Shows player's hunger + if (Placeholders.PLAYER_HUNGER.is(identifier)) { + return String.valueOf(player.getFoodLevel()); + } + // Shows player's saturation + if (Placeholders.PLAYER_SATURATION.is(identifier)) { + return String.valueOf(player.getSaturation()); + } + // Shows player's hunger bar (hunger part) + if (Placeholders.PLAYER_HUNGER_BAR_1.is(identifier)) { + return this.playerManager.getHungerVisual(player).get(1); + } + // Shows player's hunger bar (saturation part) + if (Placeholders.PLAYER_HUNGER_BAR_2.is(identifier)) { + return this.playerManager.getHungerVisual(player).get(2); + } + // Shows player's thirst + if (Placeholders.PLAYER_THIRST.is(identifier)) { + return String.valueOf(playerData.getThirst()); + } + // Shows player's thirst bar (top part - first half out of 40) + if (Placeholders.PLAYER_THIRST_BAR_1.is(identifier)) { + return this.playerManager.getThirstVisual(player).get(1); + } + // Shows player's thirst bar (bottom part - second half out of 40) + if (Placeholders.PLAYER_THIRST_BAR_2.is(identifier)) { + return this.playerManager.getThirstVisual(player).get(2); + } + // Shows player's energy level (as a number) + if (Placeholders.PLAYER_ENERGY.is(identifier)) { + return String.format("%.2f", playerData.getEnergy()); + } + // Shows player's energy level (as a colored bar) + if (Placeholders.PLAYER_ENERGY_BAR.is(identifier)) { + return this.playerManager.getEnergyVisual(player).get(1); + } + + // Shows player's nutrients bars ( ) + if (Placeholders.PLAYER_NUTRIENTS_CARBS_BAR.is(identifier)) { + List nutrientsVisual = this.playerManager.getNutrientsVisual(player); + return nutrientsVisual.get(0) + " " + nutrientsVisual.get(3); + } + if (Placeholders.PLAYER_NUTRIENTS_PROTEINS_BAR.is(identifier)) { + List nutrientsVisual = this.playerManager.getNutrientsVisual(player); + return nutrientsVisual.get(1) + " " + nutrientsVisual.get(4); + } + if (Placeholders.PLAYER_NUTRIENTS_VITAMINS_BAR.is(identifier)) { + List nutrientsVisual = this.playerManager.getNutrientsVisual(player); + return nutrientsVisual.get(2) + " " + nutrientsVisual.get(5); + } + + // Shows player's nutrients (just the ) + if (Placeholders.PLAYER_NUTRIENTS_CARBS.is(identifier)) { + return String.valueOf(playerData.getNutrient(Nutrient.CARBS)); + } + if (Placeholders.PLAYER_NUTRIENTS_PROTEINS.is(identifier)) { + return String.valueOf(playerData.getNutrient(Nutrient.PROTEIN)); + } + if (Placeholders.PLAYER_NUTRIENTS_VITAMINS.is(identifier)) { + return String.valueOf(playerData.getNutrient(Nutrient.VITAMINS)); + } + return null; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/PlayerManager.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/PlayerManager.java new file mode 100644 index 0000000..93e4edc --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/PlayerManager.java @@ -0,0 +1,279 @@ +package com.shanebeestudios.survival.plugin.managers; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.config.PlayerDataConfig; +import com.shanebeestudios.survival.api.data.Nutrient; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Manager for players + *

Get an instance of this class from {@link SurvivalPlugin#getPlayerManager()}

+ */ +public class PlayerManager implements Listener { + + private final Lang lang; + private final Config config; + private final PlayerDataConfig playerDataConfig; + + // Store all the active PlayerData + private final Map playerDataMap; + + public PlayerManager(SurvivalPlugin plugin, Map playerDataMap) { + this.playerDataMap = playerDataMap; + this.lang = plugin.getLang(); + this.playerDataConfig = plugin.getPlayerDataConfig(); + this.config = plugin.getSurvivalConfig(); + } + + /** + * Get PlayerData for a player + * + * @param player Player to get data for + * @return PlayerData for player + */ + public PlayerData getPlayerData(Player player) { + return this.playerDataMap.get(player.getUniqueId()); + } + + /** + * Get a collection of all PlayerData + * + * @return Collection of all PlayerData + */ + @SuppressWarnings("unused") + public Collection getAllPlayerData() { + return this.playerDataMap.values(); + } + + /** + * Create player data for a new player + * + * @param player Player to create data for + * @return Newly created player data + */ + public PlayerData createNewPlayerData(Player player) { + setHunger(player, this.config.mechanics_hunger_start_amount); + + PlayerData playerData = new PlayerData(player, + this.config.mechanics_thirst_starting_amount, + this.config.mechanics_food_start_protein, + this.config.mechanics_food_start_carbs, + this.config.mechanics_food_start_vitamins, + this.config.mechanics_energy_start); + this.playerDataMap.put(player.getUniqueId(), playerData); + savePlayerData(playerData); + return playerData; + } + + private void setHunger(Player player, int value) { + value = Math.min(value, 40); + int hunger = Math.min(value, 20); + int saturation = value > 20 ? value - 20 : 0; + player.setFoodLevel(hunger); + player.setSaturation(saturation); + } + + /** + * Save PlayerData to file + * + * @param data PlayerData to save + */ + private void savePlayerData(PlayerData data) { + this.playerDataConfig.savePlayerDataToFile(data); + } + + /** + * Load PlayerData from file into map + * + * @param player Player to load data for + * @return Loaded player data + */ + public PlayerData loadPlayerData(Player player) { + PlayerData playerData = this.playerDataConfig.getPlayerDataFromFile(player); + this.playerDataMap.put(player.getUniqueId(), playerData); + return playerData; + } + + /** + * Save/Unload player data + *

This will mainly be used internally for when a player leaves the server, + * their data will be saved to file then removed from the PlayerData map

+ * + * @param player Player to save/unload data for + */ + public void unloadPlayerData(Player player) { + PlayerData playerData = getPlayerData(player); + this.playerDataConfig.savePlayerDataToFile(playerData); + this.playerDataMap.remove(player.getUniqueId()); + } + + /** + * Set the waypoint of a player's compass to their location + * + * @param player The player to set a waypoint for + * @param particle If particles should show at the location a waypoint is set + */ + @SuppressWarnings("unused") + public void setWaypoint(Player player, boolean particle) { + setWaypoint(player, player.getLocation(), particle); + } + + /** + * Set the waypoint of a player's compass + * + * @param player The player to set a waypoint for + * @param location The location of the waypoint + * @param particle If the particles should show at the location a waypoint is set + */ + public void setWaypoint(Player player, Location location, boolean particle) { + PlayerData playerData = getPlayerData(player); + playerData.setCompassWaypoint(location); + if (particle) + Utils.spawnParticle(location, Particle.CLOUD, 25, 0.5, 0.5, 0.5, player); + savePlayerData(playerData); + } + + + public Location lookAt(Location loc, Location lookat) { + //Clone the loc to prevent applied changes to the input loc + loc = loc.clone(); + + // Values of change in distance (make it relative) + double dx = lookat.getX() - loc.getX(); + double dy = lookat.getY() - loc.getY(); + double dz = lookat.getZ() - loc.getZ(); + + // Set yaw + if (dx != 0) { + // Set yaw start value based on dx + if (dx < 0) + loc.setYaw((float) (1.5 * Math.PI)); + else + loc.setYaw((float) (0.5 * Math.PI)); + + loc.setYaw(loc.getYaw() - (float) Math.atan(dz / dx)); + } else if (dz < 0) + loc.setYaw((float) Math.PI); + + // Get the distance from dx/dz + double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)); + + // Set pitch + loc.setPitch((float) -Math.atan(dy / dxz)); + + // Set values, convert to degrees (invert the yaw since Bukkit uses a different yaw dimension format) + loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI); + loc.setPitch(loc.getPitch() * 180f / (float) Math.PI); + + return loc; + } + + public List getThirstVisual(Player player) { + PlayerData data = getPlayerData(player); + int thirst = (int) data.getThirst(); + double grad = ((double) thirst / 40) - 1; + + // green - green - green - yellow - orange - red + StringBuilder thirstLineOne = new StringBuilder(""); + StringBuilder thirstLineTwo = new StringBuilder(""); + + if (thirst > 20) { + thirstLineOne.append("|".repeat(20)); + thirstLineTwo.append("|".repeat(thirst - 20)); + thirstLineTwo.append(".".repeat(20 - (thirst - 20))); + } else { + thirstLineOne.append("|".repeat(thirst)); + thirstLineOne.append(".".repeat(20 - thirst)); + thirstLineTwo.append(".".repeat(20)); + } + + return Arrays.asList("" + this.lang.thirst, thirstLineOne.toString(), thirstLineTwo.toString()); + } + + @SuppressWarnings("StringBufferReplaceableByString") + public List getHungerVisual(Player player) { + int hunger = Math.clamp(player.getFoodLevel(), 0, 20); + int saturation = Math.clamp((int) player.getSaturation(), 0, 20); + double grad = ((double) hunger / 20) - 1; + + // green - green - yellow - red + StringBuilder hungerBar = new StringBuilder(""); + StringBuilder saturationBar = new StringBuilder(""); + + hungerBar.append("|".repeat(Math.max(0, hunger))); + hungerBar.append(".".repeat(Math.max(0, 20 - hunger))); + saturationBar.append("|".repeat(Math.max(0, saturation))); + saturationBar.append(".".repeat(Math.max(0, 20 - saturation))); + + return Arrays.asList("<#63F9A7>" + this.lang.hunger, hungerBar.toString(), saturationBar.toString()); + } + + public List getNutrientsVisual(Player player) { + List nutrients = new ArrayList<>(); + PlayerData data = getPlayerData(player); + + int carbs = data.getNutrient(Nutrient.CARBS); + int protein = data.getNutrient(Nutrient.PROTEIN); + int vitamins = data.getNutrient(Nutrient.VITAMINS); + + nutrients.add("<#A0E853>" + this.lang.carbohydrates); + nutrients.add("<#CE784D>" + this.lang.protein); + nutrients.add("<#53DDE8>" + this.lang.vitamins); + + double carbGrad = ((double) carbs / this.config.mechanics_food_max_level) - 1; + double proteinGrad = ((double) protein / this.config.mechanics_food_max_level) - 1; + double vitaminsGrad = ((double) vitamins / this.config.mechanics_food_max_level) - 1; + + // green - green - green - yellow - red + nutrients.add("" + carbs); + nutrients.add("" + protein); + nutrients.add("" + vitamins); + + return nutrients; + } + + @SuppressWarnings("StringBufferReplaceableByString") + public List getEnergyVisual(Player player) { + PlayerData playerData = getPlayerData(player); + double energy = Math.floor(playerData.getEnergy()); + double grad = (energy / 20) - 1; + + // green - green - green - yellow - red + StringBuilder energyBar = new StringBuilder(""); + energyBar.append("|".repeat((int) Math.max(0, Math.ceil(energy)))); + energyBar.append(".".repeat((int) Math.max(0, 20 - Math.ceil(energy)))); + + return Arrays.asList("<#F963F2>" + this.lang.energy, energyBar.toString()); + } + + /** + * Check if player is holding arrows in their offhand + * + * @param player The player to check + * @return Whether or not the player has arrows in their offhand + */ + public boolean isArrowOffHand(Player player) { + Material mainHand = player.getInventory().getItemInMainHand().getType(); + Material offHand = player.getInventory().getItemInOffHand().getType(); + if (mainHand == Material.CROSSBOW) + return offHand == Material.ARROW || offHand == Material.SPECTRAL_ARROW + || offHand == Material.TIPPED_ARROW || offHand == Material.FIREWORK_ROCKET; + return offHand == Material.ARROW || offHand == Material.SPECTRAL_ARROW || offHand == Material.TIPPED_ARROW; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/RecipeManager.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/RecipeManager.java new file mode 100644 index 0000000..5683967 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/RecipeManager.java @@ -0,0 +1,143 @@ +package com.shanebeestudios.survival.plugin.managers; + +import org.bukkit.Bukkit; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Player; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.item.Recipes; + +public class RecipeManager { + + private final Config config; + + public RecipeManager(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + } + + /** + * Load all custom server recipes + */ + public void loadCustomRecipes() { + removeRecipes(); + Recipes.init(this.config); + } + + private void removeRecipes() { + if (this.config.survival_enabled) { + removeRecipeByKey("campfire"); + removeRecipeByKey("chest"); + if (this.config.survival_torch) { + removeRecipeByKey("torch"); + } + if (this.config.recipes_furnace) { + removeRecipeByKey("furnace"); + } + if (this.config.recipes_workbench) { + removeRecipeByKey("crafting_table"); + } + } + if (this.config.survival_remove_wood_tools) { + removeRecipeByKey("wooden_sword"); + removeRecipeByKey("wooden_hoe"); + removeRecipeByKey("wooden_shovel"); + removeRecipeByKey("wooden_pickaxe"); + removeRecipeByKey("wooden_axe"); + } + if (this.config.mechanics_reduced_iron_nugget) { + removeRecipeByKey("iron_ingot"); + removeRecipeByKey("iron_ingot_from_nuggets"); + removeRecipeByKey("iron_nugget"); + removeRecipeByKey("iron_nugget_from_smelting"); + } + if (this.config.mechanics_reduced_gold_nugget) { + removeRecipeByKey("gold_ingot"); + removeRecipeByKey("gold_ingot_from_nuggets"); + removeRecipeByKey("gold_nugget"); + removeRecipeByKey("gold_nugget_from_smelting"); + + } + if (this.config.mechanics_slow_armor) { + removeRecipeByKey("diamond_helmet"); + removeRecipeByKey("diamond_chestplate"); + removeRecipeByKey("diamond_leggings"); + removeRecipeByKey("diamond_boots"); + removeRecipeByKey("iron_helmet"); + removeRecipeByKey("iron_chestplate"); + removeRecipeByKey("iron_leggings"); + removeRecipeByKey("iron_boots"); + } + if (this.config.mechanics_snowball_revamp) { + removeRecipeByKey("snow"); + removeRecipeByKey("snow_block"); + } + if (this.config.mechanics_farming_products_cookie) { + removeRecipeByKey("cookie"); + } + if (this.config.mechanics_farming_products_bread) { + removeRecipeByKey("bread"); + } + if (this.config.legendary_gold_armor_buff) { + removeRecipeByKey("golden_helmet"); + removeRecipeByKey("golden_chestplate"); + removeRecipeByKey("golden_boots"); + removeRecipeByKey("golden_leggings"); + } + if (this.config.legendary_blaze_sword) { + removeRecipeByKey("golden_sword"); + } + if (this.config.legendary_giant_blade) { + removeRecipeByKey("golden_hoe"); + } + if (this.config.legendary_quartz_pickaxe) { + removeRecipeByKey("golden_pickaxe"); + } + if (this.config.legendary_obsidian_mace) { + removeRecipeByKey("golden_shovel"); + } + if (this.config.legendary_valkyrie) { + removeRecipeByKey("golden_axe"); + } + if (this.config.recipes_granite) { + removeRecipeByKey("granite"); + } + if (this.config.recipes_andesite) { + removeRecipeByKey("andesite"); + } + if (this.config.recipes_diorite) { + removeRecipeByKey("diorite"); + } + if (this.config.recipes_leather_bard) { + removeRecipeByKey("leather_horse_armor"); + } + if (this.config.recipes_fishing_rod) { + removeRecipeByKey("fishing_rod"); + } + if (this.config.mechanics_compass_waypoint) { + removeRecipeByKey("compass"); + } + if (this.config.recipes_packed_ice) { + removeRecipeByKey("packed_ice"); + } + } + + /** + * Unlock all custom recipes for a player + * + * @param player Player to unlock recipes for + */ + public void unlockAllRecipes(Player player) { + player.discoverRecipes(Recipes.getAllRecipeKeys()); + } + + /** + * Remove a vanilla Minecraft recipe from the server + * + * @param recipeKey Recipe to remove + */ + @SuppressWarnings("WeakerAccess") + public void removeRecipeByKey(String recipeKey) { + Bukkit.removeRecipe(NamespacedKey.minecraft(recipeKey)); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/ScoreBoardManager.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/ScoreBoardManager.java new file mode 100644 index 0000000..d093e25 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/ScoreBoardManager.java @@ -0,0 +1,91 @@ +package com.shanebeestudios.survival.plugin.managers; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.data.HealthBoard; +import com.shanebeestudios.survival.plugin.tasks.HealthBoardTask; +import org.jetbrains.annotations.ApiStatus; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class ScoreBoardManager { + + private final SurvivalPlugin plugin; + private final Map healthBoardTaskMap = new HashMap<>(); + private final Map boardMap = new HashMap<>(); + + public ScoreBoardManager(SurvivalPlugin plugin) { + this.plugin = plugin; + } + + /** + * @hidden Should not be used outside this plugin + */ + @ApiStatus.Internal + public void setupScoreboard(Player player) { + this.healthBoardTaskMap.put(player.getUniqueId(), new HealthBoardTask(this.plugin, player)); + } + + /** + * @hidden Should not be used outside this plugin + */ + @ApiStatus.Internal + public void resetStatusScoreboard(boolean enabled) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (enabled) { + setupScoreboard(player); + } else { + this.removeBoard(player); + } + } + } + + /** + * @hidden Should not be used outside this plugin + */ + @ApiStatus.Internal + public void unloadScoreboard(Player player) { + UUID uuid = player.getUniqueId(); + if (this.healthBoardTaskMap.containsKey(uuid)) { + this.healthBoardTaskMap.get(uuid).cancel(); + this.healthBoardTaskMap.remove(uuid); + } + } + + /** + * Get the Board for a specific player + *
+ * If no Board is available, a new one will be created + * + * @param player Player to grab scoreboard for + * @return Board of player + */ + public HealthBoard getBoard(Player player) { + if (this.boardMap.containsKey(player)) { + return this.boardMap.get(player); + } else { + HealthBoard healthBoard = new HealthBoard(player); + this.boardMap.put(player, healthBoard); + return healthBoard; + } + } + + /** + * Remove a Board for a player + *
+ * Useful when the player leaves the server + * + * @param player Player to remove Board for + */ + public void removeBoard(Player player) { + if (this.boardMap.containsKey(player)) { + HealthBoard healthBoard = this.boardMap.get(player); + healthBoard.toggle(false); + } + this.boardMap.remove(player); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/managers/package-info.java b/src/main/java/com/shanebeestudios/survival/plugin/managers/package-info.java new file mode 100644 index 0000000..0fc563c --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/managers/package-info.java @@ -0,0 +1,4 @@ +/** + * General managers for the plugin + */ +package com.shanebeestudios.survival.plugin.managers; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/package-info.java b/src/main/java/com/shanebeestudios/survival/plugin/package-info.java new file mode 100644 index 0000000..4181cd5 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/package-info.java @@ -0,0 +1,4 @@ +/** + * Main plugin package + */ +package com.shanebeestudios.survival.plugin; diff --git a/src/main/java/com/shanebeestudios/survival/plugin/registry/TagGenerator.java b/src/main/java/com/shanebeestudios/survival/plugin/registry/TagGenerator.java new file mode 100644 index 0000000..2fe0d10 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/registry/TagGenerator.java @@ -0,0 +1,168 @@ +package com.shanebeestudios.survival.plugin.registry; + +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalBootstrap; +import io.papermc.paper.datapack.DatapackRegistrar; +import io.papermc.paper.plugin.bootstrap.BootstrapContext; +import io.papermc.paper.plugin.lifecycle.event.LifecycleEventManager; +import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; +import io.papermc.paper.registry.RegistryKey; +import io.papermc.paper.registry.TypedKey; +import io.papermc.paper.registry.keys.tags.EnchantmentTagKeys; +import io.papermc.paper.registry.tag.TagKey; +import io.papermc.paper.tag.PostFlattenTagRegistrar; +import io.papermc.paper.tag.PreFlattenTagRegistrar; +import io.papermc.paper.tag.TagEntry; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.logger.slf4j.ComponentLogger; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.block.BlockType; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemType; +import org.codehaus.plexus.util.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; + +/** + * @hidden Internal only + */ +@SuppressWarnings({"UnstableApiUsage", "PatternValidation", "NullableProblems"}) +public class TagGenerator { + + private final FileConfiguration blockTagConfig; + private final FileConfiguration itemTagConfig; + private final FileConfiguration enchantmentTagConfig; + + public TagGenerator(BootstrapContext context) { + this.blockTagConfig = loadConfig(context.getDataDirectory(), "registry/block-tags.yml"); + this.itemTagConfig = loadConfig(context.getDataDirectory(), "registry/item-tags.yml"); + this.enchantmentTagConfig = loadConfig(context.getDataDirectory(), "registry/enchantment-tags.yml"); + loadDatapack(context); + loadTags(context); + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + private FileConfiguration loadConfig(Path dataFolder, String ymlFile) { + File file = new File(dataFolder.toFile(), ymlFile); + if (!file.exists()) { + file.getParentFile().mkdirs(); + URL resource = getClass().getClassLoader().getResource(ymlFile); + try { + FileUtils.copyURLToFile(resource, file); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + return YamlConfiguration.loadConfiguration(file); + } + + private void loadDatapack(BootstrapContext context) { + LifecycleEventManager manager = context.getLifecycleManager(); + manager.registerEventHandler(LifecycleEvents.DATAPACK_DISCOVERY.newHandler(event -> { + DatapackRegistrar registrar = event.registrar(); + try { + URI datapack = Objects.requireNonNull(SurvivalBootstrap.class.getResource("/datapack")).toURI(); + registrar.discoverPack(datapack, "survival_plus"); + } catch (IOException | URISyntaxException e) { + throw new RuntimeException(e); + } + })); + } + + private void loadTags(BootstrapContext context) { + ComponentLogger logger = context.getLogger(); + LifecycleEventManager manager = context.getLifecycleManager(); + + // Create block tags + manager.registerEventHandler(LifecycleEvents.TAGS.preFlatten(RegistryKey.BLOCK), event -> { + PreFlattenTagRegistrar registrar = event.registrar(); + createTags(logger, registrar, this.blockTagConfig); + }); + + // Create item tags + manager.registerEventHandler(LifecycleEvents.TAGS.preFlatten(RegistryKey.ITEM), event -> { + PreFlattenTagRegistrar registrar = event.registrar(); + createTags(logger, registrar, this.itemTagConfig); + }); + + // Create enchantment tags + manager.registerEventHandler(LifecycleEvents.TAGS.preFlatten(RegistryKey.ENCHANTMENT), event -> { + PreFlattenTagRegistrar registrar = event.registrar(); + createTags(logger, registrar, this.enchantmentTagConfig); + }); + + // Put our enchantments at the top of the tooltip list + manager.registerEventHandler(LifecycleEvents.TAGS.postFlatten(RegistryKey.ENCHANTMENT), event -> { + PostFlattenTagRegistrar registrar = event.registrar(); + Collection> tag = registrar.getTag(EnchantmentTagKeys.TOOLTIP_ORDER); + + List> newTags = new ArrayList<>(); + newTags.add(TypedKey.create(RegistryKey.ENCHANTMENT, Key.key("survival_plus:blazing"))); + newTags.add(TypedKey.create(RegistryKey.ENCHANTMENT, Key.key("survival_plus:obsidian_power"))); + newTags.add(TypedKey.create(RegistryKey.ENCHANTMENT, Key.key("survival_plus:quartz_mining"))); + registrar.setTag(EnchantmentTagKeys.TOOLTIP_ORDER, newTags); + registrar.addToTag(EnchantmentTagKeys.TOOLTIP_ORDER, tag); + }); + } + + private void createTags(ComponentLogger logger, PreFlattenTagRegistrar registrar, FileConfiguration config) { + String registerName = StringUtils.capitalize(registrar.registryKey().key().value()); + ConfigurationSection survivalPlusSection = config.getConfigurationSection("survival_plus"); + if (survivalPlusSection != null) { + logger.info(Utils.getMini("%s Tag Creation:", registerName)); + for (String key : survivalPlusSection.getKeys(false)) { + createTagFromSection(key, registrar, survivalPlusSection); + logger.info(Utils.getMini(" Generating tag 'survival_plus:%s'", key)); + } + } + ConfigurationSection minecraftSection = config.getConfigurationSection("minecraft"); + if (minecraftSection != null) { + logger.info(Utils.getMini("%s Tag Mutation:", registerName)); + for (String key : minecraftSection.getKeys(false)) { + addToTagFromSection(key, registrar, minecraftSection); + logger.info(Utils.getMini(" Adding value to tag 'minecraft:%s'", key)); + } + } + } + + private void createTagFromSection(String key, PreFlattenTagRegistrar registrar, ConfigurationSection survivalPlusSection) { + List> entries = new ArrayList<>(); + for (String s : survivalPlusSection.getStringList( key)) { + entries.add(getTagEntry(s, registrar.registryKey())); + } + + registrar.setTag(TagKey.create(registrar.registryKey(), Key.key("survival_plus:" + key)), entries); + } + + private void addToTagFromSection(String key, PreFlattenTagRegistrar registrar, ConfigurationSection survivalPlusSection) { + List> entries = new ArrayList<>(); + for (String s : survivalPlusSection.getStringList("minecraft." + key)) { + entries.add(getTagEntry(s, registrar.registryKey())); + } + if (entries.isEmpty()) return; + + registrar.addToTag(TagKey.create(registrar.registryKey(), Key.key("minecraft:" + key)), entries); + } + + private TagEntry getTagEntry(String string, RegistryKey key) { + if (string.startsWith("#")) { + TagKey tagKey = TagKey.create(key, Key.key(string.substring(1))); + return TagEntry.tagEntry(tagKey); + } + TypedKey blockKey = TypedKey.create(key, Key.key(string)); + return TagEntry.valueEntry(blockKey); + } + +} diff --git a/src/main/java/tk/shanebee/survival/tasks/EnergyDrain.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/EnergyDrain.java similarity index 53% rename from src/main/java/tk/shanebee/survival/tasks/EnergyDrain.java rename to src/main/java/com/shanebeestudios/survival/plugin/tasks/EnergyDrain.java index 2c4e53d..b417626 100644 --- a/src/main/java/tk/shanebee/survival/tasks/EnergyDrain.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/EnergyDrain.java @@ -1,78 +1,75 @@ -package tk.shanebee.survival.tasks; +package com.shanebeestudios.survival.plugin.tasks; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.World.Environment; +import org.bukkit.block.Block; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.util.Utils; public class EnergyDrain extends BukkitRunnable { private final PlayerManager playerManager; private final Config config; private final Lang lang; - private final double drainRate; - private final double drainRateCold; - private final double increaseRateBed; - private final double increaseRateChair; private final double absorb; private final double haste; - public EnergyDrain(Survival plugin) { + public EnergyDrain(SurvivalPlugin plugin) { this.playerManager = plugin.getPlayerManager(); this.config = plugin.getSurvivalConfig(); this.lang = plugin.getLang(); - this.drainRate = config.MECHANICS_ENERGY_DRAIN_RATE; // amount of energy to drain every 5 seconds - this.drainRateCold = config.MECHANICS_ENERGY_DRAIN_COLD_RATE; // amount of energy to drain every 5 seconds - this.increaseRateBed = config.MECHANICS_ENERGY_REFRESH_RATE_BED; // amount of energy to gain every 5 seconds of sleeping - this.increaseRateChair = config.MECHANICS_ENERGY_REFRESH_RATE_CHAIR; // amount of energy to gain every 5 seconds of sitting in chair - this.absorb = config.MECHANICS_ENERGY_ABSORPTION ? 20 - (drainRate * 12) : 200; // Roughly 1 minute of absorption hearts after full energy - this.haste = config.MECHANICS_ENERGY_HASTE ? 20 - (drainRate * 25): 200; // Roughly 2 minutes of haste after full energy + this.absorb = this.config.mechanics_energy_absorption ? 20 - (this.config.mechanics_energy_drain_rate * 12) : 200; // Roughly 1 minute of absorption hearts after full energy + this.haste = this.config.mechanics_energy_haste ? 20 - (this.config.mechanics_energy_drain_rate * 25): 200; // Roughly 2 minutes of haste after full energy this.runTaskTimer(plugin, 5 * 20, 5 * 20); } @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { + PlayerData playerData = playerManager.getPlayerData(player); GameMode mode = player.getGameMode(); if (mode == GameMode.SPECTATOR || mode == GameMode.CREATIVE) continue; + if (player.isSleeping()) { - playerData.increaseEnergy(this.increaseRateBed); + playerData.increaseEnergy(this.config.mechanics_energy_refresh_rate_bed); } else if (isSitting(player)) { - playerData.increaseEnergy(this.increaseRateChair); + playerData.increaseEnergy(this.config.mechanics_energy_refresh_rate_chair); } else { double oldLevel = playerData.getEnergy(); - double rate = this.drainRate; - if (this.drainRateCold > 0 && player.getWorld().getEnvironment() == Environment.NORMAL) { - if (player.getLocation().getBlock().getTemperature() < 0.15 && Utils.isAtHighest(player)) { - rate += drainRateCold; + double rate = this.config.mechanics_energy_drain_rate; + if (this.config.mechanics_energy_drain_cold_rate > 0 && player.getWorld().getEnvironment() == Environment.NORMAL) { + Block block = player.getLocation().getBlock(); + // In a cold biome and under direct sun or close to + if (block.getTemperature() < 0.15 && block.getLightFromSky() > 13) { + rate += this.config.mechanics_energy_drain_cold_rate; } } playerData.increaseEnergy(-rate); double newLevel = playerData.getEnergy(); - if (config.MECHANICS_ENERGY_WARNING) { + if (this.config.mechanics_energy_warning) { if (targetMatch(10.0, oldLevel, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_10); + Utils.sendColoredMini(player, this.lang.energy_level_10); } else if (targetMatch(6.5, oldLevel, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_6_5); + Utils.sendColoredMini(player, this.lang.energy_level_6_5); } else if (targetMatch(3.5, oldLevel, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_3_5); + Utils.sendColoredMini(player, this.lang.energy_level_3_5); } else if (targetMatch(2, oldLevel, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_2); + Utils.sendColoredMini(player, this.lang.energy_level_2); } else if (targetMatch(1, oldLevel, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_1); + Utils.sendColoredMini(player, this.lang.energy_level_1); } } effects(player, playerData); @@ -88,10 +85,8 @@ private boolean targetMatch(double target, double level, double newLevel) { // BAD EFFECTS private static final PotionEffect SICK_40; private static final PotionEffect SICK_120; - private static final PotionEffect BLIND_50; - private static final PotionEffect BLIND_120; - private static final PotionEffect NIGHT_10; - private static final PotionEffect NIGHT_120; + private static final PotionEffect DARK_50; + private static final PotionEffect DARK_120; private static final PotionEffect MINING_120; private static final PotionEffect MINING_120_2; private static final PotionEffect MINING_120_3; @@ -103,21 +98,21 @@ private boolean targetMatch(double target, double level, double newLevel) { private static final PotionEffect ABSORPTION_500; static { - SICK_40 = new PotionEffect(PotionEffectType.CONFUSION, 40, 0); - SICK_120 = new PotionEffect(PotionEffectType.CONFUSION, 120, 0); - BLIND_50 = new PotionEffect(PotionEffectType.BLINDNESS, 50, 0); - BLIND_120 = new PotionEffect(PotionEffectType.BLINDNESS, 120, 0); - NIGHT_10 = new PotionEffect(PotionEffectType.NIGHT_VISION, 10, 0); - NIGHT_120 = new PotionEffect(PotionEffectType.NIGHT_VISION, 120, 0); - MINING_120 = new PotionEffect(PotionEffectType.SLOW_DIGGING, 120, 0, false, false); - MINING_120_2 = new PotionEffect(PotionEffectType.SLOW_DIGGING, 120, 1, false, false); - MINING_120_3 = new PotionEffect(PotionEffectType.SLOW_DIGGING, 120, 2, false, false); - SLOW_120 = new PotionEffect(PotionEffectType.SLOW, 120, 0, false, false); - WITHER_100 = new PotionEffect(PotionEffectType.WITHER, 100, 0); - HASTE_120 = new PotionEffect(PotionEffectType.FAST_DIGGING, 120, 0, false, false, true); + SICK_40 = new PotionEffect(PotionEffectType.NAUSEA, 40, 0); + SICK_120 = new PotionEffect(PotionEffectType.NAUSEA, 120, 0); + DARK_50 = new PotionEffect(PotionEffectType.DARKNESS, 50, 0); + DARK_120 = new PotionEffect(PotionEffectType.DARKNESS, 120, 0); + MINING_120 = new PotionEffect(PotionEffectType.MINING_FATIGUE, 120, 0, false, false); + MINING_120_2 = new PotionEffect(PotionEffectType.MINING_FATIGUE, 120, 1, false, false); + MINING_120_3 = new PotionEffect(PotionEffectType.MINING_FATIGUE, 120, 2, false, false); + SLOW_120 = new PotionEffect(PotionEffectType.SLOWNESS, 120, 0, false, false); + WITHER_100 = new PotionEffect(PotionEffectType.WITHER, 100, 0, false, true, false); + HASTE_120 = new PotionEffect(PotionEffectType.HASTE, 120, 0, false, false, false); ABSORPTION_500 = new PotionEffect(PotionEffectType.ABSORPTION, 500, 1, false, false); } + // TODO I want to eventually redo this. + // maybe with attributes instead? private void effects(Player player, PlayerData playerData) { double energy = playerData.getEnergy(); @@ -125,14 +120,12 @@ private void effects(Player player, PlayerData playerData) { player.addPotionEffect(WITHER_100); } else if (energy <= 2.0) { player.addPotionEffect(SICK_120); - player.addPotionEffect(NIGHT_120); - player.addPotionEffect(BLIND_120); + player.addPotionEffect(DARK_120); player.addPotionEffect(MINING_120_3); player.addPotionEffect(SLOW_120); } else if (energy <= 3.5) { player.addPotionEffect(SICK_40); - player.addPotionEffect(NIGHT_10); - player.addPotionEffect(BLIND_50); + player.addPotionEffect(DARK_50); player.addPotionEffect(MINING_120_3); } else if (energy <= 6.5) { player.addPotionEffect(MINING_120_3); @@ -150,8 +143,9 @@ private void effects(Player player, PlayerData playerData) { } } + @SuppressWarnings("deprecation") private boolean isSitting(Player player) { - if (!config.MECHANICS_CHAIRS_ENABLED) return false; + if (!this.config.mechanics_chairs_enabled) return false; Entity vehicle = player.getVehicle(); if (vehicle instanceof ArmorStand) { String name = vehicle.getCustomName(); diff --git a/src/main/java/com/shanebeestudios/survival/plugin/tasks/HealthBoardTask.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/HealthBoardTask.java new file mode 100644 index 0000000..99c2224 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/HealthBoardTask.java @@ -0,0 +1,136 @@ +package com.shanebeestudios.survival.plugin.tasks; + +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.data.HealthBoard; +import com.shanebeestudios.survival.api.data.Info; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; + +import java.util.List; + +public class HealthBoardTask extends BukkitRunnable { + + private final SurvivalPlugin plugin; + private final Config config; + private final PlayerManager playerManager; + private final Player player; + private final PlayerData playerData; + private final HealthBoard healthBoard; + + // Board stuff + private boolean hungerEnabled; + private boolean thirstEnabled; + private boolean energyEnabled; + private boolean nutrientsEnabled; + + public HealthBoardTask(SurvivalPlugin plugin, Player player) { + this.plugin = plugin; + this.config = plugin.getSurvivalConfig(); + this.playerManager = plugin.getPlayerManager(); + this.player = player; + this.playerData = plugin.getPlayerManager().getPlayerData(this.player); + this.healthBoard = plugin.getScoreboardManager().getBoard(this.player); + this.hungerEnabled = playerData.isInfoDisplayed(Info.HUNGER); + this.thirstEnabled = playerData.isInfoDisplayed(Info.THIRST); + this.energyEnabled = playerData.isInfoDisplayed(Info.ENERGY); + this.nutrientsEnabled = playerData.isInfoDisplayed(Info.NUTRIENTS); + + this.healthBoard.setTitle(plugin.getLang().healthboard_title); + + this.runTaskTimerAsynchronously(plugin, -1, 10); + } + + @Override + public void run() { + if (!this.player.isOnline()) { + this.cancel(); + return; + } + + GameMode mode = this.player.getGameMode(); + if (mode == GameMode.CREATIVE || mode == GameMode.SPECTATOR) { + // If the player is in creative/spectator and board is on, turn it off + if (this.healthBoard.isOn()) { + this.healthBoard.toggle(false); + } + } else { + // Else if player is in survival/adventure and board is off, turn it on + if (!this.healthBoard.isOn()) { + this.healthBoard.toggle(true); + } + } + + // Refresh board options + this.hungerEnabled = playerData.isInfoDisplayed(Info.HUNGER); + this.thirstEnabled = playerData.isInfoDisplayed(Info.THIRST); + this.energyEnabled = playerData.isInfoDisplayed(Info.ENERGY); + this.nutrientsEnabled = playerData.isInfoDisplayed(Info.NUTRIENTS); + + // If all options on the board are disabled, turn board off + if (!hungerEnabled && !thirstEnabled && !energyEnabled && !nutrientsEnabled) { + if (this.healthBoard.isOn()) { + this.healthBoard.toggle(false); + } + return; + } + + if (this.hungerEnabled) { + List hunger = this.playerManager.getHungerVisual(this.player); + this.healthBoard.setLine(1, hunger.get(0)); + this.healthBoard.setLine(2, hunger.get(1)); + this.healthBoard.setLine(3, hunger.get(2)); + this.healthBoard.setLine(4, ""); + } else { + this.healthBoard.deleteLine(1); + this.healthBoard.deleteLine(2); + this.healthBoard.deleteLine(3); + this.healthBoard.deleteLine(4); + } + + if (config.mechanics_thirst_enabled && thirstEnabled) { + List thirst = this.playerManager.getThirstVisual(this.player); + this.healthBoard.setLine(5, thirst.get(0)); + this.healthBoard.setLine(6, thirst.get(1)); + this.healthBoard.setLine(7, thirst.get(2)); + this.healthBoard.setLine(8, ""); + } else { + this.healthBoard.deleteLine(5); + this.healthBoard.deleteLine(6); + this.healthBoard.deleteLine(7); + this.healthBoard.deleteLine(8); + } + + if (config.mechanics_energy_enabled && energyEnabled) { + this.healthBoard.setLine(9, this.playerManager.getEnergyVisual(this.player).get(0)); + this.healthBoard.setLine(10, this.playerManager.getEnergyVisual(this.player).get(1)); + this.healthBoard.setLine(11, ""); + } else { + this.healthBoard.deleteLine(9); + this.healthBoard.deleteLine(10); + this.healthBoard.deleteLine(11); + } + + if (config.mechanics_food_diversity_enabled && nutrientsEnabled) { + List nutrients = this.playerManager.getNutrientsVisual(this.player); + this.healthBoard.setLine(12, nutrients.get(0), nutrients.get(3)); + this.healthBoard.setLine(13, nutrients.get(1), nutrients.get(4)); + this.healthBoard.setLine(14, nutrients.get(2), nutrients.get(5)); + } else { + this.healthBoard.deleteLine(12); + this.healthBoard.deleteLine(13); + this.healthBoard.deleteLine(14); + } + this.healthBoard.update(); + } + + @Override + public synchronized void cancel() throws IllegalStateException { + super.cancel(); + this.plugin.getScoreboardManager().removeBoard(this.player); + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/tasks/NutrientsAlert.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/NutrientsAlert.java new file mode 100644 index 0000000..07e90ee --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/NutrientsAlert.java @@ -0,0 +1,47 @@ +package com.shanebeestudios.survival.plugin.tasks; + +import com.shanebeestudios.survival.api.data.Nutrient; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +class NutrientsAlert extends BukkitRunnable { + + private final Lang lang; + private final PlayerManager playerManager; + + NutrientsAlert(SurvivalPlugin plugin) { + this.lang = plugin.getLang(); + final int ALERT_INTERVAL = plugin.getSurvivalConfig().MECHANICS_ALERT_INTERVAL; + this.playerManager = plugin.getPlayerManager(); + this.runTaskTimer(plugin, -1, ALERT_INTERVAL * 20L); + } + + @Override + public void run() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { + PlayerData playerData = playerManager.getPlayerData(player); + + if (playerData.getNutrient(Nutrient.CARBS) <= 480) { + Utils.sendColoredMini(player, "", this.lang.carbohydrates_lack); + } + + if (playerData.getNutrient(Nutrient.VITAMINS) <= 180) { + Utils.sendColoredMini(player, "", this.lang.vitamins_lack); + } + + if (playerData.getNutrient(Nutrient.PROTEIN) <= 120) { + Utils.sendColoredMini(player, "", this.lang.protein_lack); + } + } + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/tasks/NutrientsEffect.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/NutrientsEffect.java new file mode 100644 index 0000000..dc29eb1 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/NutrientsEffect.java @@ -0,0 +1,133 @@ +package com.shanebeestudios.survival.plugin.tasks; + +import com.shanebeestudios.survival.api.data.Nutrient; +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.Nullable; + +class NutrientsEffect extends BukkitRunnable { + + private final Config config; + private final PlayerManager playerManager; + private PotionEffect VITAMINS_NORMAL = null; + private PotionEffect VITAMINS_HARD = null; + private PotionEffect PROTEIN_NORMAL = null; + private PotionEffect PROTEIN_HARD = null; + + NutrientsEffect(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + this.playerManager = plugin.getPlayerManager(); + loadEffects(); + this.runTaskTimer(plugin, -1, 320); + } + + @Override + public void run() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getGameMode() != GameMode.SURVIVAL && player.getGameMode() != GameMode.ADVENTURE) continue; + + World world = player.getWorld(); + PlayerData playerData = playerManager.getPlayerData(player); + + if (playerData.getNutrient(Nutrient.CARBS) <= 0) { + switch (world.getDifficulty()) { + case EASY: + player.setExhaustion(player.getExhaustion() + Math.max(this.config.mechanics_food_effects_carbs_ex_amp_easy, 0)); + break; + case NORMAL: + player.setExhaustion(player.getExhaustion() + Math.max(this.config.mechanics_food_effects_carbs_ex_amp_medium, 0)); + break; + case HARD: + player.setExhaustion(player.getExhaustion() + Math.max(this.config.mechanics_food_effects_carbs_ex_amp_hard, 0)); + break; + default: + } + } + + if (playerData.getNutrient(Nutrient.VITAMINS) <= 0) { + player.setExhaustion(player.getExhaustion() + Math.max(this.config.mechanics_food_effects_vitamins_ex_amp, 0)); + switch (world.getDifficulty()) { + case NORMAL: + if (VITAMINS_NORMAL != null) { + player.addPotionEffect(VITAMINS_NORMAL); + } + break; + case HARD: + if (VITAMINS_HARD != null) { + player.addPotionEffect(VITAMINS_HARD); + } + break; + default: + } + } + + if (playerData.getNutrient(Nutrient.PROTEIN) <= 0) { + player.setExhaustion(player.getExhaustion() + Math.max(config.mechanics_food_effects_protein_ex_amp, 0)); + switch (world.getDifficulty()) { + case NORMAL: + if (PROTEIN_NORMAL != null) { + player.addPotionEffect(PROTEIN_NORMAL); + } + break; + case HARD: + if (PROTEIN_HARD != null) { + player.addPotionEffect(PROTEIN_HARD); + } + break; + default: + } + } + } + } + + private void loadEffects() { + PotionEffectType vitamins_normal_type = getType(config.mechanics_food_effects_vitamins_se_normal_effect); + if (vitamins_normal_type != null) { + int vitamins_normal_amp = this.config.mechanics_food_effects_vitamins_se_normal_amp; + int vitamins_normal_dur = this.config.mechanics_food_effects_vitamins_se_normal_duration; + VITAMINS_NORMAL = new PotionEffect(vitamins_normal_type, vitamins_normal_dur * 20, vitamins_normal_amp, true, false, false); + } + PotionEffectType vitamins_hard_type = getType(config.mechanics_food_effects_vitamins_se_hard_effect); + if (vitamins_hard_type != null) { + int vitamins_hard_amp = this.config.mechanics_food_effects_vitamins_se_hard_amp; + int vitamins_hard_dur = this.config.mechanics_food_effects_vitamins_se_hard_duration; + VITAMINS_HARD = new PotionEffect(vitamins_hard_type, vitamins_hard_dur * 20, vitamins_hard_amp, true, false, false); + } + + PotionEffectType protein_normal_type = getType(config.mechanics_food_effects_protein_se_normal_effect); + if (protein_normal_type != null) { + int protein_normal_amp = this.config.mechanics_food_effects_protein_se_normal_amp; + int protein_normal_dur = this.config.mechanics_food_effects_protein_se_normal_duration; + PROTEIN_NORMAL = new PotionEffect(protein_normal_type, protein_normal_dur * 20, protein_normal_amp, true, false, false); + } + PotionEffectType protein_hard_type = getType(config.mechanics_food_effects_protein_se_hard_effect); + if (protein_hard_type != null) { + int protein_hard_amp = this.config.mechanics_food_effects_protein_se_hard_amp; + int protein_hard_dur = this.config.mechanics_food_effects_protein_se_hard_duration; + PROTEIN_HARD = new PotionEffect(protein_hard_type, protein_hard_dur * 20, protein_hard_amp, true, false, false); + } + } + + private @Nullable PotionEffectType getType(String potionType) { + NamespacedKey key = NamespacedKey.fromString(potionType); + if (key != null) { + PotionEffectType potionEffectType = Registry.EFFECT.get(key); + if (potionEffectType != null) return potionEffectType; + } + Utils.logMini("Invalid potion effect type: '%s'", potionType); + return null; + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/tasks/TaskManager.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/TaskManager.java new file mode 100644 index 0000000..89eedeb --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/TaskManager.java @@ -0,0 +1,36 @@ +package com.shanebeestudios.survival.plugin.tasks; + +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; + +/** + * Internal task manager + */ +public class TaskManager { + + public TaskManager(SurvivalPlugin plugin) { + final int alertInterval = plugin.getSurvivalConfig().MECHANICS_ALERT_INTERVAL; + Config config = plugin.getSurvivalConfig(); + if (config.mechanics_energy_enabled) { + new EnergyDrain(plugin); + } + if (config.mechanics_food_diversity_enabled) { + new NutrientsEffect(plugin); + if (!config.mechanics_status_scoreboard && alertInterval > 0) { + new NutrientsAlert(plugin); + } + } + + if (config.mechanics_weather_enabled) { + new WeatherTask(plugin); + } + // Thirst + if (config.mechanics_thirst_enabled) { + new ThirstTask(plugin); + if (!config.mechanics_status_scoreboard && alertInterval > 0) { + new ThirstAlert(plugin); + } + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/tasks/ThirstAlert.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/ThirstAlert.java new file mode 100644 index 0000000..809195e --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/ThirstAlert.java @@ -0,0 +1,41 @@ +package com.shanebeestudios.survival.plugin.tasks; + +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.api.util.Utils; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Lang; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +class ThirstAlert extends BukkitRunnable { + + private final PlayerManager playerManager; + private final Lang lang; + + ThirstAlert(SurvivalPlugin plugin) { + this.playerManager = plugin.getPlayerManager(); + this.lang = plugin.getLang(); + final int ALERT_INTERVAL = plugin.getSurvivalConfig().MECHANICS_ALERT_INTERVAL; + this.runTaskTimer(plugin, -1, ALERT_INTERVAL * 20L); + } + + @Override + public void run() { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { + PlayerData playerData = playerManager.getPlayerData(player); + int hunger = player.getFoodLevel(); + if (hunger <= 6) { + Utils.sendColoredMini(player, "" + this.lang.starved_eat); + } + if (playerData.getThirst() <= 6) { + Utils.sendColoredMini(player, "" + this.lang.dehydrated_drink); + } + } + } + } + +} diff --git a/src/main/java/com/shanebeestudios/survival/plugin/tasks/ThirstTask.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/ThirstTask.java new file mode 100644 index 0000000..6f52e8d --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/ThirstTask.java @@ -0,0 +1,65 @@ +package com.shanebeestudios.survival.plugin.tasks; + +import com.shanebeestudios.survival.api.data.PlayerData; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.plugin.managers.PlayerManager; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.block.Block; +import org.bukkit.damage.DamageSource; +import org.bukkit.damage.DamageType; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +@SuppressWarnings("UnstableApiUsage") +class ThirstTask extends BukkitRunnable { + + private final Config config; + private final PlayerManager playerManager; + private final DamageSource damageSource = DamageSource.builder(DamageType.DRY_OUT).build(); + + ThirstTask(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); + this.playerManager = plugin.getPlayerManager(); + this.runTaskTimer(plugin, 100, 100); + } + + @Override + public void run() { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (player.getGameMode() != GameMode.SURVIVAL && player.getGameMode() != GameMode.ADVENTURE) continue; + + PlayerData playerData = this.playerManager.getPlayerData(player); + World world = player.getWorld(); + Environment environment = world.getEnvironment(); + if (environment == Environment.NORMAL && world.isDayTime()) { + Block block = player.getLocation().getBlock(); + if (block.getTemperature() >= 1.5 && block.getLightLevel() >= 14) { + playerData.increaseThirst(-this.config.mechanics_thirst_heat_drain_rate); + } + } else if (environment == Environment.NETHER) { + playerData.increaseThirst(-this.config.mechanics_thirst_nether_drain_rate); + } + // Damage player when thirst is too low + if (playerData.getThirst() <= 0) { + switch (world.getDifficulty()) { + case EASY: + if (player.getHealth() > 10) + player.damage(this.config.mechanics_thirst_damage_rate, this.damageSource); + break; + case NORMAL: + if (player.getHealth() > 1) + player.damage(this.config.mechanics_thirst_damage_rate, this.damageSource); + break; + case HARD: + player.damage(this.config.mechanics_thirst_damage_rate, this.damageSource); + break; + } + } + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/tasks/WeatherTask.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/WeatherTask.java similarity index 53% rename from src/main/java/tk/shanebee/survival/tasks/WeatherTask.java rename to src/main/java/com/shanebeestudios/survival/plugin/tasks/WeatherTask.java index d139cb0..fd97bb6 100644 --- a/src/main/java/tk/shanebee/survival/tasks/WeatherTask.java +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/WeatherTask.java @@ -1,8 +1,8 @@ -package tk.shanebee.survival.tasks; +package com.shanebeestudios.survival.plugin.tasks; +import com.shanebeestudios.survival.api.data.Permissions; import org.bukkit.Bukkit; import org.bukkit.GameMode; -import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; @@ -13,31 +13,24 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.item.Item; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.plugin.config.Config; +import com.shanebeestudios.survival.api.item.Items; +@SuppressWarnings("BooleanMethodIsAlwaysInverted") public class WeatherTask extends BukkitRunnable { - private final double baseSpeed; - private final double rainSpeed; - private final double stormSpeed; - private final double snowSpeed; - private final double snowstormSpeed; + private final Config config; - public WeatherTask(Survival plugin) { - Config config = plugin.getSurvivalConfig(); - this.baseSpeed = config.MECHANICS_WEATHER_SPEED_BASE; - this.rainSpeed = config.MECHANICS_WEATHER_SPEED_RAIN; - this.stormSpeed = config.MECHANICS_WEATHER_SPEED_STORM; - this.snowSpeed = config.MECHANICS_WEATHER_SPEED_SNOW; - this.snowstormSpeed = config.MECHANICS_WEATHER_SPEED_SNOWSTORM; + public WeatherTask(SurvivalPlugin plugin) { + this.config = plugin.getSurvivalConfig(); this.runTaskTimer(plugin, 20, 10); } @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { + if (Permissions.BYPASS_WEATHER.has(player)) continue; handleWeather(player); } } @@ -47,18 +40,18 @@ private void handleWeather(Player player) { GameMode mode = player.getGameMode(); if (world.getEnvironment() == Environment.NORMAL && (mode == GameMode.SURVIVAL || mode == GameMode.ADVENTURE)) { if (isInSnowstorm(player) && !hasSnowBoots(player)) { - setWalkSpeed(player, snowstormSpeed); + setWalkSpeed(player, this.config.mechanics_weather_speed_snowstorm); } else if (isOnSnow(player) && !hasSnowBoots(player)) { - setWalkSpeed(player, snowSpeed); + setWalkSpeed(player, this.config.mechanics_weather_speed_snow); } else if (isInStorm(player) && !hasRainBoots(player)) { - setWalkSpeed(player, stormSpeed); - } else if (isInRain(player) && !hasRainBoots(player)) { - setWalkSpeed(player, rainSpeed); + setWalkSpeed(player, this.config.mechanics_weather_speed_storm); + } else if (player.isInRain() && !hasRainBoots(player)) { + setWalkSpeed(player, this.config.mechanics_weather_speed_rain); } else { - setWalkSpeed(player, baseSpeed); + setWalkSpeed(player, this.config.mechanics_weather_speed_base); } } else { - setWalkSpeed(player, baseSpeed); + setWalkSpeed(player, this.config.mechanics_weather_speed_base); } } @@ -78,35 +71,19 @@ private boolean isOnSnow(Player player) { private boolean isInSnowstorm(Player player) { World world = player.getWorld(); - double temp = player.getLocation().getBlock().getTemperature(); - - return world.hasStorm() && temp < 0.15 && isAtHighest(player); - } - - private boolean isInRain(Player player) { - World world = player.getWorld(); - double temp = player.getLocation().getBlock().getTemperature(); + Block block = player.getLocation().getBlock(); + double temp = block.getTemperature(); + byte lightFromSky = block.getLightFromSky(); - // is raining (0.15 – 0.95 for rain) - if (world.hasStorm() && temp >= 0.15 && temp <= 0.95) { - // sky is above - return isAtHighest(player); - } - return false; + return world.hasStorm() && temp < 0.15 && lightFromSky == 15; } private boolean isInStorm(Player player) { - return isInRain(player) && player.getWorld().isThundering(); - } - - private boolean isAtHighest(Player player) { - Location location = player.getLocation(); - World world = player.getWorld(); - return location.getY() > world.getHighestBlockAt(location).getY(); + return player.isInRain() && player.getWorld().isThundering(); } private void setWalkSpeed(Player player, double speed) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED); + AttributeInstance attribute = player.getAttribute(Attribute.MOVEMENT_SPEED); if (attribute != null) { attribute.setBaseValue(speed); } @@ -114,12 +91,12 @@ private void setWalkSpeed(Player player, double speed) { private boolean hasRainBoots(Player player) { ItemStack boots = player.getInventory().getBoots(); - return boots != null && Item.RAIN_BOOTS.compare(boots); + return boots != null && Items.RAIN_BOOTS.is(boots); } private boolean hasSnowBoots(Player player) { ItemStack boots = player.getInventory().getBoots(); - return boots != null && Item.SNOW_BOOTS.compare(boots); + return boots != null && Items.SNOW_BOOTS.is(boots); } } diff --git a/src/main/java/com/shanebeestudios/survival/plugin/tasks/tool/Valkyrie.java b/src/main/java/com/shanebeestudios/survival/plugin/tasks/tool/Valkyrie.java new file mode 100644 index 0000000..36a3f62 --- /dev/null +++ b/src/main/java/com/shanebeestudios/survival/plugin/tasks/tool/Valkyrie.java @@ -0,0 +1,31 @@ +package com.shanebeestudios.survival.plugin.tasks.tool; + +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import com.shanebeestudios.survival.plugin.SurvivalPlugin; +import com.shanebeestudios.survival.api.item.Items; + +public class Valkyrie extends BukkitRunnable { + + private final SurvivalPlugin plugin; + + public Valkyrie(SurvivalPlugin plugin) { + this.plugin = plugin; + this.runTaskTimer(plugin, 1, 10); + } + + @Override + public void run() { + for (Player player : this.plugin.getServer().getOnlinePlayers()) { + if (Items.VALKYRIES_AXE.is(player.getInventory().getItemInMainHand())) { + Location particleLoc = player.getLocation(); + particleLoc.setY(particleLoc.getY() + 1); + assert particleLoc.getWorld() != null; + particleLoc.getWorld().spawnParticle(Particle.CRIT, particleLoc, 10, 0.5, 0.5, 0.5); + } + } + } + +} diff --git a/src/main/java/tk/shanebee/survival/Survival.java b/src/main/java/tk/shanebee/survival/Survival.java deleted file mode 100644 index 8f2ed8c..0000000 --- a/src/main/java/tk/shanebee/survival/Survival.java +++ /dev/null @@ -1,400 +0,0 @@ -package tk.shanebee.survival; - -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.server.ServerLoadEvent; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scoreboard.Scoreboard; -import tk.shanebee.survival.commands.*; -import tk.shanebee.survival.config.PlayerDataConfig; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.listeners.EventManager; -import tk.shanebee.survival.managers.*; -import tk.shanebee.survival.metrics.Metrics; -import tk.shanebee.survival.tasks.TaskManager; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.*; - -@SuppressWarnings("ConstantConditions") -public class Survival extends JavaPlugin implements Listener { - - static { - ConfigurationSerialization.registerClass(PlayerData.class, "PlayerData"); - } - - private static Survival instance; - - // Lists & Maps - private final List Rates = new ArrayList<>(); - private final List chairBlocks = new ArrayList<>(); - private List usingPlayers = new ArrayList<>(); - private Map playerDataMap = new HashMap<>(); - - // Configs - private Config config; - private Lang lang; - private PlayerDataConfig playerDataConfig; - - // Scoreboards - private Scoreboard mainBoard; - - // Managers - private BlockManager blockManager; - private EffectManager effectManager; - private ScoreBoardManager scoreBoardManager; - private PlayerManager playerManager; - private TaskManager taskManager; - private MerchantManager merchantManager; - private RecipeManager recipeManager; - - // Other - private String prefix; - private boolean loaded = true; - private boolean snowGenOption = true; - - public void onEnable() { - instance = this; - long time = System.currentTimeMillis(); - - // VERSION CHECK - if (!Utils.isRunningMinecraft(1, 16)) { - String ver = Bukkit.getServer().getBukkitVersion().split("-")[0]; - Utils.log("&c-----------------------------------------------------------"); - Utils.log("&cYour version is not supported: &b" + ver); - Utils.log("&eThis plugin only works on Minecraft &b1.16+"); - Utils.log("&c-----------------------------------------------------------"); - loaded = false; - Bukkit.getPluginManager().disablePlugin(this); - return; - } - - // SPIGOT CHECK - if (!Utils.isRunningSpigot()) { - Utils.log("&c-----------------------------------------------------------"); - Utils.log("&7Your server software is not supported: &c" + Bukkit.getName()); - Utils.log("&7This plugin will only work on &aSpigot &7or &aPaper."); - Utils.log("&c-----------------------------------------------------------"); - loaded = false; - Bukkit.getPluginManager().disablePlugin(this); - return; - } - - // LOAD CONFIG FILES - loadSettings(Bukkit.getConsoleSender()); - - for (World world : getServer().getWorlds()) { - world.setGameRule(GameRule.DO_LIMITED_CRAFTING, config.SURVIVAL_LIMITED_CRAFTING); - } - - // LOAD RESOURCE PACK - String url = config.RESOURCE_PACK_URL; - boolean resourcePack = config.RESOURCE_PACK_ENABLED; - if (resourcePack) { - if (url.isEmpty()) { - Utils.log("&cResource Pack is not set! Plugin disabling"); - Bukkit.getPluginManager().disablePlugin(this); - return; - } else { - Utils.log("&7Resource pack &aenabled"); - } - } else Utils.log("&eResource Pack disabled"); - - Rates.add(config.DROP_RATE_FLINT); - Rates.add(config.DROP_RATE_STICK); - Rates.add(config.MECHANICS_THIRST_DRAIN_RATE); - for (double i : Rates) { - if (i <= 0) { - Utils.log("&cRate values cannot be zero or below! (Check config.yml) Plugin disabled."); - Bukkit.getPluginManager().disablePlugin(this); - return; - } else if (i > 1) { - Utils.log("&cRate values cannot be above 1! (Check config.yml) Plugin disabled."); - Bukkit.getPluginManager().disablePlugin(this); - return; - } - } - - // LOAD SCOREBOARDS - mainBoard = Bukkit.getScoreboardManager().getMainScoreboard(); - - // LOAD MANAGERS - blockManager = new BlockManager(this); - playerManager = new PlayerManager(this, playerDataMap); - effectManager = new EffectManager(this); - taskManager = new TaskManager(this); - scoreBoardManager = new ScoreBoardManager(this); - merchantManager = new MerchantManager(this); - recipeManager = new RecipeManager(this); - - // LOAD PLAYER DATA - (during a reload if players are still online) - playerDataLoader(true); - scoreBoardManager.resetStatusScoreboard(config.MECHANICS_STATUS_SCOREBOARD); - - // LOAD PLACEHOLDERS - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { - new Placeholders(this).register(); - Utils.log("&7PlaceholderAPI placeholders &aenabled"); - } - - // REGISTER EVENTS & COMMANDS - registerCommands(); - EventManager eventManager = new EventManager(this); - eventManager.registerEvents(); - - // LOAD CUSTOM RECIPES - // This is a helper for other plugins that wipe custom recipes - secret hidden config - if (config.RECIPE_DELAY > 0) { - Utils.log("&7Custom recipe loading delayed... will load in &b" + config.RECIPE_DELAY + "&7 second[s]"); - Bukkit.getScheduler().runTaskLater(this, () -> { - this.recipeManager.loadCustomRecipes(); - Utils.log("&7Custom recipes &aloaded"); - }, config.RECIPE_DELAY * 20L); - - } else { - this.recipeManager.loadCustomRecipes(); - Utils.log("&7Custom recipes &aloaded"); - } - - // LOAD METRICS - Metrics metrics = new Metrics(this); - Utils.log("&7Metrics " + (metrics.isEnabled() ? "&aenabled" : "&cdisabled")); - - Utils.log("&aSuccessfully loaded &7in " + (System.currentTimeMillis() - time) + " milliseconds"); - - // BETA WARNING - if (this.getDescription().getVersion().contains("Beta")) { - Utils.log("&eYOU ARE RUNNING A BETA VERSION, PLEASE USE WITH CAUTION!"); - } - } - - public void onDisable() { - if (!loaded) return; - Utils.log("&eShutting down"); - getServer().getScheduler().cancelTasks(this); - //getServer().resetRecipes(); <-- why is this even here? - usingPlayers = new ArrayList<>(); - - // Remove limited crafting when server shuts down (important if server removes this plugin) - for (World world : getServer().getWorlds()) { - world.setGameRule(GameRule.DO_LIMITED_CRAFTING, false); - } - - // Unload player data (decrease chance of memory leak) - playerDataLoader(false); - - //Avoid WorkbenchShare glitch - if (config.MECHANICS_SHARED_WORKBENCH) { - for (Player p : Bukkit.getOnlinePlayers()) { - if (p.hasMetadata("shared_workbench")) { - Block workbench = (p.getMetadata("shared_workbench").get(0).value() instanceof Block) ? (Block) - p.getMetadata("shared_workbench").get(0).value() : null; - - if (workbench != null && workbench.getType() == Material.CRAFTING_TABLE) { - if (workbench.hasMetadata("shared_players")) - workbench.removeMetadata("shared_players", Survival.instance); - else - p.getOpenInventory().getTopInventory().clear(); - p.closeInventory(); - } - p.removeMetadata("shared_workbench", Survival.instance); - } - } - } - Utils.log("&eSuccessfully disabled"); - } - - private void playerDataLoader(boolean load) { - int size = Bukkit.getOnlinePlayers().size(); - if (load) { - // Load player data - if players are online (useful during reload) - for (Player player : Bukkit.getOnlinePlayers()) { - if (playerDataConfig.hasPlayerDataFile(player)) { - playerManager.loadPlayerData(player); - } else { - playerManager.createNewPlayerData(player); - } - } - if (size > 0) { - Utils.log("Loading player data for &b" + size + " player" + (size != 1 ? "s" : "")); - } - } else { - // Unload player data - if players are still online - for (Player player : Bukkit.getOnlinePlayers()) { - playerManager.unloadPlayerData(player); - } - // Clear/delete player data map to prevent memory leaks - playerDataMap.clear(); - playerDataMap = null; - Utils.log("Unloading player data for &b" + size + " player" + (size != 1 ? "s" : "")); - } - } - - /** - * Load config settings - * @param sender The person/console loading config - */ - public void loadSettings(CommandSender sender) { - this.config = new Config(this); - this.lang = new Lang(this, config.LANG); - this.lang.loadLangFile(sender); - this.prefix = lang.prefix; - for (String type : config.MECHANICS_CHAIRS_BLOCKS) { - Material mat = Material.getMaterial(type); - if (mat != null) { - chairBlocks.add(mat); - } else { - Utils.log("&cInvalid chair block material: &7" + type); - } - } - this.playerDataConfig = new PlayerDataConfig(this); - } - - @EventHandler - private void onServerReload(ServerLoadEvent e) { - if (e.getType() == ServerLoadEvent.LoadType.RELOAD) { - for (Player player : getServer().getOnlinePlayers()) { - Utils.sendColoredMsg(player, prefix + "&cDETECTED SERVER RELOAD"); - Utils.sendColoredMsg(player, " &6Recipes may have been impacted"); - Utils.sendColoredMsg(player, " &6Relog to update your recipes"); - } - Utils.sendColoredConsoleMsg(prefix + "&cDETECTED SERVER RELOAD"); - Utils.sendColoredConsoleMsg(" &7- &6Server reloads will impact recipes"); - Utils.sendColoredConsoleMsg(" &7- &6Players will need to relog to re-enable custom recipes"); - Utils.sendColoredConsoleMsg(" &7- &6A warning has been sent to each player that is online right now"); - } - } - - private void registerCommands() { - String noPerm = Utils.getColoredString(prefix + lang.no_perm); - getCommand("recipes").setExecutor(new Recipes()); - getCommand("togglechat").setExecutor(new ToggleChat(this)); - getCommand("togglechat").setPermissionMessage(noPerm); - getCommand("status").setExecutor(new Status(this)); - getCommand("reload-survival").setExecutor(new Reload(this)); - getCommand("reload-survival").setPermissionMessage(noPerm); - if (config.MECHANICS_SNOW_GEN_REVAMP) { - getCommand("snowgen").setExecutor(new SnowGen(this)); - getCommand("snowgen").setPermissionMessage(noPerm); - } - getCommand("giveitem").setExecutor(new GiveItem(this)); - getCommand("giveitem").setPermissionMessage(noPerm); - getCommand("nutrition").setExecutor(new Nutrition(this)); - getCommand("nutrition").setPermissionMessage(noPerm); - getCommand("heal").setExecutor(new Heal(this)); - getCommand("heal").setPermissionMessage(noPerm); - getCommand("playerdata").setExecutor(new PlayerDataCmd(this)); - getCommand("playerdata").setPermissionMessage(noPerm); - } - - /** Get instance of this plugin - * @return Instance of this plugin - */ - public static Survival getInstance() { - return instance; - } - - /** Get the block manager - * @return Instance of the block manager - */ - public BlockManager getBlockManager() { - return this.blockManager; - } - - /** Get the effect manager - * @return Instance of the effect manager - */ - public EffectManager getEffectManager() { - return this.effectManager; - } - - /** Get the scoreboard manager - * @return Instance of the scoreboard manager - */ - public ScoreBoardManager getScoreboardManager() { - return this.scoreBoardManager; - } - - /** Get the player manager - * @return Instance of the player manager - */ - public PlayerManager getPlayerManager() { - return this.playerManager; - } - - /** Get the task manager - * @return Instance of the task manager - */ - @SuppressWarnings("unused") - public TaskManager getTaskManager() { - return this.taskManager; - } - - /** Get an instance of the merchant manager - * @return Instance of the merchant manager - */ - public MerchantManager getMerchantManager() { - return merchantManager; - } - - /** Get an instance of the recipe manager - * @return Instance of recipe manager - */ - public RecipeManager getRecipeManager() { - return recipeManager; - } - - /** Get the main SurvivalPlus config - * @return SurvivalPlus config - */ - public Config getSurvivalConfig() { - return this.config; - } - - /** Get an instance of the language config - * @return Language config - */ - public Lang getLang() { - return lang; - } - - /** Get the main server scoreboard - * @return Main server scoreboard - */ - public Scoreboard getMainBoard() { - return mainBoard; - } - - public boolean isSnowGenOption() { - return snowGenOption; - } - - public void setSnowGenOption(boolean snowGenOption) { - this.snowGenOption = snowGenOption; - } - - /** Get acceptable chair blocks - * @return List of chair blocks - */ - public List getChairBlocks() { - return chairBlocks; - } - - /** Get a list of players using the plugin's resource pack - * @return List of players using the plugin's resource pack - */ - public List getUsingPlayers() { - return usingPlayers; - } - - public PlayerDataConfig getPlayerDataConfig() { - return playerDataConfig; - } -} diff --git a/src/main/java/tk/shanebee/survival/commands/GiveItem.java b/src/main/java/tk/shanebee/survival/commands/GiveItem.java deleted file mode 100644 index d5dcfbf..0000000 --- a/src/main/java/tk/shanebee/survival/commands/GiveItem.java +++ /dev/null @@ -1,93 +0,0 @@ -package tk.shanebee.survival.commands; - -import com.google.common.collect.ImmutableList; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.StringUtil; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -@SuppressWarnings("NullableProblems") -public class GiveItem implements CommandExecutor, TabCompleter { - - private final Lang lang; - - public GiveItem(Survival plugin) { - this.lang = plugin.getLang(); - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { - String prefix = Utils.getColoredString(lang.prefix); - if (args.length < 2) return true; - Player player = Bukkit.getPlayer(args[0]); - if (player != null) { - Item item; - int amount = 1; - try { - if (args.length == 3) { - amount = Integer.parseInt(args[2]); - } - } catch (IllegalArgumentException ignore) {} - try { - item = Item.valueOf(args[1].toUpperCase()); - ItemStack itemStack = ItemManager.get(item); - itemStack.setAmount(amount); - - Location loc = player.getLocation(); - loc.setY(loc.getY() + 1); - - if (player.getInventory().addItem(itemStack).size() != 0) { - player.getWorld().dropItem(loc, itemStack); - } - if (item != null) { - String itemName = item.getKey().replace("_", " "); - if (sender instanceof Player) { - Utils.sendColoredMsg(sender, prefix + "&6You gave &b" + itemName + " &6to &b" + player.getName()); - } else { - Utils.sendColoredMsg(sender, prefix + "&6CONSOLE gave &b" + itemName + " &6to &b" + player.getName()); - } - } - } catch (IllegalArgumentException ignore) { - Utils.sendColoredMsg(sender, prefix + "&b" + args[1] + "&c is not an item"); - } - } else { - Utils.sendColoredMsg(sender, prefix + "&b" + args[0] + " &cis not online"); - } - return true; - } - - @Override - public List onTabComplete(CommandSender sender, Command command, String s, String[] args) { - if (args.length == 0 || args.length >= 4) { - return ImmutableList.of(); - } - if (args.length <= 1) return null; - if (args.length == 2) { - ArrayList matches = new ArrayList<>(); - for (Item item : Item.values()) { - String name = item.getKey().toUpperCase(); - if (StringUtil.startsWithIgnoreCase(name, args[1])) { - matches.add(name); - } - } - return matches; - } else { - return Collections.singletonList(""); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/Heal.java b/src/main/java/tk/shanebee/survival/commands/Heal.java deleted file mode 100644 index 8958e12..0000000 --- a/src/main/java/tk/shanebee/survival/commands/Heal.java +++ /dev/null @@ -1,87 +0,0 @@ -package tk.shanebee.survival.commands; - -import org.bukkit.Bukkit; -import org.bukkit.attribute.Attribute; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.util.Utils; - -public class Heal implements CommandExecutor { - - private final Survival plugin; - private final Config config; - private final Lang lang; - - public Heal(Survival plugin) { - this.plugin = plugin; - this.config = plugin.getSurvivalConfig(); - this.lang = plugin.getLang(); - } - - @SuppressWarnings("NullableProblems") - @Override - public boolean onCommand(CommandSender sender, Command cmd, String s, String[] args) { - if (args.length > 0) { - if (!sender.hasPermission("survivalplus.heal.others")) { - sender.sendMessage(plugin.getLang().no_perm); - return true; - } - Player healed = Bukkit.getPlayer(args[0]); - if (healed == null) { - Utils.sendColoredMsg(sender, lang.cmd_player_not_online.replace("", args[0])); - return true; - } - heal(healed); - Utils.sendColoredMsg(sender, lang.cmd_heal_other.replace("", args[0])); - Utils.sendColoredMsg(healed, lang.cmd_heal_by.replace("", sender.getName())); - } else { - if (sender instanceof Player) { - heal(((Player) sender)); - Utils.sendColoredMsg(sender, lang.cmd_heal_self); - } else { - Utils.log("&cConsole can not heal itself!"); - return true; - } - } - return true; - } - - @SuppressWarnings("ConstantConditions") - private void heal(Player player) { - player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()); - player.setFoodLevel(20); - player.setSaturation(5); - PlayerData playerData = plugin.getPlayerManager().getPlayerData(player); - if (config.MECHANICS_THIRST_ENABLED) { - playerData.setThirst(40); - } - if (config.MECHANICS_FOOD_DIVERSITY_ENABLED) { - switch (player.getWorld().getDifficulty()) { - case PEACEFUL: - case EASY: - playerData.setNutrients( 960, 240, 360); - break; - case NORMAL: - playerData.setNutrients( 480, 120, 180); - break; - case HARD: - playerData.setNutrients( 96, 24, 36); - break; - } - } - if (config.MECHANICS_ENERGY_ENABLED) { - playerData.setEnergy(20.0); - } - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/Nutrition.java b/src/main/java/tk/shanebee/survival/commands/Nutrition.java deleted file mode 100644 index 82f2cff..0000000 --- a/src/main/java/tk/shanebee/survival/commands/Nutrition.java +++ /dev/null @@ -1,47 +0,0 @@ -package tk.shanebee.survival.commands; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.gui.NutritionGUI; -import tk.shanebee.survival.util.Utils; - -public class Nutrition implements CommandExecutor { - - private final Survival plugin; - - public Nutrition(Survival plugin) { - this.plugin = plugin; - } - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) { - if (sender instanceof Player) { - Player player = ((Player) sender); - NutritionGUI gui = new NutritionGUI(this.plugin); - gui.openInventory(player, 0); - } else { - if (args.length == 1 && args[0].equalsIgnoreCase("debug")) { - itemTest(); - return true; - } - Utils.log("&cThis is a player only command!"); - } - return true; - } - - // Used for debugging edible items - private void itemTest() { - tk.shanebee.survival.item.Nutrition.getAllNutritions().forEach(nutrition -> { - String key = nutrition.getKey().toString().replace(":", "&r:&a"); - String item = nutrition.getItemStack().toString().replace("{", "&r{&b").replace("}", "&r}&b"); - Utils.log("Nutrition%s:", nutrition.isCustom() ? "&r(&cCUSTOM&r)&7" : ""); - Utils.log(" - Key: &a%s", key); - Utils.log(" - Item: &e%s", item); - }); - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/PlayerDataCmd.java b/src/main/java/tk/shanebee/survival/commands/PlayerDataCmd.java deleted file mode 100644 index faf90e0..0000000 --- a/src/main/java/tk/shanebee/survival/commands/PlayerDataCmd.java +++ /dev/null @@ -1,104 +0,0 @@ -package tk.shanebee.survival.commands; - -import com.google.common.collect.ImmutableList; -import org.apache.commons.lang.math.NumberUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.data.PlayerData.DataType; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.util.Utils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class PlayerDataCmd implements TabExecutor { - - private final PlayerManager playerManager; - - public PlayerDataCmd(Survival plugin) { - this.playerManager = plugin.getPlayerManager(); - } - - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - // command player (add/set/remove) stat amount - if (args.length != 4) { - return false; - } - Player player = Bukkit.getPlayer(args[0]); - if (player == null) { - Utils.sendColoredMsg(sender, "&cPlayer &b" + args[0] + "&c is not online!"); - return true; - } - PlayerData playerData = playerManager.getPlayerData(player); - if (playerData == null) { - Utils.sendColoredMsg(sender, "&cInvalid player data for &b" + args[0]); - return true; - } - - String changer = args[1]; - if (!changer.equalsIgnoreCase("set") && !changer.equalsIgnoreCase("add") && !changer.equalsIgnoreCase("remove")) { - return false; - } - - if (!NumberUtils.isNumber(args[3])) { - return false; - } - double value = Double.parseDouble(args[3]); - DataType dataType = DataType.getByName(args[2]); - if (dataType == null) { - return false; - } - - switch (args[1]) { - case "add": - value = value + playerData.getData(dataType); - break; - case "remove": - value = playerData.getData(dataType) - value; - break; - } - playerData.setData(dataType, value); - - return true; - } - - private final String[] DATA_TYPES = PlayerData.DataType.getNames(); - private final String[] CHANGE = new String[]{"add", "set", "remove"}; - - @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - if (args.length == 1) { - return null; // return player names - } else if (args.length == 2) { - List matches = new ArrayList<>(); - for (String name : CHANGE) { - if (StringUtil.startsWithIgnoreCase(name, args[1])) { - matches.add(name); - } - } - return matches; - } else if (args.length == 3) { - List matches = new ArrayList<>(); - for (String name : DATA_TYPES) { - if (StringUtil.startsWithIgnoreCase(name, args[2])) { - matches.add(name); - } - } - return matches; - } else if (args.length == 4) { - return Collections.singletonList(""); - } - return ImmutableList.of(); // Return nothing - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/Recipes.java b/src/main/java/tk/shanebee/survival/commands/Recipes.java deleted file mode 100644 index b2db348..0000000 --- a/src/main/java/tk/shanebee/survival/commands/Recipes.java +++ /dev/null @@ -1,23 +0,0 @@ -package tk.shanebee.survival.commands; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import tk.shanebee.survival.util.Utils; - -public class Recipes implements CommandExecutor { - - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - String prefix = "&7[&3SurvivalPlus&7] "; - if (!(sender instanceof Player)) { - Utils.sendColoredConsoleMsg(prefix + "&cPlayer only command"); - return true; - } - Player player = (Player) sender; - Utils.sendColoredMsg(player, prefix + "&6Recipes"); - Utils.sendColoredMsg(player, " &7Recipes can be found in your crafting guide in your inventory/crafting table"); - return true; - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/Reload.java b/src/main/java/tk/shanebee/survival/commands/Reload.java deleted file mode 100644 index 35fe145..0000000 --- a/src/main/java/tk/shanebee/survival/commands/Reload.java +++ /dev/null @@ -1,26 +0,0 @@ -package tk.shanebee.survival.commands; - -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -public class Reload implements CommandExecutor { - - private final Survival plugin; - private final Lang lang; - - public Reload(Survival plugin) { - this.plugin = plugin; - this.lang = plugin.getLang(); - } - - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - plugin.loadSettings(sender); - Utils.sendColoredMsg(sender, lang.prefix + "&aReload complete"); - return true; - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/SnowGen.java b/src/main/java/tk/shanebee/survival/commands/SnowGen.java deleted file mode 100644 index 5d94e04..0000000 --- a/src/main/java/tk/shanebee/survival/commands/SnowGen.java +++ /dev/null @@ -1,83 +0,0 @@ -package tk.shanebee.survival.commands; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; -import org.bukkit.World; -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 tk.shanebee.survival.Survival; -import tk.shanebee.survival.listeners.block.SnowGeneration; - -public class SnowGen implements CommandExecutor { - - private final Survival plugin; - private final String prefix = ChatColor.translateAlternateColorCodes('&', "&7[&3SurvivalPlus&7] "); - - public SnowGen(Survival plugin) { - this.plugin = plugin; - } - - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (args.length == 1) { - switch (args[0].toLowerCase()) { - case "on": - plugin.setSnowGenOption(true); - break; - case "off": - plugin.setSnowGenOption(false); - break; - default: - return false; - } - if (sender instanceof Player) { - sender.sendMessage(ChatColor.AQUA + prefix + ChatColor.YELLOW + "Snow Generation is " + args[0].toLowerCase()); - sender.getServer().getConsoleSender().sendMessage(prefix + ChatColor.YELLOW + "Snow Generation is " + args[0].toLowerCase()); - } else if (sender instanceof ConsoleCommandSender) { - sender.sendMessage(prefix + ChatColor.YELLOW + "Snow Generation is " + args[0].toLowerCase()); - } - return true; - } else if (args.length == 0) { - if (Bukkit.getServer().getOnlinePlayers().size() <= 1) { - if (sender instanceof Player) { - sender.sendMessage(ChatColor.AQUA + prefix + ChatColor.RED + "WARNING!" + ChatColor.YELLOW + " Snow Generation is running for generated chunks!"); - sender.getServer().getConsoleSender().sendMessage(prefix + ChatColor.RED + "WARNING!" + ChatColor.YELLOW + " Snow Generation is running for generated chunks!"); - } else if (sender instanceof ConsoleCommandSender) { - sender.sendMessage(prefix + ChatColor.RED + "WARNING!" + ChatColor.YELLOW + " Snow Generation is running for generated chunks!"); - } - - SnowGeneration snowGen = new SnowGeneration(plugin); - - for (final World world : Bukkit.getServer().getWorlds()) { - for (final Chunk chunk : world.getLoadedChunks()) { - snowGen.checkChunk(chunk); - } - } - - if (sender instanceof Player) { - sender.sendMessage(ChatColor.AQUA + prefix + ChatColor.GREEN + "Snow Generation is completed."); - sender.getServer().getConsoleSender().sendMessage(prefix + ChatColor.GREEN + "Snow Generation is completed."); - } else if (sender instanceof ConsoleCommandSender) { - sender.sendMessage(prefix + ChatColor.GREEN + "Snow Generation is completed."); - } - - return true; - } else { - if (sender instanceof Player) { - sender.sendMessage(ChatColor.AQUA + prefix + ChatColor.RED + "WARNING!" + ChatColor.YELLOW + " Snow Generation will run through all generated chunks, lag spikes may occur!"); - sender.sendMessage(ChatColor.AQUA + prefix + ChatColor.YELLOW + "Run this command while nobody is in the server."); - } else if (sender instanceof ConsoleCommandSender) { - sender.sendMessage(prefix + ChatColor.RED + "WARNING!" + ChatColor.YELLOW + " Snow Generation will run through all generated chunks, lag spikes may occur!"); - sender.sendMessage(prefix + ChatColor.YELLOW + "Run this command while nobody is in the server."); - } - - return false; - } - } - return false; - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/Status.java b/src/main/java/tk/shanebee/survival/commands/Status.java deleted file mode 100644 index a712911..0000000 --- a/src/main/java/tk/shanebee/survival/commands/Status.java +++ /dev/null @@ -1,169 +0,0 @@ -package tk.shanebee.survival.commands; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.Info; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.ArrayList; -import java.util.List; - -@SuppressWarnings("NullableProblems") -public class Status implements CommandExecutor, TabCompleter { - - private final Config config; - private final Lang lang; - private final PlayerManager playerManager; - - public Status(Survival plugin) { - this.config = plugin.getSurvivalConfig(); - this.lang = plugin.getLang(); - this.playerManager = plugin.getPlayerManager(); - } - - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (command.getName().equalsIgnoreCase("status")) { - if (!(sender instanceof Player)) { - sender.sendMessage(Utils.getColoredString(lang.players_only)); - return false; - } - - Player player = (Player) sender; - PlayerData playerData = playerManager.getPlayerData(player); - - if (args.length == 0) { - if (!config.MECHANICS_STATUS_SCOREBOARD) { - player.sendMessage(playerManager.ShowHunger(player).get(1) + - playerManager.ShowHunger(player).get(2) + " " + - playerManager.ShowHunger(player).get(0).toUpperCase()); - if (config.MECHANICS_THIRST_ENABLED) - player.sendMessage(playerManager.ShowThirst(player).get(1) + - playerManager.ShowThirst(player).get(2) + " " + - playerManager.ShowThirst(player).get(0).toUpperCase()); - } else { - sendHelp(player); - } - } - - if (args.length == 1) { - switch (args[0]) { - case "all": - if (!config.MECHANICS_STATUS_SCOREBOARD) { - player.sendMessage(playerManager.ShowHunger(player).get(1) + - playerManager.ShowHunger(player).get(2) + " " + - playerManager.ShowHunger(player).get(0).toUpperCase()); - if (config.MECHANICS_THIRST_ENABLED) - player.sendMessage(playerManager.ShowThirst(player).get(1) + - playerManager.ShowThirst(player).get(2) + " " + - playerManager.ShowThirst(player).get(0).toUpperCase()); - if (config.MECHANICS_ENERGY_ENABLED) - player.sendMessage(playerManager.showEnergy(player).get(1) + - " " + playerManager.showEnergy(player).get(0).toUpperCase()); - if (config.MECHANICS_FOOD_DIVERSITY_ENABLED) { - for (String s : playerManager.ShowNutrients(player)) - player.sendMessage(s); - } - } else { - playerData.setInfoDisplayed(Info.HUNGER, true); - if (config.MECHANICS_THIRST_ENABLED) - playerData.setInfoDisplayed(Info.THIRST, true); - if (config.MECHANICS_ENERGY_ENABLED) - playerData.setInfoDisplayed(Info.ENERGY, true); - if (config.MECHANICS_FOOD_DIVERSITY_ENABLED) - playerData.setInfoDisplayed(Info.NUTRIENTS, true); - } - break; - case "none": - case "off": - playerData.setInfoDisplayed(Info.HUNGER, false); - playerData.setInfoDisplayed(Info.THIRST, false); - playerData.setInfoDisplayed(Info.ENERGY, false); - playerData.setInfoDisplayed(Info.NUTRIENTS, false); - break; - case "hunger": - case "h": - if (!config.MECHANICS_STATUS_SCOREBOARD) { - player.sendMessage(playerManager.ShowHunger(player).get(1) + - playerManager.ShowHunger(player).get(2) + " " + - playerManager.ShowHunger(player).get(0).toUpperCase()); - } else - playerData.setInfoDisplayed(Info.HUNGER, !playerData.isInfoDisplayed(Info.HUNGER)); - break; - case "thirst": - case "t": - if (!config.MECHANICS_STATUS_SCOREBOARD) { - if (config.MECHANICS_THIRST_ENABLED) - player.sendMessage(playerManager.ShowThirst(player).get(1) + - playerManager.ShowThirst(player).get(2) + " " + - playerManager.ShowThirst(player).get(0).toUpperCase()); - } else - playerData.setInfoDisplayed(Info.THIRST, !playerData.isInfoDisplayed(Info.THIRST)); - break; - case "fatigue": - case "f": - case "energy": - case "e": - if (!config.MECHANICS_STATUS_SCOREBOARD) { - if (config.MECHANICS_ENERGY_ENABLED) - player.sendMessage(playerManager.showEnergy(player).get(1) + - " " + playerManager.showEnergy(player).get(0).toUpperCase()); - } else - playerData.setInfoDisplayed(Info.ENERGY, !playerData.isInfoDisplayed(Info.ENERGY)); - break; - case "nutrients": - case "n": - if (!config.MECHANICS_STATUS_SCOREBOARD) { - if (config.MECHANICS_FOOD_DIVERSITY_ENABLED) { - for (String s : playerManager.ShowNutrients(player)) - player.sendMessage(s); - } - } else - playerData.setInfoDisplayed(Info.NUTRIENTS, !playerData.isInfoDisplayed(Info.NUTRIENTS)); - break; - default: - sendHelp(player); - } - } - return true; - } else - return false; - } - - @Override - public List onTabComplete(CommandSender sender, Command command, String s, String[] args) { - StringBuilder builder = new StringBuilder(); - for (String arg : args) { - builder.append(arg).append(" "); - } - String[] list = {"all", "hunger", "thirst", "energy", "nutrients", "none", "help"}; - - String arg = builder.toString().trim(); - ArrayList matches = new ArrayList<>(); - for (String name : list) { - if (StringUtil.startsWithIgnoreCase(name, arg)) { - matches.add(name); - } - } - return matches; - } - - private void sendHelp(Player player) { - Utils.sendColoredMsg(player, lang.prefix + "&6HealthBoard"); - Utils.sendColoredMsg(player, " &b/stat all &7- Show your entire health board"); - Utils.sendColoredMsg(player, " &b/stat none &7- Turn off your entire health board"); - Utils.sendColoredMsg(player, " &b/stat hunger &7- Turn on/off hunger"); - Utils.sendColoredMsg(player, " &b/stat thirst &7- Turn on/off thirst"); - Utils.sendColoredMsg(player, " &b/stat energy &7- Turn on/off energy"); - Utils.sendColoredMsg(player, " &b/stat nutrients &7- Turn on/off nutrients"); - } - -} diff --git a/src/main/java/tk/shanebee/survival/commands/ToggleChat.java b/src/main/java/tk/shanebee/survival/commands/ToggleChat.java deleted file mode 100644 index 1419bc6..0000000 --- a/src/main/java/tk/shanebee/survival/commands/ToggleChat.java +++ /dev/null @@ -1,100 +0,0 @@ -package tk.shanebee.survival.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.ArrayList; -import java.util.List; - -@SuppressWarnings("NullableProblems") -public class ToggleChat implements CommandExecutor, TabCompleter { - - private final Lang lang; - private final PlayerManager playerManager; - private final int LOCAL_CHAT_DIST; - - public ToggleChat(Survival plugin) { - this.lang = plugin.getLang(); - this.playerManager = plugin.getPlayerManager(); - this.LOCAL_CHAT_DIST = plugin.getSurvivalConfig().LOCAL_CHAT_DISTANCE; - } - - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (command.getName().equalsIgnoreCase("togglechat")) { - if (!(sender instanceof Player)) { - sender.sendMessage(Utils.getColoredString(lang.players_only)); - return true; - } - Player player = (Player) sender; - PlayerData playerData = playerManager.getPlayerData(player); - - if (LOCAL_CHAT_DIST <= -1) { - player.sendMessage(Utils.getColoredString(lang.toggle_chat_disabled)); - return true; - } - - if (args.length == 1) { - - switch (args[0]) { - case "local": - case "l": - player.sendMessage(Utils.getColoredString(lang.toggle_chat_local)); - playerData.setLocalChat(true); - break; - case "global": - case "g": - player.sendMessage(Utils.getColoredString(lang.toggle_chat_global)); - playerData.setLocalChat(false); - break; - default: - return false; - } - } else if (args.length == 0) { - if (playerData.isLocalChat()) { - player.sendMessage(Utils.getColoredString(lang.toggle_chat_global)); - playerData.setLocalChat(false); - } else { - player.sendMessage(Utils.getColoredString(lang.toggle_chat_local)); - playerData.setLocalChat(true); - } - } else { - sender.sendMessage(ChatColor.RED + Utils.getColoredString(lang.invalid_arg)); - return false; - } - - return true; - } else { - sender.sendMessage("Command: " + command.getName()); - return true; - } - } - - @Override - public List onTabComplete(CommandSender sender, Command command, String s, String[] args) { - StringBuilder builder = new StringBuilder(); - for (String arg : args) { - builder.append(arg).append(" "); - } - String[] list = {"local", "global"}; - String[] list2 = {""}; - String arg = builder.toString().trim(); - ArrayList matches = new ArrayList<>(); - for (String name : (LOCAL_CHAT_DIST > -1) ? list : list2) { - if (StringUtil.startsWithIgnoreCase(name, arg)) { - matches.add(name); - } - } - return matches; - } - -} diff --git a/src/main/java/tk/shanebee/survival/config/Config.java b/src/main/java/tk/shanebee/survival/config/Config.java deleted file mode 100644 index fcd6b84..0000000 --- a/src/main/java/tk/shanebee/survival/config/Config.java +++ /dev/null @@ -1,502 +0,0 @@ -package tk.shanebee.survival.config; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.util.Utils; - -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.List; - -public class Config { - - private final Survival plugin; - private FileConfiguration settings; - private File configFile; - private final String prefix; - - public String LANG; - - public String RESOURCE_PACK_URL; - public boolean RESOURCE_PACK_ENABLED; - public boolean RESOURCE_PACK_NOTIFY; - - public int LOCAL_CHAT_DISTANCE; - public boolean NO_POS; - - public boolean WELCOME_GUIDE_ENABLED; - public boolean WELCOME_GUIDE_NEW_PLAYERS; - public int WELCOME_GUIDE_DELAY; - - // SURVIVAL - public boolean SURVIVAL_ENABLED; - public boolean SURVIVAL_LIMITED_CRAFTING; - public boolean SURVIVAL_UNLOCK_ALL_RECIPES; - public boolean SURVIVAL_REMOVE_WOOD_TOOLS; - public boolean SURVIVAL_TORCH; - public boolean SURVIVAL_UPDATE_MERCHANT_TRADES; - - public boolean BREAK_ONLY_WITH_SICKLE; - public boolean BREAK_ONLY_WITH_SHOVEL; - public boolean BREAK_ONLY_WITH_AXE; - public boolean BREAK_ONLY_WITH_PICKAXE; - public boolean BREAK_ONLY_WITH_SHEARS; - public boolean PLACE_ONLY_WITH_HAMMER; - - public boolean SURVIVAL_SICKLE_FLINT; - public boolean SURVIVAL_SICKLE_STONE; - public boolean SURVIVAL_SICKLE_IRON; - public boolean SURVIVAL_SICKLE_DIAMOND; - - public double DROP_RATE_STICK; - public double DROP_RATE_FLINT; - - // MECHANICS - public boolean MECHANICS_SHARED_WORKBENCH; - public boolean MECHANICS_PREVENT_NIGHT_SKIP; - - // ENERGY - public boolean MECHANICS_ENERGY_ENABLED; - public double MECHANICS_ENERGY_START; - public double MECHANICS_ENERGY_RESPAWN; - public boolean MECHANICS_ENERGY_WARNING; - public double MECHANICS_ENERGY_DRAIN_RATE; - public double MECHANICS_ENERGY_DRAIN_COLD_RATE; - public double MECHANICS_ENERGY_REFRESH_RATE_BED; - public double MECHANICS_ENERGY_REFRESH_RATE_CHAIR; - public double MECHANICS_ENERGY_EXHAUSTION; - public boolean MECHANICS_ENERGY_COFFEE_ENABLED; - public boolean MECHANICS_ENERGY_ABSORPTION; - public boolean MECHANICS_ENERGY_HASTE; - - public boolean MECHANICS_SLOW_ARMOR; - public boolean MECHANICS_REINFORCED_ARMOR; - public boolean MECHANICS_BOW; - public boolean MECHANICS_RECURVED_BOW; - public boolean MECHANICS_GRAPPLING_HOOK; - public boolean MECHANICS_MEDIC_KIT; - public boolean MECHANICS_REDUCED_IRON_NUGGET; - public boolean MECHANICS_REDUCED_GOLD_NUGGET; - - public boolean MECHANICS_STATUS_SCOREBOARD; - public int MECHANICS_ALERT_INTERVAL; - - public boolean MECHANICS_RAW_MEAT_HUNGER; - public boolean MECHANICS_EMPTY_POTION; - public boolean MECHANICS_POISON_POTATO; - public boolean MECHANICS_COOKIE_BOOST; - public boolean MECHANICS_BEET_STRENGTH; - - public boolean MECHANICS_FOOD_DIVERSITY_ENABLED; - public int MECHANICS_FOOD_MAX_PROTEINS; - public int MECHANICS_FOOD_MAX_SALTS; - public int MECHANICS_FOOD_MAX_CARBS; - public int MECHANICS_FOOD_START_PROTEINS; - public int MECHANICS_FOOD_START_SALTS; - public int MECHANICS_FOOD_START_CARBS; - public int MECHANICS_FOOD_RESPAWN_PROTEINS; - public int MECHANICS_FOOD_RESPAWN_SALTS; - public int MECHANICS_FOOD_RESPAWN_CARBS; - public int MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_EASY; - public int MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_MEDIUM; - public int MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_HARD; - public int MECHANICS_FOOD_EFFECTS_SALTS_EX_AMP; - public String MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_EFFECT; - public int MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_AMP; - public int MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_DURATION; - public String MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_EFFECT; - public int MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_AMP; - public int MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_DURATION; - public int MECHANICS_FOOD_EFFECTS_PROTEIN_EX_AMP; - public String MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_EFFECT; - public int MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_AMP; - public int MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_DURATION; - public String MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_EFFECT; - public int MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_AMP; - public int MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_DURATION; - - // THIRST - public boolean MECHANICS_THIRST_ENABLED; - public int MECHANICS_THIRST_START_AMOUNT; - public int MECHANICS_THIRST_RESPAWN_AMOUNT; - public boolean MECHANICS_THIRST_PURIFY_WATER; - public boolean MECHANICS_THIRST_MELT_SNOW; - public double MECHANICS_THIRST_DRAIN_RATE; - public int MECHANICS_THIRST_DRAIN_HEAT; - public int MECHANICS_THIRST_DRAIN_NETHER; - public double MECHANICS_THIRST_DAMAGE_RATE; - public int MECHANICS_THIRST_REP_BEET_SOUP; - public int MECHANICS_THIRST_REP_MELON_SLICE; - public int MECHANICS_THIRST_REP_MUSH_STEW; - public int MECHANICS_THIRST_REP_WATER_BOWL; - public int MECHANICS_THIRST_REP_DIRTY_WATER; - public int MECHANICS_THIRST_REP_CLEAN_WATER; - public int MECHANICS_THIRST_REP_PURE_WATER; - public int MECHANICS_THIRST_REP_COFFEE; - public int MECHANICS_THIRST_REP_COLD_MILK; - public int MECHANICS_THIRST_REP_HOT_MILK; - public int MECHANICS_THIRST_REP_MILK_BUCKET; - public int MECHANICS_THIRST_REP_WATER; - public int MECHANICS_THIRST_REP_HONEY_BOTTLE; - public int MECHANICS_THIRST_REP_OTHER_WATER; - - public int MECHANICS_HUNGER_START_AMOUNT; - public int MECHANICS_HUNGER_RESPAWN_AMOUNT; - - public boolean MECHANICS_COMPASS_WAYPOINT; - public boolean MECHANICS_COMPASS_WAYPOINT_WORLDS; - public boolean MECHANICS_CLOWN_FISH; - public boolean MECHANICS_FERMENTED_SKIN; - public boolean MECHANICS_LIVING_SLIME; - public boolean MECHANICS_SNOWBALL_REVAMP; - public boolean MECHANICS_SNOW_GEN_REVAMP; - - public boolean MECHANICS_FARMING_PRODUCTS_COOKIE; - public boolean MECHANICS_FARMING_PRODUCTS_BREAD; - - public boolean MECHANICS_CHAIRS_ENABLED; - public int MECHANICS_CHAIRS_MAX_WIDTH; - public List MECHANICS_CHAIRS_BLOCKS; - - public boolean MECHANICS_BURNOUT_TORCH_ENABLED; - public int MECHANICS_BURNOUT_TORCH_TIME; - public boolean MECHANICS_BURNOUT_TORCH_RELIGHT; - public boolean MECHANICS_BURNOUT_TORCH_DROP; - public boolean MECHANICS_BURNOUT_TORCH_PERSIST; - - public boolean MECHANICS_WEATHER_ENABLED; - public double MECHANICS_WEATHER_SPEED_BASE; - public double MECHANICS_WEATHER_SPEED_RAIN; - public double MECHANICS_WEATHER_SPEED_STORM; - public double MECHANICS_WEATHER_SPEED_SNOW; - public double MECHANICS_WEATHER_SPEED_SNOWSTORM; - - // ITEM MECHANICS - public int ITEM_FIRESTRIKER_COOK_TIME; - - // ENTITY MECHANICS - public boolean ENTITY_MECHANICS_PIGMEN_CHEST_ENABLED; - public int ENTITY_MECHANICS_PIGMEN_CHEST_RADIUS; - public double ENTITY_MECHANICS_PIGMEN_CHEST_SPEED; - public boolean ENTITY_MECHANICS_BEEKEEPER_SUIT_ENABLED; - public boolean ENTITY_MECHANICS_SUSPICIOUS_MEAT_ENABLED; - public int ENTITY_MECHANICS_SUSPICIOUS_MEAT_CHANCE; - public boolean ENTITY_MECHANICS_CHICKEN_BREEDING_ENABLED; - public int ENTITY_MECHANICS_CHICKEN_BREEDING_MAX_EGGS; - public boolean ENTITY_MECHANICS_CHICKEN_BREEDING_ALWAYS_BABY; - public int ENTITY_MECHANICS_CHICKEN_BREEDING_BABY_TICKS; - public boolean ENTITY_MECHANICS_PIGLIN_DROP_WATER; - public boolean ENTITY_MECHANICS_PIGLIN_ALT_DROP; - - // RECIPES - public boolean RECIPES_SADDLE; - public boolean RECIPES_NAME_TAG; - public boolean RECIPES_PACKED_ICE; - public boolean RECIPES_LEATHER_BARD; - public boolean RECIPES_IRON_BARD; - public boolean RECIPES_GOLD_BARD; - public boolean RECIPES_DIAMOND_BARD; - public boolean RECIPES_CLAY_BRICK; - public boolean RECIPES_QUARTZ_BLOCK; - public boolean RECIPES_WOOL_STRING; - public boolean RECIPES_WEB_STRING; - public boolean RECIPES_ICE; - public boolean RECIPES_CLAY; - public boolean RECIPES_DIORITE; - public boolean RECIPES_GRANITE; - public boolean RECIPES_ANDESITE; - public boolean RECIPES_GRAVEL; - public boolean RECIPES_SLIMEBALL; - public boolean RECIPES_COBWEB; - public boolean RECIPES_SAPLING_STICK; - public boolean RECIPES_FISHING_ROD; - public boolean RECIPES_FURNACE; - public boolean RECIPES_WORKBENCH; - - // LEGENDARY TOOLS - public boolean LEGENDARY_VALKYRIE; - public boolean LEGENDARY_QUARTZPICKAXE; - public boolean LEGENDARY_OBSIDIAN_MACE; - public boolean LEGENDARY_GIANTBLADE; - public boolean LEGENDARY_BLAZESWORD; - public boolean LEGENDARY_NOTCH_APPLE; - public boolean LEGENDARY_GOLDARMORBUFF; - - // HIDDEN CONFIG - public int RECIPE_DELAY; - - public Config(Survival plugin) { - this.plugin = plugin; - this.prefix = "&7[&3Survival&bPlus&7] "; //temp prefix used before lang.yml loads - loadDefaultSettings(); - } - - private void loadDefaultSettings() { - if (configFile == null) { - configFile = new File(plugin.getDataFolder(), "config.yml"); - } - if (!configFile.exists()) { - plugin.saveResource("config.yml", false); - settings = YamlConfiguration.loadConfiguration(configFile); - Utils.sendColoredConsoleMsg(prefix + "new config.yml created"); - } else { - settings = YamlConfiguration.loadConfiguration(configFile); - } - matchConfig(settings, configFile); - loadSettings(); - Utils.sendColoredConsoleMsg(prefix + "&7config.yml &aloaded"); - } - - // Used to update config - @SuppressWarnings("ConstantConditions") - private void matchConfig(FileConfiguration config, File file) { - try { - boolean hasUpdated = false; - InputStream is = plugin.getResource(file.getName()); - assert is != null; - InputStreamReader isr = new InputStreamReader(is); - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(isr); - for (String key : defConfig.getConfigurationSection("").getKeys(true)) { - if (!config.contains(key)) { - config.set(key, defConfig.get(key)); - hasUpdated = true; - } - } - for (String key : config.getConfigurationSection("").getKeys(true)) { - if (!defConfig.contains(key) && !key.equalsIgnoreCase("recipe-delay")) { - config.set(key, null); - hasUpdated = true; - } - } - if (hasUpdated) - config.save(file); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @SuppressWarnings("unused") - public FileConfiguration getSettings() { - return this.settings; - } - - private void loadSettings() { - - this.LANG = settings.getString("Language"); - - // MULTIWORLD - this.RESOURCE_PACK_URL = settings.getString("MultiWorld.ResourcePackURL"); - this.RESOURCE_PACK_ENABLED = settings.getBoolean("MultiWorld.EnableResourcePack"); - this.RESOURCE_PACK_NOTIFY = settings.getBoolean("MultiWorld.NotifyMessage"); - - this.LOCAL_CHAT_DISTANCE = settings.getInt("LocalChatDist"); - this.NO_POS = settings.getBoolean("NoPos"); - - // WELCOME GUIDE - this.WELCOME_GUIDE_ENABLED = settings.getBoolean("WelcomeGuide.Enabled"); - this.WELCOME_GUIDE_NEW_PLAYERS = settings.getBoolean("WelcomeGuide.NewPlayersOnly"); - this.WELCOME_GUIDE_DELAY = settings.getInt("WelcomeGuide.Delay"); - - // SURVIVAL - this.SURVIVAL_ENABLED = settings.getBoolean("Survival.Enabled"); - this.SURVIVAL_LIMITED_CRAFTING = settings.getBoolean("Survival.LimitedCrafting"); - this.SURVIVAL_UNLOCK_ALL_RECIPES = settings.getBoolean("Survival.Unlock-all-recipes-on-join"); - this.SURVIVAL_REMOVE_WOOD_TOOLS = settings.getBoolean("Survival.Remove-Wooden-Tools"); - this.SURVIVAL_TORCH = settings.getBoolean("Survival.Torch"); - this.SURVIVAL_UPDATE_MERCHANT_TRADES = settings.getBoolean("Survival.UpdateMerchantTrades"); - - this.BREAK_ONLY_WITH_SICKLE = settings.getBoolean("Survival.BreakOnlyWith.Sickle"); - this.BREAK_ONLY_WITH_SHOVEL = settings.getBoolean("Survival.BreakOnlyWith.Shovel"); - this.BREAK_ONLY_WITH_AXE = settings.getBoolean("Survival.BreakOnlyWith.Axe"); - this.BREAK_ONLY_WITH_PICKAXE = settings.getBoolean("Survival.BreakOnlyWith.Pickaxe"); - this.BREAK_ONLY_WITH_SHEARS = settings.getBoolean("Survival.BreakOnlyWith.Shears"); - this.PLACE_ONLY_WITH_HAMMER = settings.getBoolean("Survival.PlaceOnlyWith.Hammer"); - - this.SURVIVAL_SICKLE_FLINT = settings.getBoolean("Survival.Sickles.Flint"); - this.SURVIVAL_SICKLE_STONE = settings.getBoolean("Survival.Sickles.Stone"); - this.SURVIVAL_SICKLE_IRON = settings.getBoolean("Survival.Sickles.Iron"); - this.SURVIVAL_SICKLE_DIAMOND = settings.getBoolean("Survival.Sickles.Diamond"); - - this.DROP_RATE_STICK = settings.getDouble("Survival.DropRate.Stick"); - this.DROP_RATE_FLINT = settings.getDouble("Survival.DropRate.Flint"); - - // MECHANICS - this.MECHANICS_SHARED_WORKBENCH = settings.getBoolean("Mechanics.SharedWorkbench"); - this.MECHANICS_PREVENT_NIGHT_SKIP = settings.getBoolean("Mechanics.Prevent-Night-Skip"); - this.MECHANICS_ENERGY_ENABLED = settings.getBoolean("Mechanics.Energy.enabled"); - this.MECHANICS_ENERGY_START = settings.getDouble("Mechanics.Energy.start-level"); - this.MECHANICS_ENERGY_RESPAWN = settings.getDouble("Mechanics.Energy.respawn-level"); - this.MECHANICS_ENERGY_WARNING = settings.getBoolean("Mechanics.Energy.warning"); - this.MECHANICS_ENERGY_DRAIN_RATE = settings.getDouble("Mechanics.Energy.drain-rate"); - this.MECHANICS_ENERGY_DRAIN_COLD_RATE = settings.getDouble("Mechanics.Energy.cold-drain-rate"); - this.MECHANICS_ENERGY_REFRESH_RATE_BED = settings.getDouble("Mechanics.Energy.sleeping-refresh-rate"); - this.MECHANICS_ENERGY_REFRESH_RATE_CHAIR = settings.getDouble("Mechanics.Energy.chair-refresh-rate"); - this.MECHANICS_ENERGY_EXHAUSTION = settings.getDouble("Mechanics.Energy.exhaustion"); - this.MECHANICS_ENERGY_COFFEE_ENABLED = settings.getBoolean("Mechanics.Energy.coffee"); - this.MECHANICS_ENERGY_ABSORPTION = settings.getBoolean("Mechanics.Energy.absorption"); - this.MECHANICS_ENERGY_HASTE = settings.getBoolean("Mechanics.Energy.haste"); - - this.MECHANICS_SLOW_ARMOR = settings.getBoolean("Mechanics.SlowArmor"); - this.MECHANICS_REINFORCED_ARMOR = settings.getBoolean("Mechanics.ReinforcedLeatherArmor"); - this.MECHANICS_BOW = settings.getBoolean("Mechanics.Bow"); - this.MECHANICS_RECURVED_BOW = settings.getBoolean("Mechanics.RecurveBow"); - this.MECHANICS_GRAPPLING_HOOK = settings.getBoolean("Mechanics.GrapplingHook"); - this.MECHANICS_MEDIC_KIT = settings.getBoolean("Mechanics.MedicalKit"); - this.MECHANICS_REDUCED_IRON_NUGGET = settings.getBoolean("Mechanics.ReducedIronNugget"); - this.MECHANICS_REDUCED_GOLD_NUGGET = settings.getBoolean("Mechanics.ReducedGoldNugget"); - - this.MECHANICS_STATUS_SCOREBOARD = settings.getBoolean("Mechanics.StatusScoreboard"); - this.MECHANICS_ALERT_INTERVAL = settings.getInt("Mechanics.AlertInterval"); - - this.MECHANICS_RAW_MEAT_HUNGER = settings.getBoolean("Mechanics.RawMeatHunger"); - this.MECHANICS_EMPTY_POTION = settings.getBoolean("Mechanics.EmptyPotions"); - this.MECHANICS_POISON_POTATO = settings.getBoolean("Mechanics.PoisonousPotato"); - this.MECHANICS_COOKIE_BOOST = settings.getBoolean("Mechanics.CookieHealthBoost"); - this.MECHANICS_BEET_STRENGTH = settings.getBoolean("Mechanics.BeetrootStrength"); - - this.MECHANICS_FOOD_DIVERSITY_ENABLED = settings.getBoolean("Mechanics.FoodDiversity.enabled"); - this.MECHANICS_FOOD_MAX_CARBS = settings.getInt("Mechanics.FoodDiversity.max-level.carbs"); - this.MECHANICS_FOOD_MAX_SALTS = settings.getInt("Mechanics.FoodDiversity.max-level.salts"); - this.MECHANICS_FOOD_MAX_PROTEINS = settings.getInt("Mechanics.FoodDiversity.max-level.proteins"); - this.MECHANICS_FOOD_DIVERSITY_ENABLED = settings.getBoolean("Mechanics.FoodDiversity.enabled"); - this.MECHANICS_FOOD_START_CARBS = settings.getInt("Mechanics.FoodDiversity.start-level.carbs"); - this.MECHANICS_FOOD_START_SALTS = settings.getInt("Mechanics.FoodDiversity.start-level.salts"); - this.MECHANICS_FOOD_START_PROTEINS = settings.getInt("Mechanics.FoodDiversity.start-level.proteins"); - this.MECHANICS_FOOD_DIVERSITY_ENABLED = settings.getBoolean("Mechanics.FoodDiversity.enabled"); - this.MECHANICS_FOOD_RESPAWN_CARBS = settings.getInt("Mechanics.FoodDiversity.respawn-level.carbs"); - this.MECHANICS_FOOD_RESPAWN_SALTS = settings.getInt("Mechanics.FoodDiversity.respawn-level.salts"); - this.MECHANICS_FOOD_RESPAWN_PROTEINS = settings.getInt("Mechanics.FoodDiversity.respawn-level.proteins"); - this.MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_EASY = settings.getInt("Mechanics.FoodDiversity.effects.carbs.exhaustion-amplifier.easy"); - this.MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_MEDIUM = settings.getInt("Mechanics.FoodDiversity.effects.carbs.exhaustion-amplifier.normal"); - this.MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_HARD = settings.getInt("Mechanics.FoodDiversity.effects.carbs.exhaustion-amplifier.hard"); - this.MECHANICS_FOOD_EFFECTS_SALTS_EX_AMP = settings.getInt("Mechanics.FoodDiversity.effects.salts.exhaustion-amplifier"); - this.MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_EFFECT = settings.getString("Mechanics.FoodDiversity.effects.salts.status-effects.normal.effect"); - this.MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_AMP = settings.getInt("Mechanics.FoodDiversity.effects.salts.status-effects.normal.amplifier"); - this.MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_DURATION = settings.getInt("Mechanics.FoodDiversity.effects.salts.status-effects.normal.duration"); - this.MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_EFFECT = settings.getString("Mechanics.FoodDiversity.effects.salts.status-effects.hard.effect"); - this.MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_AMP = settings.getInt("Mechanics.FoodDiversity.effects.salts.status-effects.hard.amplifier"); - this.MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_DURATION = settings.getInt("Mechanics.FoodDiversity.effects.salts.status-effects.hard.duration"); - - this.MECHANICS_FOOD_EFFECTS_PROTEIN_EX_AMP = settings.getInt("Mechanics.FoodDiversity.effects.proteins.exhaustion-amplifier"); - this.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_EFFECT = settings.getString("Mechanics.FoodDiversity.effects.proteins.status-effects.normal.effect"); - this.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_AMP = settings.getInt("Mechanics.FoodDiversity.effects.proteins.status-effects.normal.amplifier"); - this.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_DURATION = settings.getInt("Mechanics.FoodDiversity.effects.proteins.status-effects.normal.duration"); - this.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_EFFECT = settings.getString("Mechanics.FoodDiversity.effects.proteins.status-effects.hard.effect"); - this.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_AMP = settings.getInt("Mechanics.FoodDiversity.effects.proteins.status-effects.hard.amplifier"); - this.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_DURATION = settings.getInt("Mechanics.FoodDiversity.effects.proteins.status-effects.hard.duration"); - - this.MECHANICS_THIRST_ENABLED = settings.getBoolean("Mechanics.Thirst.Enabled"); - this.MECHANICS_THIRST_START_AMOUNT = settings.getInt("Mechanics.Thirst.Starting-Amount"); - this.MECHANICS_THIRST_RESPAWN_AMOUNT = settings.getInt("Mechanics.Thirst.Respawn-Amount"); - this.MECHANICS_THIRST_PURIFY_WATER = settings.getBoolean("Mechanics.Thirst.PurifyWater"); - this.MECHANICS_THIRST_MELT_SNOW = settings.getBoolean("Mechanics.Thirst.MeltSnow"); - this.MECHANICS_THIRST_DRAIN_RATE = settings.getDouble("Mechanics.Thirst.DrainRate"); - this.MECHANICS_THIRST_DRAIN_HEAT = settings.getInt("Mechanics.Thirst.HeatDrain"); - this.MECHANICS_THIRST_DRAIN_NETHER = settings.getInt("Mechanics.Thirst.NetherDrain"); - this.MECHANICS_THIRST_DAMAGE_RATE = settings.getDouble("Mechanics.Thirst.DamageRate"); - - this.MECHANICS_THIRST_REP_BEET_SOUP = settings.getInt("Mechanics.Thirst.Replenish-Level.beetroot-soup"); - this.MECHANICS_THIRST_REP_MELON_SLICE = settings.getInt("Mechanics.Thirst.Replenish-Level.melon-slice"); - this.MECHANICS_THIRST_REP_MUSH_STEW = settings.getInt("Mechanics.Thirst.Replenish-Level.mushroom-stew"); - this.MECHANICS_THIRST_REP_WATER_BOWL = settings.getInt("Mechanics.Thirst.Replenish-Level.water-bowl"); - this.MECHANICS_THIRST_REP_DIRTY_WATER = settings.getInt("Mechanics.Thirst.Replenish-Level.dirty-water"); - this.MECHANICS_THIRST_REP_CLEAN_WATER = settings.getInt("Mechanics.Thirst.Replenish-Level.clean-water"); - this.MECHANICS_THIRST_REP_PURE_WATER = settings.getInt("Mechanics.Thirst.Replenish-Level.purified-water"); - this.MECHANICS_THIRST_REP_COFFEE = settings.getInt("Mechanics.Thirst.Replenish-Level.coffee"); - this.MECHANICS_THIRST_REP_COLD_MILK = settings.getInt("Mechanics.Thirst.Replenish-Level.cold-milk"); - this.MECHANICS_THIRST_REP_HOT_MILK = settings.getInt("Mechanics.Thirst.Replenish-Level.hot-milk"); - this.MECHANICS_THIRST_REP_MILK_BUCKET = settings.getInt("Mechanics.Thirst.Replenish-Level.milk-bucket"); - this.MECHANICS_THIRST_REP_WATER = settings.getInt("Mechanics.Thirst.Replenish-Level.water"); - this.MECHANICS_THIRST_REP_HONEY_BOTTLE = settings.getInt("Mechanics.Thirst.Replenish-Level.honey-bottle"); - this.MECHANICS_THIRST_REP_OTHER_WATER = settings.getInt("Mechanics.Thirst.Replenish-Level.other-water"); - - this.MECHANICS_HUNGER_START_AMOUNT = settings.getInt("Mechanics.Hunger.Starting-Amount"); - this.MECHANICS_HUNGER_RESPAWN_AMOUNT = settings.getInt("Mechanics.Hunger.Respawn-Amount"); - - this.MECHANICS_COMPASS_WAYPOINT = settings.getBoolean("Mechanics.CompassWaypoint.enabled"); - this.MECHANICS_COMPASS_WAYPOINT_WORLDS = settings.getBoolean("Mechanics.CompassWaypoint.per-world"); - this.MECHANICS_CLOWN_FISH = settings.getBoolean("Mechanics.Clownfish"); - this.MECHANICS_FERMENTED_SKIN = settings.getBoolean("Mechanics.FermentedSkin"); - this.MECHANICS_LIVING_SLIME = settings.getBoolean("Mechanics.LivingSlime"); - - this.MECHANICS_SNOWBALL_REVAMP = settings.getBoolean("Mechanics.SnowballRevamp"); - this.MECHANICS_SNOW_GEN_REVAMP = settings.getBoolean("Mechanics.SnowGenerationRevamp"); - - this.MECHANICS_FARMING_PRODUCTS_COOKIE = settings.getBoolean("Mechanics.FarmingProducts.Cookie"); - this.MECHANICS_FARMING_PRODUCTS_BREAD = settings.getBoolean("Mechanics.FarmingProducts.Bread"); - - this.MECHANICS_CHAIRS_ENABLED = settings.getBoolean("Mechanics.Chairs.Enabled"); - this.MECHANICS_CHAIRS_MAX_WIDTH = settings.getInt("Mechanics.Chairs.MaxChairWidth"); - this.MECHANICS_CHAIRS_BLOCKS = settings.getStringList("Mechanics.Chairs.AllowedBlocks"); - - this.MECHANICS_BURNOUT_TORCH_ENABLED = settings.getBoolean("Mechanics.BurnoutTorches.Enabled"); - this.MECHANICS_BURNOUT_TORCH_TIME = settings.getInt("Mechanics.BurnoutTorches.BurnoutTime"); - this.MECHANICS_BURNOUT_TORCH_RELIGHT = settings.getBoolean("Mechanics.BurnoutTorches.Relightable"); - this.MECHANICS_BURNOUT_TORCH_DROP = settings.getBoolean("Mechanics.BurnoutTorches.DropTorch"); - this.MECHANICS_BURNOUT_TORCH_PERSIST = settings.getBoolean("Mechanics.BurnoutTorches.PersistentTorches"); - - this.MECHANICS_WEATHER_ENABLED = settings.getBoolean("Mechanics.Weather.Enabled"); - this.MECHANICS_WEATHER_SPEED_BASE = settings.getDouble("Mechanics.Weather.speed.base"); - this.MECHANICS_WEATHER_SPEED_RAIN = settings.getDouble("Mechanics.Weather.speed.rain"); - this.MECHANICS_WEATHER_SPEED_STORM = settings.getDouble("Mechanics.Weather.speed.storm"); - this.MECHANICS_WEATHER_SPEED_SNOW = settings.getDouble("Mechanics.Weather.speed.snow"); - this.MECHANICS_WEATHER_SPEED_SNOWSTORM = settings.getDouble("Mechanics.Weather.speed.snowstorm"); - - // ITEM MECHANICS - this.ITEM_FIRESTRIKER_COOK_TIME = settings.getInt("Item-Mechanics.firestriker.cook-time"); - - // ENTITY MECHANICS - this.ENTITY_MECHANICS_PIGMEN_CHEST_ENABLED = settings.getBoolean("Entity-Mechanics.pigmen-chests.enabled"); - this.ENTITY_MECHANICS_PIGMEN_CHEST_RADIUS = settings.getInt("Entity-Mechanics.pigmen-chests.distance"); - this.ENTITY_MECHANICS_PIGMEN_CHEST_SPEED = settings.getDouble("Entity-Mechanics.pigmen-chests.speed-modifier"); - this.ENTITY_MECHANICS_BEEKEEPER_SUIT_ENABLED = settings.getBoolean("Entity-Mechanics.beekeeper-suit.enabled"); - this.ENTITY_MECHANICS_SUSPICIOUS_MEAT_ENABLED = settings.getBoolean("Entity-Mechanics.suspicious-meat.enabled"); - this.ENTITY_MECHANICS_SUSPICIOUS_MEAT_CHANCE = settings.getInt("Entity-Mechanics.suspicious-meat.chance"); - this.ENTITY_MECHANICS_CHICKEN_BREEDING_ENABLED = settings.getBoolean("Entity-Mechanics.chicken-breeding.enabled"); - this.ENTITY_MECHANICS_CHICKEN_BREEDING_MAX_EGGS = settings.getInt("Entity-Mechanics.chicken-breeding.max-eggs"); - this.ENTITY_MECHANICS_CHICKEN_BREEDING_ALWAYS_BABY = settings.getBoolean("Entity-Mechanics.chicken-breeding.always-baby"); - this.ENTITY_MECHANICS_CHICKEN_BREEDING_BABY_TICKS = settings.getInt("Entity-Mechanics.chicken-breeding.baby-ticks"); - this.ENTITY_MECHANICS_PIGLIN_DROP_WATER = settings.getBoolean("Entity-Mechanics.piglin-barter.drop-purified-water"); - this.ENTITY_MECHANICS_PIGLIN_ALT_DROP = settings.getBoolean("Entity-Mechanics.piglin-barter.alternate-bartering"); - - // RECIPES - this.RECIPES_SADDLE = settings.getBoolean("Recipes.Saddle"); - this.RECIPES_NAME_TAG = settings.getBoolean("Recipes.Nametag"); - this.RECIPES_PACKED_ICE = settings.getBoolean("Recipes.PackedIce"); - this.RECIPES_LEATHER_BARD = settings.getBoolean("Recipes.LeatherBard"); - this.RECIPES_IRON_BARD = settings.getBoolean("Recipes.IronBard"); - this.RECIPES_GOLD_BARD = settings.getBoolean("Recipes.GoldBard"); - this.RECIPES_DIAMOND_BARD = settings.getBoolean("Recipes.DiamondBard"); - this.RECIPES_CLAY_BRICK = settings.getBoolean("Recipes.ClayBrick"); - this.RECIPES_QUARTZ_BLOCK = settings.getBoolean("Recipes.QuartzBlock"); - this.RECIPES_WOOL_STRING = settings.getBoolean("Recipes.WoolString"); - this.RECIPES_WEB_STRING = settings.getBoolean("Recipes.WebString"); - this.RECIPES_ICE = settings.getBoolean("Recipes.Ice"); - this.RECIPES_CLAY = settings.getBoolean("Recipes.Clay"); - this.RECIPES_DIORITE = settings.getBoolean("Recipes.Diorite"); - this.RECIPES_GRANITE = settings.getBoolean("Recipes.Granite"); - this.RECIPES_ANDESITE = settings.getBoolean("Recipes.Andesite"); - this.RECIPES_GRAVEL = settings.getBoolean("Recipes.Gravel"); - this.RECIPES_SLIMEBALL = settings.getBoolean("Recipes.Slimeball"); - this.RECIPES_COBWEB = settings.getBoolean("Recipes.Cobweb"); - this.RECIPES_SAPLING_STICK = settings.getBoolean("Recipes.SaplingToSticks"); - this.RECIPES_FISHING_ROD = settings.getBoolean("Recipes.FishingRod"); - this.RECIPES_FURNACE = settings.getBoolean("Recipes.Furnace"); - this.RECIPES_WORKBENCH = settings.getBoolean("Recipes.Workbench"); - - // LEGENDARY ITEMS - this.LEGENDARY_VALKYRIE = settings.getBoolean("LegendaryItems.ValkyrieAxe"); - this.LEGENDARY_QUARTZPICKAXE = settings.getBoolean("LegendaryItems.QuartzPickaxe"); - this.LEGENDARY_OBSIDIAN_MACE = settings.getBoolean("LegendaryItems.ObsidianMace"); - this.LEGENDARY_GIANTBLADE = settings.getBoolean("LegendaryItems.GiantBlade"); - this.LEGENDARY_BLAZESWORD = settings.getBoolean("LegendaryItems.BlazeSword"); - this.LEGENDARY_NOTCH_APPLE = settings.getBoolean("LegendaryItems.NotchApple"); - this.LEGENDARY_GOLDARMORBUFF = settings.getBoolean("LegendaryItems.GoldArmorBuff"); - - // HIDDEN CONFIG - this.RECIPE_DELAY = settings.getInt("recipe-delay", 0); - } - -} diff --git a/src/main/java/tk/shanebee/survival/config/Lang.java b/src/main/java/tk/shanebee/survival/config/Lang.java deleted file mode 100644 index 906a6c4..0000000 --- a/src/main/java/tk/shanebee/survival/config/Lang.java +++ /dev/null @@ -1,432 +0,0 @@ -package tk.shanebee.survival.config; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.util.Utils; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.List; - -public class Lang { - - private final Survival plugin; - private final String lang_yml; - - public String prefix; - public String no_perm; - public String survival_guide_msg; - public String survival_guide_click_msg; - public String survival_guide_hover_msg; - public String survival_guide_link; - - public String resource_pack_accepted; - public String resource_pack_declined; - public String resource_pack_apply; - public String resource_pack_required; - - public String task_must_use_shovel; - public String task_must_use_axe; - public String task_must_use_pick; - public String task_must_use_sickle; - public String task_must_use_shear; - public String task_must_use_hammer; - - public String no_rename; - public String period; - public String charge; - public String charge_ready; - public String charge_unable; - - public String lack_of_energy; - public String arrows_off_hand; - public String arrows_off_hand_crossbow; - public String bow_main_hand; - public String recurved_bow; - public String recurved_crossbow; - public String recurved; - - public String fishing_off_hand; - public String fishing_main_hand; - public String grappling_off_hand; - public String grappling_main_hand; - public String compass_pointed; - public String compass_coords; - public List compass_lore; - public String players_only; - public String toggle_chat_local; - public String toggle_chat_global; - public String toggle_chat_disabled; - public String invalid_arg; - - public String starved_eat; - public String dehydrated_drink; - public String healthboard_title; - public String hunger; - public String thirst; - public String energy; - public String carbohydrates; - public String carbohydrates_lack; - public String protein; - public String protein_lack; - public String vitamins; - public String vitamins_lack; - public String nutrition_gui; - public String nutrition_gui_next_page; - public String nutrition_gui_last_page; - - public String healing; - public String healing_self; - public String keep; - public String on_hand; - public String being_healed; - public String stay_still; - public String healing_complete; - public String healing_interrupted; - - public String energy_level_10; - public String energy_level_6_5; - public String energy_level_3_5; - public String energy_level_2; - public String energy_level_1; - /* - public String energized; - public String sleepy; - public String overworked; - public String distressed; - public String collapsed_1; - public String collapsed_2; - public String feeling_sleepy_1; - public String feeling_sleepy_2; - public String feeling_sleepy_3; - public String energy_rising; - - */ - - public String locked; - public String missing_component; - public String in_main_hand; - public String in_off_hand; - public String attack_speed; - public String attack_damage; - public String right_click_sprinting; - public String right_click_sneaking; - public String decrease_hunger_value; - public String hatchet; - public String mattock; - public String firestriker; - public String firestriker_lore; - public String shiv; - public String poisoned_enemy; - public String poisoned_retain; - public String reduce_50; - public String grappling_hook; - public String hammer; - public String workbench; - public String valkyrie_axe; - public String valkyrie_axe_unable_dual; - public String valkyrie_axe_spin; - public String valkyrie_axe_cooldown; - public String quartz_breaker; - public String haste; - public String obsidian_mace; - public String cripple_hit; - public String drain_hit; - public String exhausted_slow; - public String expire_disarm; - public String knockback_resistance; - public String ender_giant_blade; - public String ender_giant_blade_unable_duel; - public String ender_giant_blade_charge; - public String ender_giant_blade_cooldown; - public String half_shield_resistance; - public String reflecting_coming; - public String blaze_sword; - public String blaze_sword_fire_resistance; - public String blaze_sword_fiery; - public String blaze_sword_spread_fire; - public String blaze_sword_cost; - public String reinforced_boots; - public String reinforced_tunic; - public String reinforced_pants; - public String reinforced_hat; - public String golden_sabatons; - public String golden_guard; - public String golden_greaves; - public String golden_crown; - public String fermented_skin; - public String suspicious_meat; - public String medical_kit; - public String water_bowl; - public String dirty_water; - public String dirty_water_lore; - public int dirty_water_color; - public String clean_water; - public String clean_water_lore; - public int clean_water_color; - public String purified_water; - public String purified_water_lore; - public int purified_water_color; - public String coffee_bean_name; - public String coffee_name; - public int coffee_color; - public String cold_milk_name; - public int cold_milk_color; - public String hot_milk_name; - public int hot_milk_color; - public String hot_milk_drink; - public String breeding_egg_name; - - public String flint_sickle; - public String stone_sickle; - public String iron_sickle; - public String diamond_sickle; - public String campfire_name; - public String campfire_lore; - - public String bee_helmet_name; - public String bee_chest_name; - public String bee_legs_name; - public String bee_boots_name; - public String bee_suit_lore; - public String snow_boots_name; - public String snow_boots_lore; - public String rain_boots_name; - public String rain_boots_lore; - - public String cmd_player_not_online; - public String cmd_heal_self; - public String cmd_heal_by; - public String cmd_heal_other; - - public Lang(Survival main, String language) { - this.plugin = main; - this.lang_yml = language.equals("CN") ? "lang_CN.yml" : "lang_EN.yml"; - } - - public void loadLangFile(CommandSender sender) { - String loaded; - FileConfiguration lang; - File lang_file = new File(plugin.getDataFolder(), lang_yml); - if (!lang_file.exists()) { - plugin.saveResource(lang_yml, true); - loaded = "&aNew " + lang_yml + " created"; - } else { - loaded = "&7" + lang_yml + " &aloaded"; - //updateLang(YamlConfiguration.loadConfiguration(lang_file), lang_file); - matchConfig(YamlConfiguration.loadConfiguration(lang_file), lang_file); - } - lang = YamlConfiguration.loadConfiguration(lang_file); - - prefix = lang.getString("prefix"); - no_perm = lang.getString("no-perm"); - survival_guide_msg = lang.getString("survival-guide-msg"); - survival_guide_click_msg = lang.getString("survival-guide-click-msg"); - survival_guide_hover_msg = lang.getString("survival-guide-hover-msg"); - survival_guide_link = lang.getString("survival-guide-link"); - resource_pack_accepted = lang.getString("resource-pack-accepted"); - resource_pack_declined = lang.getString("resource-pack-declined"); - resource_pack_apply = lang.getString("resource-pack-apply"); - resource_pack_required = lang.getString("resource-pack-required"); - task_must_use_shovel = lang.getString("task-must-use-shovel"); - task_must_use_axe = lang.getString("task-must-use-axe"); - task_must_use_pick = lang.getString("task-must-use-pick"); - task_must_use_sickle = lang.getString("task-must-use-sickle"); - task_must_use_shear = lang.getString("task-must-use-shear"); - task_must_use_hammer = lang.getString("task-must-use-hammer"); - no_rename = lang.getString("no-rename"); - period = lang.getString("period"); - charge = lang.getString("charge"); - charge_ready = lang.getString("charge-ready"); - charge_unable = lang.getString("charge-unable"); - lack_of_energy = lang.getString("lack-of-energy"); - arrows_off_hand = lang.getString("arrows-off-hand"); - arrows_off_hand_crossbow = lang.getString("arrows-off-hand-crossbow"); - bow_main_hand = lang.getString("bow-main-hand"); - recurved_bow = lang.getString("recurved-bow"); - recurved_crossbow = lang.getString("recurved-crossbow"); - recurved = lang.getString("recurved"); - fishing_off_hand = lang.getString("fishing-off-hand"); - fishing_main_hand = lang.getString("fishing-main-hand"); - grappling_off_hand = lang.getString("grappling-off-hand"); - grappling_main_hand = lang.getString("grappling-main-hand"); - compass_pointed = lang.getString("compass-pointed"); - compass_coords = lang.getString("compass-coords"); - compass_lore = lang.getStringList("compass-lore"); - players_only = lang.getString("players-only"); - toggle_chat_local = lang.getString("toggle-chat-local"); - toggle_chat_global = lang.getString("toggle-chat-global"); - toggle_chat_disabled = lang.getString("toggle-chat-disabled"); - invalid_arg = lang.getString("invalid-arg"); - starved_eat = lang.getString("starved-eat"); - dehydrated_drink = lang.getString("dehydrated-drink"); - healthboard_title = lang.getString("healthboard-title"); - hunger = lang.getString("hunger"); - thirst = lang.getString("thirst"); - energy = lang.getString("energy"); - carbohydrates = lang.getString("carbohydrates"); - carbohydrates_lack = lang.getString("carbohydrates-lack"); - protein = lang.getString("protein"); - protein_lack = lang.getString("protein-lack"); - vitamins = lang.getString("vitamins"); - vitamins_lack = lang.getString("vitamins-lack"); - nutrition_gui = lang.getString("nutrition-gui"); - nutrition_gui_next_page = lang.getString("nutrition-gui-next-page"); - nutrition_gui_last_page = lang.getString("nutrition-gui-last-page"); - healing = lang.getString("healing"); - healing_self = lang.getString("healing-self"); - keep = lang.getString("keep"); - on_hand = lang.getString("on-hand"); - being_healed = lang.getString("being-healed"); - stay_still = lang.getString("stay-still"); - healing_complete = lang.getString("healing-complete"); - healing_interrupted = lang.getString("healing-interrupted"); - energy_level_10 = lang.getString("energy-level-10"); - energy_level_6_5 = lang.getString("energy-level-6-5"); - energy_level_3_5 = lang.getString("energy-level-3-5"); - energy_level_2 = lang.getString("energy-level-2"); - energy_level_1 = lang.getString("energy-level-1"); - locked = lang.getString("locked"); - missing_component = lang.getString("missing-component"); - in_main_hand = lang.getString("in-main-hand"); - in_off_hand = lang.getString("in-off-hand"); - attack_speed = lang.getString("attack-speed"); - attack_damage = lang.getString("attack-damage"); - right_click_sneaking = lang.getString("right-click-sneaking"); - right_click_sprinting = lang.getString("right-click-sprinting"); - decrease_hunger_value = lang.getString("decrease-hunger-value"); - hatchet = lang.getString("hatchet"); - mattock = lang.getString("mattock"); - firestriker = lang.getString("firestriker"); - firestriker_lore = lang.getString("firestriker-lore"); - shiv = lang.getString("shiv"); - poisoned_enemy = lang.getString("poisoned-enemy"); - poisoned_retain = lang.getString("poisoned-retain"); - reduce_50 = lang.getString("reduce-50"); - grappling_hook = lang.getString("grappling-hook"); - hammer = lang.getString("hammer"); - workbench = lang.getString("workbench"); - valkyrie_axe = lang.getString("valkyrie-axe"); - valkyrie_axe_unable_dual = lang.getString("valkyrie-axe-unable-dual"); - valkyrie_axe_spin = lang.getString("valkyrie-axe-spin"); - valkyrie_axe_cooldown = lang.getString("valkyrie-axe-cooldown"); - quartz_breaker = lang.getString("quartz-breaker"); - haste = lang.getString("haste"); - obsidian_mace = lang.getString("obsidian-mace"); - cripple_hit = lang.getString("cripple-hit"); - drain_hit = lang.getString("drain-hit"); - exhausted_slow = lang.getString("exhausted-slow"); - expire_disarm = lang.getString("expire-disarm"); - knockback_resistance = lang.getString("knockback-resistance"); - ender_giant_blade = lang.getString("ender-giant-blade"); - ender_giant_blade_unable_duel = lang.getString("ender-giant-blade-unable-duel"); - ender_giant_blade_charge = lang.getString("ender-giant-blade-charge"); - ender_giant_blade_cooldown = lang.getString("ender-giant-blade-cooldown"); - half_shield_resistance = lang.getString("half-shield-resistance"); - reflecting_coming = lang.getString("reflecting-coming"); - blaze_sword = lang.getString("blaze-sword"); - blaze_sword_fire_resistance = lang.getString("blaze-sword-fire-resistance"); - blaze_sword_fiery = lang.getString("blaze-sword-fiery"); - blaze_sword_spread_fire = lang.getString("blaze-sword-spread-fire"); - blaze_sword_cost = lang.getString("blaze-sword-cost"); - reinforced_boots = lang.getString("reinforced-boots"); - reinforced_tunic = lang.getString("reinforced-tunic"); - reinforced_pants = lang.getString("reinforced-pants"); - reinforced_hat = lang.getString("reinforced-hat"); - golden_sabatons = lang.getString("golden-sabatons"); - golden_guard = lang.getString("golden-guard"); - golden_greaves = lang.getString("golden-greaves"); - golden_crown = lang.getString("golden-crown"); - fermented_skin = lang.getString("fermented-skin"); - suspicious_meat = lang.getString("suspicious-meat"); - medical_kit = lang.getString("medical-kit"); - water_bowl = lang.getString("water-bowl"); - dirty_water = lang.getString("dirty-water"); - dirty_water_lore = lang.getString("dirty-water-lore"); - dirty_water_color = lang.getInt("dirty-water-color"); - clean_water = lang.getString("clean-water"); - clean_water_lore = lang.getString("clean-water-lore"); - clean_water_color = lang.getInt("clean-water-color"); - purified_water = lang.getString("purified-water"); - purified_water_lore = lang.getString("purified-water-lore"); - purified_water_color = lang.getInt("purified-water-color"); - coffee_bean_name = lang.getString("coffee-bean-name"); - coffee_name = lang.getString("coffee-name"); - coffee_color = lang.getInt("coffee-color"); - cold_milk_name = lang.getString("cold-milk-name"); - cold_milk_color = lang.getInt("cold-milk-color"); - hot_milk_name = lang.getString("hot-milk-name"); - hot_milk_color = lang.getInt("hot-milk-color"); - hot_milk_drink = lang.getString("hot-milk-drink"); - breeding_egg_name = lang.getString("breeding-egg-name"); - - flint_sickle = lang.getString("flint_sickle"); - stone_sickle = lang.getString("stone_sickle"); - iron_sickle = lang.getString("iron_sickle"); - diamond_sickle = lang.getString("diamond_sickle"); - campfire_name = lang.getString("campfire-name"); - campfire_lore = lang.getString("campfire-lore"); - - bee_helmet_name = lang.getString("bee-helmet-name"); - bee_chest_name = lang.getString("bee-chest-name"); - bee_legs_name = lang.getString("bee-legs-name"); - bee_boots_name = lang.getString("bee-boots-name"); - bee_suit_lore = lang.getString("bee-suit-lore"); - snow_boots_name = lang.getString("snow-boots-name"); - snow_boots_lore = lang.getString("snow-boots-lore"); - rain_boots_name = lang.getString("rain-boots-name"); - rain_boots_lore = lang.getString("rain-boots-lore"); - - cmd_player_not_online = lang.getString("cmd-player-not-online"); - cmd_heal_self = lang.getString("cmd-heal-self"); - cmd_heal_by = lang.getString("cmd-heal-by"); - cmd_heal_other = lang.getString("cmd-heal-other"); - - Utils.sendColoredMsg(sender, prefix + loaded); - } - - // Used to update config - @SuppressWarnings("ConstantConditions") - private void matchConfig(FileConfiguration config, File file) { - try { - boolean hasUpdated = false; - InputStream test = plugin.getResource(file.getName()); - assert test != null; - InputStreamReader is = new InputStreamReader(test); - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(is); - for (String key : defConfig.getConfigurationSection("").getKeys(true)) { - if (!config.contains(key)) { - config.set(key, defConfig.get(key)); - hasUpdated = true; - } - } - for (String key : config.getConfigurationSection("").getKeys(true)) { - if (!defConfig.contains(key)) { - config.set(key, null); - hasUpdated = true; - } - } - if (hasUpdated) - config.save(file); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void saveLang(YamlConfiguration lang, File file) { - try { - lang.save(file); - String prefix = lang.getString("prefix"); - Utils.sendColoredMsg(Bukkit.getConsoleSender(), prefix + "&7" + lang_yml + " &aUpdated"); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/config/PlayerDataConfig.java b/src/main/java/tk/shanebee/survival/config/PlayerDataConfig.java deleted file mode 100644 index 5802b31..0000000 --- a/src/main/java/tk/shanebee/survival/config/PlayerDataConfig.java +++ /dev/null @@ -1,71 +0,0 @@ -package tk.shanebee.survival.config; - -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.file.YamlConfiguration; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; - -import java.io.File; -import java.io.IOException; - -public class PlayerDataConfig { - - private final Survival plugin; - private File playerDirectory = null; - - public PlayerDataConfig(Survival plugin) { - this.plugin = plugin; - loadPlayerDirectory(); - } - - private void loadPlayerDirectory() { - if (playerDirectory == null) { - playerDirectory = new File(plugin.getDataFolder(), "playerData"); - } - if (!playerDirectory.exists()) { - //noinspection ResultOfMethodCallIgnored - playerDirectory.mkdir(); - } - } - - public boolean needsConversion() { - File file = new File(playerDirectory, "converted.yml"); - return !file.exists(); - } - - public void createConvertedFile(int conversions) { - File file = new File(playerDirectory, "converted.yml"); - YamlConfiguration converted = YamlConfiguration.loadConfiguration(file); - converted.set("converted", conversions); - converted.options().header("This file is a placeholder, do not delete this file"); - saveFile(converted, file); - } - - public boolean hasPlayerDataFile(OfflinePlayer player) { - File file = new File(playerDirectory, player.getUniqueId().toString() + ".yml"); - return file.exists(); - } - - public PlayerData getPlayerDataFromFile(OfflinePlayer player) { - File file = new File(playerDirectory, player.getUniqueId().toString() + ".yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - - return ((PlayerData) config.get("player-data")); - } - - public void savePlayerDataToFile(PlayerData playerData) { - File file = new File(playerDirectory, playerData.getUuid().toString() + ".yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(file); - config.set("player-data", playerData); - saveFile(config, file); - } - - private void saveFile(YamlConfiguration config, File file) { - try { - config.save(file); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/data/Board.java b/src/main/java/tk/shanebee/survival/data/Board.java deleted file mode 100644 index 69e7ee7..0000000 --- a/src/main/java/tk/shanebee/survival/data/Board.java +++ /dev/null @@ -1,194 +0,0 @@ -package tk.shanebee.survival.data; - -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.ScoreboardManager; -import org.bukkit.scoreboard.Team; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.util.Utils; -import tk.shanebee.survival.util.Validate; - -import java.util.HashMap; -import java.util.Map; - -/** - * Represents a team based scoreboard for a player - *

This class also has a map that holds all player scoreboards

- */ -@SuppressWarnings("unused") -public class Board { - - // STATIC STUFF - private static final Map BOARD_MAP = new HashMap<>(); - - /** - * Get the Board for a specific player - *
- * If no Board is available, a new one will be created - * - * @param player Player to grab scoreboard for - * @return Board of player - */ - public static Board getBoard(Player player) { - if (BOARD_MAP.containsKey(player)) { - return BOARD_MAP.get(player); - } else { - return createBoard(player); - } - } - - /** - * Create a Board for a player - *
- * Useful in a join event - * - * @param player Player to create Board for - */ - public static Board createBoard(Player player) { - Board board = new Board(player, false); - BOARD_MAP.put(player, board); - return board; - } - - /** - * Remove a Board for a player - *
- * Useful when the player leaves the server - * - * @param player Player to remove Board for - */ - public static void removeBoard(Player player) { - if (BOARD_MAP.containsKey(player)) { - Board board = BOARD_MAP.get(player); - board.toggle(false); - board.clearBoard(); - } - BOARD_MAP.remove(player); - } - - /** - * Clear and remove all Boards - */ - public static void clearBoards() { - for (Board board : BOARD_MAP.values()) { - board.clearBoard(); - } - BOARD_MAP.clear(); - } - - // OBJECT STUFF - private final Player player; - private final Scoreboard oldScoreboard; - private final Scoreboard scoreboard; - private final Objective board; - private final Team[] lines = new Team[15]; - private final String[] entries = new String[]{"&1", "&2", "&3", "&4", "&5", "&6", "&7", "&8", "&9", "&0", "&a", "&b", "&c", "&d", "&e"}; - private boolean on; - - public Board(Player player, boolean load) { - this.player = player; - this.on = true; - Survival plugin = Survival.getInstance(); - ScoreboardManager scoreboardManager = plugin.getServer().getScoreboardManager(); - oldScoreboard = player.getScoreboard(); - if (!load) { - assert scoreboardManager != null; - scoreboard = scoreboardManager.getNewScoreboard(); - this.player.setScoreboard(scoreboard); - board = scoreboard.registerNewObjective("Board", "dummy", "Board"); - board.setDisplaySlot(DisplaySlot.SIDEBAR); - board.setDisplayName(" "); - - for (int i = 0; i < 15; i++) { - lines[i] = scoreboard.registerNewTeam("line" + (i + 1)); - } - - for (int i = 0; i < 15; i++) { - lines[i].addEntry(getColString(entries[i])); - } - } else { - scoreboard = player.getScoreboard(); - board = scoreboard.getObjective("Board"); - - for (int i = 0; i < 15; i++) { - lines[i] = scoreboard.getTeam("line" + (i + 1)); - } - } - } - - /** - * Set the title of this Board - * - * @param title Title to set - */ - public void setTitle(String title) { - board.setDisplayName(getColString(title)); - } - - /** - * Set a specific line for this Board - *

Lines 1 - 15

- * - * @param line Line to set (1 - 15) - * @param text Text to put in line - */ - public void setLine(int line, String text) { - Validate.isBetween(line, 1, 15); - Team t = lines[line - 1]; - t.setPrefix(getColString(text)); - board.getScore(getColString(entries[line - 1])).setScore(line); - } - - /** - * Delete a line in this Board - *

Lines 1 - 15

- * - * @param line Line to delete (1 - 15) - */ - public void deleteLine(int line) { - Validate.isBetween(line, 1, 15); - scoreboard.resetScores(getColString(entries[line - 1])); - } - - /** - * Clear all lines of this Board - */ - public void clearBoard() { - for (int i = 1; i < 16; i++) { - deleteLine(i); - } - } - - /** - * Toggle this Board on or off - *
- * When off, will not be visible to player, but can still update - * - * @param on Whether on or off - */ - public void toggle(boolean on) { - if (on) { - player.setScoreboard(this.scoreboard); - this.on = true; - } else { - player.setScoreboard(this.oldScoreboard); - this.on = false; - } - } - - /** - * Check if this Board is on or off - * - * @return True if on else false - */ - public boolean isOn() { - return this.on; - } - - private String getColString(String string) { - return Utils.getColoredString(string); - } - -} diff --git a/src/main/java/tk/shanebee/survival/events/ThirstLevelChangeEvent.java b/src/main/java/tk/shanebee/survival/events/ThirstLevelChangeEvent.java deleted file mode 100644 index 74e3506..0000000 --- a/src/main/java/tk/shanebee/survival/events/ThirstLevelChangeEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -package tk.shanebee.survival.events; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -/** - * Called when a player's thirst level changes - */ -@SuppressWarnings("unused") -public class ThirstLevelChangeEvent extends Event implements Cancellable { - - private final static HandlerList handlers = new HandlerList(); - private final Player player; - private final int thirst; - private final int changed; - private boolean isCancelled; - - public ThirstLevelChangeEvent(Player player, int changed, int thirst) { - this.player = player; - this.changed = changed; - this.thirst = thirst; - this.isCancelled = false; - } - - /** Get the player involved in this event - * @return The player involved in this event - */ - public Player getPlayer() { - return this.player; - } - - /** Get the new thirst level from the event - * @return The new thirst level from the event - */ - public int getThirst() { - return this.thirst; - } - - /** Get the level of thirst that was changed - * @return The level that was changed - */ - public int getChanged() { - return this.changed; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.isCancelled; - } - - @Override - public void setCancelled(boolean b) { - this.isCancelled = b; - } - -} diff --git a/src/main/java/tk/shanebee/survival/item/Item.java b/src/main/java/tk/shanebee/survival/item/Item.java deleted file mode 100644 index 84f5b9b..0000000 --- a/src/main/java/tk/shanebee/survival/item/Item.java +++ /dev/null @@ -1,323 +0,0 @@ -package tk.shanebee.survival.item; - -import com.google.common.base.Preconditions; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import tk.shanebee.survival.managers.ItemManager; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * Custom SurvivalPlus items - */ -public class Item { - - static final ItemConfig ITEM_CONFIG = new ItemConfig(); - private static final Map ALL_ITEMS = new HashMap<>(); - - // TOOLS - public static final Item HATCHET = get("hatchet", Material.WOODEN_AXE, 1, -1, 0.85); - public static final Item MATTOCK = get("mattock", Material.WOODEN_PICKAXE, 1, -1, 0.85); - public static final Item SHIV = get("shiv", Material.WOODEN_HOE, 1, -1, 0.85); - public static final Item HAMMER = get("hammer", Material.WOODEN_SWORD, 1, -1, 0.85); - public static final Item FIRESTRIKER = get("firestriker", Material.WOODEN_SHOVEL, 1, -1, 0.0); - public static final Item GRAPPLING_HOOK = get("grappling_hook", Material.FISHING_ROD, 1, -1, 0.95); - public static final Item COMPASS = get("compass", Material.COMPASS, 1, -1, 0.85); - public static final Item FLINT_SICKLE = get("flint_sickle", Material.WOODEN_HOE, 4, -1, 1.0); - public static final Item STONE_SICKLE = get("stone_sickle", Material.WOODEN_HOE, 2, -1, 1.0); - public static final Item IRON_SICKLE = get("iron_sickle", Material.IRON_HOE, 1, -1, 0.90); - public static final Item DIAMOND_SICKLE = get("diamond_sickle", Material.DIAMOND_HOE, 1, -1, 0.90); - public static final Item MEDIC_KIT = get("medic_kit", Material.CLOCK, 1, 0, 0); - public static final Item RECURVE_BOW = get("recurve_bow", Material.BOW, 1, 1.25, 0.9); - public static final Item RECURVE_CROSSBOW = get("recurve_crossbow", Material.CROSSBOW, 1, 1.75, 0.9); - - // LEGENDARY TOOLS - public static final Item VALKYRIES_AXE = get("valkyries_axe", Material.DIAMOND_AXE, 1, 2.5, 0.95); - public static final Item QUARTZ_PICKAXE = get("quartz_pickaxe", Material.DIAMOND_PICKAXE, 1, 2.5, 0.95); - public static final Item OBSIDIAN_MACE = get("obsidian_mace", Material.DIAMOND_SHOVEL, 1, 2.5, 0.95); - public static final Item ENDER_GIANT_BLADE = get("ender_giant_blade", Material.DIAMOND_HOE, 2, 2.5, 0.95); - public static final Item BLAZE_SWORD = get("blaze_sword", Material.DIAMOND_SWORD, 1, 2.5, 0.95); - - // ARMOR - public static final Item REINFORCED_LEATHER_BOOTS = get("reinforced_leather_boots", Material.CHAINMAIL_BOOTS, 1, 2, 0.85); - public static final Item REINFORCED_LEATHER_TUNIC = get("reinforced_leather_tunic", Material.CHAINMAIL_CHESTPLATE, 1, 2, 0.85); - public static final Item REINFORCED_LEATHER_TROUSERS = get("reinforced_leather_trousers", Material.CHAINMAIL_LEGGINGS, 1, 2, 0.85); - public static final Item REINFORCED_LEATHER_HELMET = get("reinforced_leather_helmet", Material.CHAINMAIL_HELMET, 1, 2, 0.85); - public static final Item GOLDEN_SABATONS = get("golden_sabatons", Material.GOLDEN_BOOTS, 0, -1, 1.0); - public static final Item GOLDEN_GUARD = get("golden_guard", Material.GOLDEN_CHESTPLATE, 0, -1, 1.0); - public static final Item GOLDEN_GREAVES = get("golden_greaves", Material.GOLDEN_LEGGINGS, 0, -1, 1.0); - public static final Item GOLDEN_CROWN = get("golden_crown", Material.GOLDEN_HELMET, 0, -1, 1.0); - public static final Item IRON_BOOTS = get("iron_boots", Material.IRON_BOOTS, 0, -1, 1.0); - public static final Item IRON_CHESTPLATE = get("iron_chestplate", Material.IRON_CHESTPLATE, 0, -1, 1.0); - public static final Item IRON_LEGGINGS = get("iron_leggings", Material.IRON_LEGGINGS, 0, -1, 1.0); - public static final Item IRON_HELMET = get("iron_helmet", Material.IRON_HELMET, 0, -1, 1.0); - public static final Item DIAMOND_BOOTS = get("diamond_boots", Material.DIAMOND_BOOTS, 0, -1, 1.0); - public static final Item DIAMOND_CHESTPLATE = get("diamond_chestplate", Material.DIAMOND_CHESTPLATE, 0, -1, 1.0); - public static final Item DIAMOND_HELMET = get("diamond_helmet", Material.DIAMOND_HELMET, 0, -1, 1.0); - public static final Item DIAMOND_LEGGINGS = get("diamond_leggings", Material.DIAMOND_LEGGINGS, 0, -1, 1.0); - public static final Item NETHERITE_HELMET = get("netherite_helmet", Material.NETHERITE_HELMET, 0, -1, 1.0); - public static final Item NETHERITE_CHESTPLATE = get("netherite_chestplate", Material.NETHERITE_CHESTPLATE, 0, -1, 1.0); - public static final Item NETHERITE_LEGGINGS = get("netherite_leggings", Material.NETHERITE_LEGGINGS, 0, -1, 1.0); - public static final Item NETHERITE_BOOTS = get("netherite_boots", Material.NETHERITE_BOOTS, 0, -1, 1.0); - public static final Item BEEKEEPER_HELMET = get("beekeeper_helmet", Material.LEATHER_HELMET, 10881, 1.2, 1.0); - public static final Item BEEKEEPER_CHESTPLATE = get("beekeeper_chestplate", Material.LEATHER_CHESTPLATE, 10881, 1.2, 1.0); - public static final Item BEEKEEPER_LEGGINGS = get("beekeeper_leggings", Material.LEATHER_LEGGINGS, 10881, 1.2, 1.0); - public static final Item BEEKEEPER_BOOTS = get("beekeeper_boots", Material.LEATHER_BOOTS, 10881, 1.2, 1.0); - public static final Item SNOW_BOOTS = get("snow_boots", Material.LEATHER_BOOTS, 10882, 1.4, 0.97); - public static final Item RAIN_BOOTS = get("rain_boots", Material.LEATHER_BOOTS, 10883, 1.2, 0.97); - - // BLOCKS - public static final Item WORKBENCH = get("workbench", Material.CRAFTING_TABLE, 0); - public static final Item CAMPFIRE = get("campfire", Material.CAMPFIRE, 1); - - // MISC - public static final Item FERMENTED_SKIN = get("fermented_skin", Material.RABBIT_HIDE, 0); - public static final Item COFFEE_BEAN = get("coffee_bean", Material.COCOA_BEANS, 1); - public static final Item BREEDING_EGG = get("breeding_egg", Material.EGG, 10885); - - // FOOD - public static final Item SUSPICIOUS_MEAT = get("suspicious_meat", Material.SUSPICIOUS_STEW, 10881); - - // DRINKS - public static final Item DIRTY_WATER = get("dirty_water", Material.POTION, 1); - public static final Item CLEAN_WATER = get("clean_water", Material.POTION, 2); - public static final Item PURIFIED_WATER = get("purified_water", Material.POTION, 3); - public static final Item COFFEE = get("coffee", Material.POTION, 4); - public static final Item HOT_MILK = get("hot_milk", Material.POTION, 5); - public static final Item COLD_MILK = get("cold_milk", Material.POTION, 6); - - /** - * @deprecated Use {@link #WATER_BOWL} instead - */ - @SuppressWarnings("DeprecatedIsStillUsed") - @Deprecated // Removed in 3.11.0 - Will remove old water bowl in future - public static final Item WATER_BOWL_OLD = get("water_bowl_old", Material.BEETROOT_SOUP, 1); - public static final Item WATER_BOWL = get("water_bowl", Material.POTION, 10881); - - // TODO Experimental - public static final Item PERSISTENT_TORCH = get("persistent_torch", Material.TORCH, 1); - - private static Item get(String key, Material material, int model) { - String prefix = String.format("Registering Item (%s): ", key); - Preconditions.checkArgument(key != null, "%sKey must not be null", prefix); - - int data = ITEM_CONFIG.getModelData(key, model); - Preconditions.checkArgument(model >= 0 && model <= 99999999, "%sModel must be between 0 and 99999999, found %s", prefix, data); - - Item item = new Item(key, material, data); - ALL_ITEMS.put(key, item); - return item; - } - - @SuppressWarnings("ConstantConditions") - private static Item get(@NotNull String key, @NotNull Material material, int model, double repairCost, double repairPercent) { - String prefix = String.format("Registering Item (%s): ", key); - Preconditions.checkArgument(key != null, "%sKey must not be null", prefix); - - int data = ITEM_CONFIG.getModelData(key, model); - Preconditions.checkArgument(model >= 0 && model <= 99999999, "%sModel must be between 0 and 99999999, found %s", prefix, data); - - double cost = ITEM_CONFIG.getRepairCost(key, repairCost); - Preconditions.checkArgument(cost >= -1, "%sCost must be >= -1, found %s", prefix, cost); - - double percent = ITEM_CONFIG.getRepairPercent(key, repairPercent); - Preconditions.checkArgument(percent >= 0.0f && percent <= 1.0f, "%sRepair percent must be between 0.0 and 1.0, found %s", prefix, percent); - - Item item = new Item(key, material, data, cost, percent); - ALL_ITEMS.put(key, item); - return item; - } - - /** - * Get an Item based on a key - * - * @param value Key for item - * @return Item based on key - */ - public static Item valueOf(String value) { - if (ALL_ITEMS.containsKey(value.toLowerCase())) { - return ALL_ITEMS.get(value.toLowerCase()); - } - return null; - } - - /** - * Get a collection of all registered Items - * - * @return Collection of all registered Items - */ - public static Collection values() { - return ALL_ITEMS.values(); - } - - // OBJECT - - private final String key; - private final Material materialType; - private final int modelData; - private final double repairCostMultiplier; - private final double repairPercent; - - Item(@NotNull String key, @NotNull Material mat, int customModelData) { - this.key = key; - this.modelData = customModelData; - this.materialType = mat; - this.repairCostMultiplier = -1; - this.repairPercent = 0; - } - - Item(@NotNull String key, @NotNull Material mat, int customModelData, double repairCost, double repairPercent) { - this.key = key; - this.modelData = customModelData; - this.materialType = mat; - this.repairCostMultiplier = repairCost; - this.repairPercent = repairPercent; - } - - /** - * Get the key of this item - * - * @return Key of this item - */ - @SuppressWarnings("unused") - public String getKey() { - return key; - } - - /** - * Get the Material of this item - * - * @return Material of this item - */ - public Material getMaterialType() { - return materialType; - } - - /** - * Get the CustomModelData of this item - * - * @return CustomModelData of this item - */ - public int getModelData() { - return modelData; - } - - public double getRepairCostMultiplier() { - return repairCostMultiplier; - } - - public double getRepairPercent() { - return repairPercent; - } - - /** - * Get a new ItemStack based on this item - * - * @return New ItemStack based on this item - */ - public ItemStack getItem() { - return ItemManager.get(this); - } - - /** - * Get a new ItemStack based on this item - * - * @param amount Stack size - * @return New ItemStack based on this item - */ - public ItemStack getItem(int amount) { - ItemStack itemStack = getItem(); - itemStack.setAmount(amount); - return itemStack; - } - - /** - * Compare this item with an ItemStack - * - * @param itemStack ItemStack to check - * @return True if matched - */ - public boolean compare(@NotNull ItemStack itemStack) { - if (itemStack.getType() == materialType) { - ItemMeta meta = itemStack.getItemMeta(); - if (meta != null && meta.hasCustomModelData()) { - return meta.getCustomModelData() == modelData; - } else { - return modelData == 0; - } - } - return false; - } - - @Nullable - public static Item getFromStack(@NotNull ItemStack itemStack) { - for (Item value : ALL_ITEMS.values()) { - if (value.compare(itemStack)) { - return value; - } - } - return null; - } - - /** - * Tags for different {@link Item} groups - */ - @SuppressWarnings("unused") - public enum Tags { - /** - * Any sickle - */ - SICKLES(FLINT_SICKLE, STONE_SICKLE, IRON_SICKLE, DIAMOND_SICKLE), - /** - * Any reinforced leather armor - */ - REINFORCED_LEATHER_ARMOR(REINFORCED_LEATHER_BOOTS, REINFORCED_LEATHER_TROUSERS, - REINFORCED_LEATHER_TUNIC, REINFORCED_LEATHER_HELMET), - /** - * Any water bottle - */ - WATER_BOTTLE(DIRTY_WATER, CLEAN_WATER, PURIFIED_WATER), - /** - * Any drinkable item - */ - DRINKABLE(DIRTY_WATER, CLEAN_WATER, PURIFIED_WATER, WATER_BOWL, - COLD_MILK, HOT_MILK, COFFEE), - - /** - * Any legendary item - */ - LEGENDARY(BLAZE_SWORD, OBSIDIAN_MACE, VALKYRIES_AXE, ENDER_GIANT_BLADE, QUARTZ_PICKAXE); - - private final Item[] items; - - Tags(Item... items) { - this.items = items; - } - - /** - * Get all items tagged in this group - * - * @return All items tagged in this group - */ - public Item[] getItems() { - return items; - } - - /** - * Check if an ItemStack is tagged in a group of custom {@link Item} - * - * @param item ItemStack to check - * @return True if item matches tag - */ - public boolean isTagged(ItemStack item) { - return ItemManager.compare(item, items); - } - - } - -} diff --git a/src/main/java/tk/shanebee/survival/item/ItemConfig.java b/src/main/java/tk/shanebee/survival/item/ItemConfig.java deleted file mode 100644 index 55b7a7e..0000000 --- a/src/main/java/tk/shanebee/survival/item/ItemConfig.java +++ /dev/null @@ -1,103 +0,0 @@ -package tk.shanebee.survival.item; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.util.Utils; - -import java.io.File; -import java.io.IOException; - -class ItemConfig { - - static ItemConfig INSTANCE; - private final Survival plugin = Survival.getInstance(); - private final String prefix = plugin.getLang().prefix; - private FileConfiguration settings; - private File configFile; - - ItemConfig() { - INSTANCE = this; - loadDefaultSettings(); - Nutrition.setup(); - save(); - Utils.sendColoredConsoleMsg(prefix + "&7items.yml &aloaded"); - } - - private void loadDefaultSettings() { - if (configFile == null) { - configFile = new File(plugin.getDataFolder(), "items.yml"); - } - if (!configFile.exists()) { - plugin.saveResource("items.yml", false); - settings = YamlConfiguration.loadConfiguration(configFile); - Utils.sendColoredConsoleMsg(prefix + "&aNew items.yml created"); - } else { - settings = YamlConfiguration.loadConfiguration(configFile); - } - } - - int getModelData(String key, int defaultValue) { - int data; - String path = "items." + key + ".model_data"; - if (settings.contains(path)) { - data = settings.getInt(path); - } else { - data = defaultValue; - settings.set(path, data); - save(); - } - return data; - } - - int[] getNutritionValues(String key, int carbs, int proteins, int vitamins) { - String path = "nutritions." + key + "."; - String[] paths = new String[]{path + "carbs", path + "proteins", path + "vitamins"}; - int[] nutritions = new int[]{carbs, proteins, vitamins}; - if (settings.contains(paths[0])) { - nutritions[0] = settings.getInt(paths[0]); - } else { - settings.set(paths[0], carbs); - } - if (settings.contains(paths[1])) { - nutritions[1] = settings.getInt(paths[1]); - } else { - settings.set(paths[1], proteins); - } - if (settings.contains(paths[2])) { - nutritions[2] = settings.getInt(paths[2]); - } else { - settings.set(paths[2], vitamins); - } - return nutritions; - } - - double getRepairCost(String key, double defaultValue) { - String path = "items." + key + ".repair_cost_multiplier"; - if (settings.contains(path)) { - return settings.getDouble(path); - } else { - settings.set(path, defaultValue); - return defaultValue; - } - } - - double getRepairPercent(String key, double defaultValue) { - String path = "items." + key + ".repair_percent"; - if (settings.contains(path)) { - return settings.getDouble(path); - } else { - settings.set(path, defaultValue); - return defaultValue; - } - } - - void save() { - try { - settings.save(configFile); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/EventManager.java b/src/main/java/tk/shanebee/survival/listeners/EventManager.java deleted file mode 100644 index 1631d0e..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/EventManager.java +++ /dev/null @@ -1,151 +0,0 @@ -package tk.shanebee.survival.listeners; - -import org.bukkit.Bukkit; -import org.bukkit.plugin.PluginManager; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.listeners.block.BlockBreak; -import tk.shanebee.survival.listeners.block.BlockPlace; -import tk.shanebee.survival.listeners.block.BurnoutTorches; -import tk.shanebee.survival.listeners.block.Campfire; -import tk.shanebee.survival.listeners.block.Chairs; -import tk.shanebee.survival.listeners.block.NoAnvil; -import tk.shanebee.survival.listeners.block.SnowGeneration; -import tk.shanebee.survival.listeners.block.SnowballThrow; -import tk.shanebee.survival.listeners.block.WorkbenchShare; -import tk.shanebee.survival.listeners.entity.BeeKeeperSuit; -import tk.shanebee.survival.listeners.entity.ChestPigmen; -import tk.shanebee.survival.listeners.entity.ChickenSpawn; -import tk.shanebee.survival.listeners.entity.EntityDeath; -import tk.shanebee.survival.listeners.entity.LivingSlime; -import tk.shanebee.survival.listeners.entity.MerchantTrades; -import tk.shanebee.survival.listeners.entity.PiglinBarter; -import tk.shanebee.survival.listeners.item.*; -import tk.shanebee.survival.listeners.player.EnergyChange; -import tk.shanebee.survival.listeners.player.PlayerDataListener; -import tk.shanebee.survival.listeners.server.Guide; -import tk.shanebee.survival.listeners.server.InventoryUpdate; -import tk.shanebee.survival.listeners.server.LocalChat; -import tk.shanebee.survival.listeners.server.NoPos; -import tk.shanebee.survival.listeners.server.RecipeDiscovery; -import tk.shanebee.survival.listeners.server.SetResourcePack; -import tk.shanebee.survival.util.Utils; - -/** - * Internal use only - */ -public class EventManager { - - private final Survival plugin; - private final int LOCAL_CHAT; - private final Config config; - - public EventManager(Survival plugin) { - this.plugin = plugin; - this.config = plugin.getSurvivalConfig(); - this.LOCAL_CHAT = config.LOCAL_CHAT_DISTANCE; - } - - public void registerEvents() { - PluginManager pm = plugin.getServer().getPluginManager(); - pm.registerEvents(this.plugin, this.plugin); - pm.registerEvents(new RecipeDiscovery(plugin), this.plugin); - Bukkit.getPluginManager().registerEvents(new PlayerDataListener(this.plugin), this.plugin); - - if (config.SURVIVAL_ENABLED) { - pm.registerEvents(new BlockBreak(plugin), this.plugin); - pm.registerEvents(new BlockPlace(plugin), this.plugin); - pm.registerEvents(new FirestrikerClick(plugin), this.plugin); - pm.registerEvents(new ShivPoison(this.plugin), this.plugin); - pm.registerEvents(new WaterBowl(plugin), this.plugin); - pm.registerEvents(new Campfire(plugin), this.plugin); - //pm.registerEvents(new Backpack(), this.plugin); needs to be reworked - } - pm.registerEvents(new NoAnvil(plugin), this.plugin); - if (config.MECHANICS_BOW) - pm.registerEvents(new Bow(plugin), this.plugin); - if (config.MECHANICS_GRAPPLING_HOOK) - pm.registerEvents(new GrapplingHook(plugin), this.plugin); - if (config.LEGENDARY_OBSIDIAN_MACE) - pm.registerEvents(new ObsidianMaceWeakness(plugin), this.plugin); - if (config.LEGENDARY_VALKYRIE) - pm.registerEvents(new Valkyrie(plugin), this.plugin); - if (config.LEGENDARY_GIANTBLADE) - pm.registerEvents(new GiantBlade(plugin), this.plugin); - if (config.LEGENDARY_BLAZESWORD) - pm.registerEvents(new BlazeSword(), this.plugin); - if (LOCAL_CHAT > -1) - pm.registerEvents(new LocalChat(plugin), this.plugin); - if (config.MECHANICS_COMPASS_WAYPOINT) - pm.registerEvents(new CompassWaypoint(this.plugin), this.plugin); - if (config.MECHANICS_MEDIC_KIT) - pm.registerEvents(new MedicKit(plugin), this.plugin); - - pm.registerEvents(new WaterBottleCrafting(plugin), this.plugin); - - pm.registerEvents(new SetResourcePack(plugin), this.plugin); - - if (config.MECHANICS_RAW_MEAT_HUNGER) - pm.registerEvents(new RawMeatHunger(), this.plugin); - if (config.MECHANICS_THIRST_ENABLED) { - pm.registerEvents(new Consume(this.plugin), this.plugin); - if (config.MECHANICS_THIRST_PURIFY_WATER) - pm.registerEvents(new CauldronWaterBottle(), this.plugin); - } - if (config.MECHANICS_POISON_POTATO) - pm.registerEvents(new PoisonousPotato(), this.plugin); - if (config.MECHANICS_SHARED_WORKBENCH) - pm.registerEvents(new WorkbenchShare(plugin), this.plugin); - if (config.MECHANICS_CHAIRS_ENABLED) - pm.registerEvents(new Chairs(plugin), this.plugin); - if (config.MECHANICS_COOKIE_BOOST) - pm.registerEvents(new CookieHealthBoost(), this.plugin); - if (config.MECHANICS_BEET_STRENGTH) - pm.registerEvents(new BeetrootStrength(), this.plugin); - if (config.MECHANICS_CLOWN_FISH) - pm.registerEvents(new Clownfish(), this.plugin); - if (config.MECHANICS_LIVING_SLIME) - pm.registerEvents(new LivingSlime(plugin), this.plugin); - if (config.MECHANICS_ENERGY_ENABLED) - pm.registerEvents(new EnergyChange(plugin), this.plugin); - if (config.MECHANICS_FOOD_DIVERSITY_ENABLED) - pm.registerEvents(new FoodDiversityConsume(plugin), this.plugin); - if (config.MECHANICS_RECURVED_BOW) - pm.registerEvents(new RecurvedBow(plugin), this.plugin); - if (config.MECHANICS_SNOWBALL_REVAMP) - pm.registerEvents(new SnowballThrow(), this.plugin); - if (config.MECHANICS_SNOW_GEN_REVAMP) - pm.registerEvents(new SnowGeneration(plugin), this.plugin); - if (config.ENTITY_MECHANICS_CHICKEN_BREEDING_ENABLED) - pm.registerEvents(new ChickenSpawn(this.plugin), this.plugin); - if (config.WELCOME_GUIDE_ENABLED) - pm.registerEvents(new Guide(plugin), this.plugin); - if (config.MECHANICS_BURNOUT_TORCH_ENABLED) // TODO experimental feature, not 100% sure about this - pm.registerEvents(new BurnoutTorches(this.plugin), this.plugin); - pm.registerEvents(new InventoryUpdate(), this.plugin); - - if (config.ENTITY_MECHANICS_PIGMEN_CHEST_ENABLED) - pm.registerEvents(new ChestPigmen(this.plugin), this.plugin); - - if (config.NO_POS) { - if (Utils.isRunningMinecraft(1, 16)) { - Utils.log("&7NoPos &ccurrently broken. &7Please use the &breducedDebugInfo &7gamerule for the time being"); - } else { - Bukkit.getPluginManager().registerEvents(new NoPos(), this.plugin); - Utils.log("&7NoPos &aimplemented &7- F3 coordinates are disabled!"); - } - } - if (config.ENTITY_MECHANICS_BEEKEEPER_SUIT_ENABLED) { - Bukkit.getPluginManager().registerEvents(new BeeKeeperSuit(), this.plugin); - } - if (config.SURVIVAL_UPDATE_MERCHANT_TRADES) { - pm.registerEvents(new MerchantTrades(this.plugin), this.plugin); - } - pm.registerEvents(new PiglinBarter(this.plugin), this.plugin); - // Config handled within this event - pm.registerEvents(new EntityDeath(this.plugin), this.plugin); - pm.registerEvents(new RepairCrafting(), this.plugin); - - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/block/BlockBreak.java b/src/main/java/tk/shanebee/survival/listeners/block/BlockBreak.java deleted file mode 100644 index 4665fc6..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/block/BlockBreak.java +++ /dev/null @@ -1,290 +0,0 @@ - -package tk.shanebee.survival.listeners.block; - -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.Ageable; -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.BlockPhysicsEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.Random; - -public class BlockBreak implements Listener { - - private Config settings; - private Lang lang; - - public BlockBreak(Survival plugin) { - this.lang = plugin.getLang(); - this.settings = plugin.getSurvivalConfig(); - } - - @EventHandler(priority = EventPriority.HIGHEST) - private void onBlockBreak(BlockBreakEvent event) { - if (event.isCancelled()) return; - Player player = event.getPlayer(); - - ItemStack tool = player.getInventory().getItemInMainHand(); - - Block block = event.getBlock(); - Material material = block.getType(); - - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - if (!ItemManager.compare(tool, Item.QUARTZ_PICKAXE)) { - if (settings.BREAK_ONLY_WITH_SHOVEL) { - if (!Utils.isShovel(tool.getType())) { - if (Utils.requiresShovel(material)) { - event.setCancelled(true); - player.updateInventory(); - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.task_must_use_shovel)); - } - //Flint - if (material == Material.GRAVEL) { - event.setDropItems(false); - - Random rand = new Random(); - double chance = rand.nextDouble(); - - if (chance <= settings.DROP_RATE_FLINT) - event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), new ItemStack(Material.FLINT)); - } - } else { - Block above = block.getRelative(BlockFace.UP); - switch (block.getType()) { - case GRASS_BLOCK: - case DIRT: - case PODZOL: - case COARSE_DIRT: - case FARMLAND: - if (Utils.isFarmable(above.getType())) { - above.setType(Material.AIR); - } - } - } - } - - if (settings.BREAK_ONLY_WITH_AXE && !Utils.isAxe(tool.getType())) { - if (Utils.requiresAxe(material)) { - event.setCancelled(true); - player.updateInventory(); - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.task_must_use_axe)); - } - - //Fix half door glitch - if (Tag.DOORS.isTagged(material)) { - if (block.getRelative(BlockFace.UP).getType() == material) - block.getRelative(BlockFace.UP).getState().update(true); - if (block.getRelative(BlockFace.DOWN).getType() == material) - block.getRelative(BlockFace.DOWN).getState().update(true); - } - } - if (settings.BREAK_ONLY_WITH_PICKAXE && !Utils.isPickaxe(tool.getType())) { - if (Utils.requiresPickaxe(material)) { - event.setCancelled(true); - player.updateInventory(); - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.task_must_use_pick)); - } - } - - if (settings.BREAK_ONLY_WITH_SICKLE) { - if (Utils.isFarmable(material)) { - if (!Item.Tags.SICKLES.isTagged(tool)) { - event.setCancelled(true); - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.task_must_use_sickle)); - } else { - event.setDropItems(false); - Location loc = event.getBlock().getLocation(); - int random = 1; - int multiplier = 1; - boolean grown = true; - - if (event.getBlock().getBlockData() instanceof Ageable) { - Ageable crop = ((Ageable) event.getBlock().getBlockData()); - grown = crop.getAge() == crop.getMaximumAge(); - } - - // Flint/Stone sickles drop a chance of 0-1 items (not grown) or 1-2 (grown) - if (ItemManager.compare(tool, Item.FLINT_SICKLE)) { - multiplier = 4; - random = grown ? new Random().nextInt(2) + 1 : new Random().nextInt(2); - } - if (ItemManager.compare(tool, Item.STONE_SICKLE)) { - multiplier = 2; - random = grown ? new Random().nextInt(2) + 1 : new Random().nextInt(2); - } - // Iron/Diamond sickles drop a chance of 1 (not grown) or 2-4 items (grown) - if (ItemManager.compare(tool, Item.IRON_SICKLE, Item.DIAMOND_SICKLE)) { - random = grown ? new Random().nextInt(2) + 3 : 1; - } - - for (Material drop : Utils.getDrops(material, grown)) { - if (drop != Material.AIR && random != 0) { - assert loc.getWorld() != null; - if (drop == Material.PUMPKIN) { // prevent duping pumpkins - random = 1; - } - loc.getWorld().dropItemNaturally(loc, new ItemStack(drop, random)); - } - } - if (tool.getType().getMaxDurability() < Utils.getDurability(tool) + multiplier) { - player.getInventory().setItemInMainHand(null); - player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1); - return; - } - Utils.setDurability(tool, Utils.getDurability(tool) + multiplier); - player.updateInventory(); - } - } - } - - if (!(tool.getType() == Material.SHEARS)) { - if (settings.BREAK_ONLY_WITH_SHEARS) { - if (Utils.requiresShears(material)) { - event.setCancelled(true); - player.updateInventory(); - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.task_must_use_shear)); - } - } - - //Sticks - Maybe this should be removed since 1.14+ leaves drop sticks?!?!? - if (Tag.LEAVES.isTagged(material)) { - Random rand = new Random(); - double chance = rand.nextDouble(); - - if (chance <= settings.DROP_RATE_STICK) - event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), new ItemStack(Material.STICK)); - } - } - if (settings.RECIPES_WORKBENCH && material == Material.CRAFTING_TABLE && !event.isCancelled()) { - event.setDropItems(false); - ItemStack workbench = ItemManager.get(Item.WORKBENCH); - block.getWorld().dropItem(block.getLocation(), workbench); - } - } else { - if (Utils.isOreBlock(material) || Utils.isNaturalOreBlock(material)) { - event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), new ItemStack(material)); - } - } - } - } - - @SuppressWarnings("deprecation") - @EventHandler - private void onHarvest(PlayerInteractEvent e) { - if (e.isCancelled()) return; - if (!settings.BREAK_ONLY_WITH_SICKLE) return; - if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_AIR - || e.getAction() == Action.LEFT_CLICK_BLOCK) return; - Player player = e.getPlayer(); - Block block = e.getClickedBlock(); - ItemStack tool = player.getInventory().getItemInMainHand(); - assert block != null; - if (block.getType() == Material.SWEET_BERRY_BUSH) { - Ageable bush = ((Ageable) block.getBlockData()); - if (e.getItem() != null && e.getItem().getType() == Material.BONE_MEAL) { - if (bush.getAge() == 3) { - e.setCancelled(true); - return; - } else return; - } - if (!Item.Tags.SICKLES.isTagged(tool)) { - e.setCancelled(true); - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.task_must_use_sickle)); - } else { - if (bush.getAge() >= 2) { - int berries = 0; - Location loc = block.getLocation(); - assert loc.getWorld() != null; - int multiplier = 1; - e.setCancelled(true); - int random = new Random().nextInt(5) + 1; - - if (ItemManager.compare(tool, Item.FLINT_SICKLE)) { - if (bush.getAge() == 3) { - berries = 1; - } - multiplier = 4; - } else if (ItemManager.compare(tool, Item.STONE_SICKLE)) { - if (bush.getAge() == 2) { - if (random <= 4) - berries = 1; - } else if (bush.getAge() == 3) { - if (random <= 3) - berries = 1; - else - berries = 2; - } - multiplier = 2; - } else if (ItemManager.compare(tool, Item.IRON_SICKLE, Item.DIAMOND_SICKLE)) { - if (bush.getAge() == 2) { - if (random <= 3) - berries = 1; - else - berries = 2; - } else if (bush.getAge() == 3) { - if (random <= 4) - berries = 2; - else - berries = 4; - } - } - if (berries != 0) - loc.getWorld().dropItemNaturally(loc, new ItemStack(Material.SWEET_BERRIES, berries)); - - bush.setAge(1); - block.setBlockData(bush); - int durability = Utils.getDurability(tool) + multiplier; - Utils.setDurability(tool, durability); - player.playSound(loc, Sound.ITEM_SWEET_BERRIES_PICK_FROM_BUSH, 1, 1); - if (durability >= tool.getType().getMaxDurability()) { - player.getInventory().setItemInMainHand(null); - player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1); - } - } - } - } - } - - @EventHandler - private void onWaterBreakCrops(BlockPhysicsEvent event) { - if (!settings.BREAK_ONLY_WITH_SICKLE) return; - if (event.getSourceBlock().getType() == Material.WATER) { - Material type = event.getBlock().getType(); - if (Utils.isFarmable(type)) { - if (type == Material.MELON || type == Material.PUMPKIN) return; - event.getBlock().setType(Material.AIR); - } - } - } - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.HIGHEST) - private void onTrample(PlayerInteractEvent event) { - if (event.isCancelled()) return; - if (!settings.BREAK_ONLY_WITH_SICKLE) return; - if (event.getAction() == Action.PHYSICAL) { - if (event.getClickedBlock() == null) return; - if (event.getClickedBlock().getType() == Material.FARMLAND) { - Location loc = event.getClickedBlock().getLocation(); - assert loc.getWorld() != null; - loc.getWorld().playEffect(loc, Effect.STEP_SOUND, event.getClickedBlock().getRelative(BlockFace.UP).getType()); - event.getClickedBlock().getRelative(BlockFace.UP).setType(Material.AIR); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/block/BlockPlace.java b/src/main/java/tk/shanebee/survival/listeners/block/BlockPlace.java deleted file mode 100644 index b576454..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/block/BlockPlace.java +++ /dev/null @@ -1,77 +0,0 @@ -package tk.shanebee.survival.listeners.block; - -import org.bukkit.*; -import org.bukkit.block.Block; -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.BlockPlaceEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.Random; - -public class BlockPlace implements Listener { - - private Config config; - private Lang lang; - - public BlockPlace(Survival plugin) { - this.config = plugin.getSurvivalConfig(); - this.lang = plugin.getLang(); - } - - @SuppressWarnings("ConstantConditions") - @EventHandler(priority = EventPriority.HIGHEST) - private void onBlockPlace(BlockPlaceEvent event) { - if (event.isCancelled()) return; - Player player = event.getPlayer(); - - ItemStack mainTool = player.getInventory().getItemInMainHand(); - ItemStack offTool = player.getInventory().getItemInOffHand(); - - Block block = event.getBlock(); - - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - if (config.PLACE_ONLY_WITH_HAMMER) { - if (Utils.requiresHammer(block.getType())) { - if (ItemManager.compare(offTool, Item.HAMMER)) { - Random rand = new Random(); - int chance_reduceDur = rand.nextInt(10) + 1; - if (chance_reduceDur == 1) { - Utils.setDurability(offTool, Utils.getDurability(offTool) + 1); - } - - if (Utils.getDurability(offTool) >= offTool.getType().getMaxDurability()) { - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - player.getInventory().setItemInOffHand(null); - } - } else if (ItemManager.compare(mainTool, Item.HAMMER)) { - Random rand = new Random(); - int chance_reduceDur = rand.nextInt(10) + 1; - if (chance_reduceDur == 1) { - Utils.setDurability(mainTool, ((Damageable) mainTool.getItemMeta()).getDamage() + 1); - } - - if (Utils.getDurability(mainTool) >= mainTool.getType().getMaxDurability()) { - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - player.getInventory().setItemInMainHand(null); - } - } else { - event.setCancelled(true); - player.updateInventory(); - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.task_must_use_hammer)); - } - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/listeners/block/BurnoutTorches.java b/src/main/java/tk/shanebee/survival/listeners/block/BurnoutTorches.java deleted file mode 100644 index 24d5d9e..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/block/BurnoutTorches.java +++ /dev/null @@ -1,221 +0,0 @@ -package tk.shanebee.survival.listeners.block; - -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Lightable; -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.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.managers.BlockManager; -import tk.shanebee.survival.util.Utils; - -import java.util.Random; - -public class BurnoutTorches implements Listener { - - // TODO Experimental Feature - - private final boolean RELIGHTABLE; - private final boolean PERSISTENT_TORCHES; - private final boolean DROP_TORCH; - - private final BlockManager torchManager; - - public BurnoutTorches(Survival plugin) { - this.torchManager = plugin.getBlockManager(); - this.RELIGHTABLE = plugin.getSurvivalConfig().MECHANICS_BURNOUT_TORCH_RELIGHT; - this.PERSISTENT_TORCHES = plugin.getSurvivalConfig().MECHANICS_BURNOUT_TORCH_PERSIST; - this.DROP_TORCH = plugin.getSurvivalConfig().MECHANICS_BURNOUT_TORCH_DROP; - } - - @EventHandler - private void onBlockUpdate(BlockPhysicsEvent e) { - Block block = e.getBlock(); - if (block.getType() == Material.REDSTONE_TORCH || block.getType() == Material.REDSTONE_WALL_TORCH) { - if (torchManager.isNonPersistent(block) && !((Lightable) block.getBlockData()).isLit()) { - e.setCancelled(true); - } - } - } - - @EventHandler - private void onRelight(PlayerInteractEvent e) { - if (!RELIGHTABLE) return; - Player player = e.getPlayer(); - ItemStack tool = player.getInventory().getItemInMainHand(); - Block block = e.getClickedBlock(); - if (block == null || (block.getType() != Material.REDSTONE_TORCH && block.getType() != Material.REDSTONE_WALL_TORCH)) - return; - if (!torchManager.isNonPersistent(block)) return; - if (tool.getType() != Material.FLINT_AND_STEEL && !ItemManager.compare(tool, Item.FIRESTRIKER)) return; - if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return; - e.setCancelled(true); - if (block.getType() == Material.REDSTONE_WALL_TORCH) { - BlockFace face = ((Directional) block.getBlockData()).getFacing(); - block.setType(Material.WALL_TORCH); - Directional dir = ((Directional) block.getBlockData()); - dir.setFacing(face); - block.setBlockData(dir); - } else { - block.setType(Material.TORCH); - } - Random rand = new Random(); - Location loc = block.getLocation(); - assert loc.getWorld() != null; - loc.getWorld().playSound(loc, Sound.ITEM_FLINTANDSTEEL_USE, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - - if ((Utils.getDurability(tool) + 1) < tool.getType().getMaxDurability()) - Utils.setDurability(tool, Utils.getDurability(tool) + 1); - else { - player.getInventory().setItemInMainHand(null); - assert player.getLocation().getWorld() != null; - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - } - torchManager.setNonPersistent(block); - torchManager.burnoutTorch(block); - } - - @EventHandler(priority = EventPriority.HIGH) - private void onPlaceTorch(BlockPlaceEvent e) { - if (e.isCancelled()) { // If another plugin cancels these, lets get outta here - return; - } - Block block = e.getBlock(); - ItemStack mainHand = e.getItemInHand(); - GameMode mode = e.getPlayer().getGameMode(); - if (mode != GameMode.SURVIVAL && mode != GameMode.ADVENTURE) { - return; - } - if (block.getType() == Material.TORCH || block.getType() == Material.WALL_TORCH) { - if (!ItemManager.compare(mainHand, Item.PERSISTENT_TORCH)) { - torchManager.burnoutTorch(block); - torchManager.setNonPersistent(block); - } - } - } - - @EventHandler(priority = EventPriority.HIGH) - private void onBreakTorch(BlockBreakEvent e) { - if (e.isCancelled()) { // If another plugin cancels these, lets get outta here - return; - } - Block block = e.getBlock(); - Location loc = e.getBlock().getLocation(); - GameMode mode = e.getPlayer().getGameMode(); - assert loc.getWorld() != null; - /* - if (block.getType() == Material.REDSTONE_WALL_TORCH || block.getType() == Material.REDSTONE_TORCH) { - if (((Lightable) block.getBlockData()).isLit()) return; - e.setDropItems(false); - loc.getWorld().dropItemNaturally(loc, new ItemStack(Material.STICK)); - torchManager.unsetNonPersistent(block); - } else if (block.getType() == Material.TORCH || block.getType() == Material.WALL_TORCH) { - if (PERSISTENT_TORCHES && !torchManager.isNonPersistent(block)) { - e.setDropItems(false); - loc.getWorld().dropItemNaturally(loc, ItemManager.get(Items.PERSISTENT_TORCH)); - } else { - torchManager.unsetNonPersistent(block); - if (!DROP_TORCH) { - e.setDropItems(false); - loc.getWorld().dropItemNaturally(loc, new ItemStack(Material.STICK)); - } - } - } else { - for (BlockFace blockFace : BlockFace.values()) { - Block relative = block.getRelative(blockFace); - if (torchManager.isNonPersistent(relative)) { - relative.setType(Material.AIR); - dropTorch(relative); - } - } - } - */ - switch (block.getType()) { - case TORCH: - case WALL_TORCH: - case REDSTONE_TORCH: - case REDSTONE_WALL_TORCH: - if (mode != GameMode.SURVIVAL && mode != GameMode.ADVENTURE) { - if (torchManager.isNonPersistent(block)) { - torchManager.unsetNonPersistent(block); - } - return; - } - if (dropTorch(block)) { - e.setDropItems(false); - } - return; - default: - for (BlockFace blockFace : BlockFace.values()) { - Block relative = block.getRelative(blockFace); - if (torchManager.isNonPersistent(relative)) { - if (mode != GameMode.SURVIVAL && mode != GameMode.ADVENTURE) { - torchManager.unsetNonPersistent(relative); - continue; - } - if (dropTorch(relative)) { - relative.setType(Material.AIR); - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGH) - private void pistonExtend(BlockPistonExtendEvent event) { - if (event.isCancelled()) { - return; - } - for (Block block : event.getBlocks()) { - if (dropTorch(block)) { - block.setType(Material.AIR); - } - } - } - - private boolean dropTorch(Block block) { - Location loc = block.getLocation(); - World world = loc.getWorld(); - if (world == null) return false; - Material mat = block.getType(); - if (mat == Material.TORCH || mat == Material.WALL_TORCH) { - if (PERSISTENT_TORCHES && !torchManager.isNonPersistent(block)) { - world.dropItemNaturally(loc, Item.PERSISTENT_TORCH.getItem()); - } else if (DROP_TORCH) { - return false; - } else { - world.dropItemNaturally(loc, new ItemStack(Material.STICK)); - } - } else if (mat == Material.REDSTONE_TORCH || mat == Material.REDSTONE_WALL_TORCH) { - if (torchManager.isNonPersistent(block)) { - world.dropItemNaturally(loc, new ItemStack(Material.STICK)); - } else { - return false; - } - } else { - return false; - } - if (torchManager.isNonPersistent(block)) { - torchManager.unsetNonPersistent(block); - } - return true; - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/block/Campfire.java b/src/main/java/tk/shanebee/survival/listeners/block/Campfire.java deleted file mode 100644 index a438d96..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/block/Campfire.java +++ /dev/null @@ -1,97 +0,0 @@ -package tk.shanebee.survival.listeners.block; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.block.Block; -import org.bukkit.block.data.Lightable; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockCookEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -import java.util.Random; - -public class Campfire implements Listener { - - private Survival plugin; - - public Campfire(Survival plugin) { - this.plugin = plugin; - } - - // When placing a campfire, turn it off (Requiring a player to light it manually) - @EventHandler - private void onPlaceCampfire(BlockPlaceEvent e) { - if (e.getBlockPlaced().getType() != Material.CAMPFIRE) return; - if (ItemManager.compare(e.getItemInHand(), Item.CAMPFIRE)) { - Lightable camp = ((Lightable) e.getBlock().getBlockData()); - camp.setLit(false); - e.getBlock().setBlockData(camp); - - } else { - if (e.getPlayer().getGameMode() == GameMode.CREATIVE) return; - e.setCancelled(true); - } - } - - // Hit an unlit campfire with a stick to light it - @EventHandler - private void lightFire(PlayerInteractEvent e) { - if (e.getClickedBlock() == null) return; - if (e.getClickedBlock().getType() == Material.CAMPFIRE) { - if (e.getItem() != null && e.getItem().getType() == Material.STICK) { - Block block = e.getClickedBlock(); - Lightable camp = ((Lightable) block.getBlockData()); - if (camp.isLit()) return; - e.setCancelled(true); - int i = new Random().nextInt(20); - if (i == 10) { - camp.setLit(true); - block.setBlockData(camp); - ItemStack tool = e.getItem(); - tool.setAmount(tool.getAmount() - 1); - e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1); - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> - e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.ENTITY_GENERIC_BURN, 1, 1), 1); - - } - } else if (e.getItem() != null && e.getItem().getType() == Material.POTION) { - if (!e.getPlayer().isSneaking()) return; - Lightable camp = ((Lightable) e.getClickedBlock().getBlockData()); - if (!camp.isLit()) return; - camp.setLit(false); - e.getClickedBlock().setBlockData(camp); - Player p = e.getPlayer(); - if (e.getHand() == EquipmentSlot.HAND) p.getInventory().setItemInMainHand(new ItemStack(Material.GLASS_BOTTLE)); - if (e.getHand() == EquipmentSlot.OFF_HAND) p.getInventory().setItemInOffHand(new ItemStack(Material.GLASS_BOTTLE)); - p.playSound(e.getPlayer().getLocation(), Sound.BLOCK_FIRE_EXTINGUISH, 1, 1); - - } - } - } - - // Randomly put out the fire when cooking food - @EventHandler - private void fireFinishedCooking(BlockCookEvent e) { - if (e.getBlock().getType() != Material.CAMPFIRE) return; - int i = new Random().nextInt(8); - - if (i == 5) { - Block block = e.getBlock(); - Lightable camp = ((Lightable) block.getBlockData()); - camp.setLit(false); - block.setBlockData(camp); - block.getLocation().getWorld().playSound(block.getLocation(), Sound.BLOCK_FIRE_EXTINGUISH, 1, 1); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/block/NoAnvil.java b/src/main/java/tk/shanebee/survival/listeners/block/NoAnvil.java deleted file mode 100644 index dd568f8..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/block/NoAnvil.java +++ /dev/null @@ -1,59 +0,0 @@ -package tk.shanebee.survival.listeners.block; - -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; -import org.bukkit.ChatColor; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.AnvilInventory; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.ItemStack; - -import tk.shanebee.survival.Survival; - -public class NoAnvil implements Listener { - - private Lang lang; - - public NoAnvil(Survival plugin) { - this.lang = plugin.getLang(); - } - - @EventHandler - private void onInventoryClick(InventoryClickEvent e) { - Inventory inv = e.getInventory(); - - if (inv instanceof AnvilInventory) { - AnvilInventory anvil = (AnvilInventory) inv; - InventoryView view = e.getView(); - int rawSlot = e.getRawSlot(); - - // compare raw slot to the inventory view to make sure we are in the upper inventory - if (rawSlot == view.convertSlot(rawSlot)) { - // 2 = result slot - if (rawSlot == 2) { - // item in the left slot - ItemStack item = anvil.getContents()[0]; - - if (item != null) { - if (ItemManager.compare(item, Item.VALKYRIES_AXE) - || ItemManager.compare(item, Item.QUARTZ_PICKAXE) || ItemManager.compare(item, Item.OBSIDIAN_MACE) - || ItemManager.compare(item, Item.ENDER_GIANT_BLADE) || ItemManager.compare(item, Item.BLAZE_SWORD) - || ItemManager.compare(item, Item.HATCHET) || ItemManager.compare(item, Item.MATTOCK) - || ItemManager.compare(item, Item.FIRESTRIKER) || ItemManager.compare(item, Item.SHIV) - || ItemManager.compare(item, Item.HAMMER)) { - e.setCancelled(true); - e.getWhoClicked().closeInventory(); - e.getWhoClicked().sendMessage(ChatColor.RED + Utils.getColoredString(lang.no_rename) + item.getItemMeta().getDisplayName() + ChatColor.RED + Utils.getColoredString(lang.period)); - } - } - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/listeners/block/SnowGeneration.java b/src/main/java/tk/shanebee/survival/listeners/block/SnowGeneration.java deleted file mode 100644 index bd34fef..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/block/SnowGeneration.java +++ /dev/null @@ -1,179 +0,0 @@ -package tk.shanebee.survival.listeners.block; - -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockFormEvent; -import org.bukkit.event.world.ChunkLoadEvent; - -import tk.shanebee.survival.Survival; - -public class SnowGeneration implements Listener { - - private Survival plugin; - - public SnowGeneration(Survival plugin) { - this.plugin = plugin; - } - - @EventHandler(ignoreCancelled = true) - private void chunkLoad(final ChunkLoadEvent event) { - if (plugin.isSnowGenOption()) { - if (event.isNewChunk()) { - Bukkit.getScheduler().runTask(plugin, () -> checkChunk(event.getChunk())); - } - } - } - - /** - * Internal usage, do not use - * - * @param chunk A chunk - */ - public void checkChunk(final Chunk chunk) { - final ChunkSnapshot chunkSnap = chunk.getChunkSnapshot(true, false, false); - - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - final int y = chunkSnap.getHighestBlockYAt(x, z); - - if (chunkSnap.getBlockType(x, y, z) == Material.SNOW) - - placeSnow(chunk, chunkSnap, x, y, z); - } - } - } - - @EventHandler(ignoreCancelled = true) - private void snowForm(final BlockFormEvent event) { - if (plugin.isSnowGenOption()) { - if (event.getNewState().getType() != Material.SNOW) - return; - - Bukkit.getScheduler().runTask(plugin, () -> placeSnow(event.getBlock())); - } - } - - private void placeSnow(final Block block) { - final Location loc = block.getLocation(); - final Chunk chunk = block.getChunk(); - - placeSnow(chunk, chunk.getChunkSnapshot(true, false, false), Math.abs((chunk.getX() * 16) - loc.getBlockX()), loc.getBlockY(), Math.abs((chunk.getZ() * 16) - loc.getBlockZ())); - } - - private void placeSnow(final Chunk chunk, final ChunkSnapshot chunkSnap, final int x, int y, final int z) { - if (y <= 1) - return; - - Material type = chunkSnap.getBlockType(x, --y, z); - - if (!(Tag.LEAVES.isTagged(type))) - return; - - Material lastType = type; - - while (true) { - type = chunkSnap.getBlockType(x, --y, z); - - switch (type) { - case AIR: // ignore air and snow - case SNOW: - break; - case OAK_LEAVES: - case BIRCH_LEAVES: - case JUNGLE_LEAVES: - case DARK_OAK_LEAVES: - case ACACIA_LEAVES: - case SPRUCE_LEAVES: // check leaves if they have air above them to place snow - { - if (lastType == Material.AIR) { - try { - chunk.getBlock(x, y + 1, z).setType(Material.SNOW); - } catch (Exception ignore) { - } - } - - break; - } - - // snowable blocks and the stop - case STONE: - case GRASS: - case DIRT: - case COBBLESTONE: - case BEDROCK: - case SAND: - case GRAVEL: - case GOLD_ORE: - case IRON_ORE: - case COAL_ORE: - case SPONGE: - case GLASS: - case LAPIS_ORE: - case LAPIS_BLOCK: - case DISPENSER: - case SANDSTONE: - case NOTE_BLOCK: -// case PISTON_BASE: -// case PISTON_STICKY_BASE: -// case PISTON_MOVING_PIECE: -// case PISTON_EXTENSION: - case GOLD_BLOCK: - case IRON_BLOCK: - case BRICK: - case TNT: - case BOOKSHELF: - case MOSSY_COBBLESTONE: - case OBSIDIAN: - case SPAWNER: - case DIAMOND_ORE: - case DIAMOND_BLOCK: - case CRAFTING_TABLE: - case FURNACE: -// case BURNING_FURNACE: - case REDSTONE_ORE: -// case ICE: - case SNOW_BLOCK: - case CLAY: - case JUKEBOX: - case PUMPKIN: - case NETHERRACK: - case SOUL_SAND: - case GLOWSTONE: -// case JACK_O_LANTERN: -// case SMOOTH_BRICK: - case MELON: - case NETHER_BRICK: - case END_STONE: - case REDSTONE_LAMP: - case EMERALD_BLOCK: - case EMERALD_ORE: { - setSnow(lastType, chunk, x, y, z); - return; - } - - default: // everything else stops - if (Tag.LOGS.isTagged(type) || - Tag.WOOL.isTagged(type) || - Tag.PLANKS.isTagged(type) || - Tag.SLABS.isTagged(type)) setSnow(lastType, chunk, x, y, z); - return; - } - - lastType = type; - } - } - - private void setSnow(Material mat, Chunk chunk, final int x, int y, final int z) { - - if (mat == Material.AIR) { - try { - chunk.getBlock(x, y + 1, z).setType(Material.SNOW); - } catch (Exception ignore) { - } - } - - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/entity/ChestPigmen.java b/src/main/java/tk/shanebee/survival/listeners/entity/ChestPigmen.java deleted file mode 100644 index 7c214dc..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/entity/ChestPigmen.java +++ /dev/null @@ -1,76 +0,0 @@ -package tk.shanebee.survival.listeners.entity; - -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.attribute.Attributable; -import org.bukkit.attribute.Attribute; -import org.bukkit.block.Chest; -import org.bukkit.entity.PigZombie; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; - -import java.util.ArrayList; -import java.util.List; - -public class ChestPigmen implements Listener { - - private final List GOLD_ITEMS; - private final int RADIUS; - private double SPEED; - - public ChestPigmen(Survival plugin) { - GOLD_ITEMS = new ArrayList<>(); - GOLD_ITEMS.add(Material.GOLDEN_SWORD); - GOLD_ITEMS.add(Material.GOLDEN_SHOVEL); - GOLD_ITEMS.add(Material.GOLDEN_PICKAXE); - GOLD_ITEMS.add(Material.GOLDEN_AXE); - GOLD_ITEMS.add(Material.GOLDEN_HOE); - GOLD_ITEMS.add(Material.GOLDEN_HELMET); - GOLD_ITEMS.add(Material.GOLDEN_CHESTPLATE); - GOLD_ITEMS.add(Material.GOLDEN_LEGGINGS); - GOLD_ITEMS.add(Material.GOLDEN_BOOTS); - GOLD_ITEMS.add(Material.GOLD_BLOCK); - GOLD_ITEMS.add(Material.GOLD_INGOT); - GOLD_ITEMS.add(Material.GOLD_NUGGET); - RADIUS = plugin.getSurvivalConfig().ENTITY_MECHANICS_PIGMEN_CHEST_RADIUS; - SPEED = plugin.getSurvivalConfig().ENTITY_MECHANICS_PIGMEN_CHEST_SPEED; - } - - @EventHandler - private void onOpenChest(PlayerInteractEvent event) { - Player player = event.getPlayer(); - if (player.getWorld().getEnvironment() != World.Environment.NETHER) return; - if (event.getClickedBlock() == null) return; - if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock().getType() != Material.CHEST) return; - Chest chest = ((Chest) event.getClickedBlock().getState()); - if (chestContainsGold(chest)) { - player.getNearbyEntities(RADIUS, RADIUS, RADIUS).forEach(entity -> { - if (entity instanceof PigZombie) { - ((PigZombie) entity).setTarget(player); - moveFaster((Attributable) entity, SPEED); - } - }); - } - } - - private boolean chestContainsGold(Chest block) { - for (ItemStack item : block.getInventory().getContents()) { - if (item == null) continue; - if (GOLD_ITEMS.contains(item.getType())) return true; - } - return false; - } - - private void moveFaster(Attributable entity, double modifier) { - if (entity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED) != null) { - double speed = entity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED).getBaseValue(); - entity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED).setBaseValue(speed * modifier); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/entity/ChickenSpawn.java b/src/main/java/tk/shanebee/survival/listeners/entity/ChickenSpawn.java deleted file mode 100644 index 72b52da..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/entity/ChickenSpawn.java +++ /dev/null @@ -1,94 +0,0 @@ -package tk.shanebee.survival.listeners.entity; - -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.Sound; -import org.bukkit.World; -import org.bukkit.entity.Chicken; -import org.bukkit.entity.Egg; -import org.bukkit.entity.EntityType; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -import org.bukkit.event.player.PlayerEggThrowEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.item.Item; - -import java.util.Random; - -public class ChickenSpawn implements Listener { - - private final Random rand = new Random(); - private final NamespacedKey key; - private final int maxEggs; - private final boolean alwaysBaby; - private final int babyTicks; - - public ChickenSpawn(Survival plugin) { - Config config = plugin.getSurvivalConfig(); - this.key = new NamespacedKey(plugin, "fromBreeding"); - this.maxEggs = config.ENTITY_MECHANICS_CHICKEN_BREEDING_MAX_EGGS; - this.alwaysBaby = config.ENTITY_MECHANICS_CHICKEN_BREEDING_ALWAYS_BABY; - this.babyTicks = config.ENTITY_MECHANICS_CHICKEN_BREEDING_BABY_TICKS; - } - - @EventHandler - private void onChickenSpawn(CreatureSpawnEvent e) { - if (e.getEntityType() == EntityType.CHICKEN) { - SpawnReason reason = e.getSpawnReason(); - if (reason == SpawnReason.BREEDING) { - e.setCancelled(true); - Location loc = e.getLocation(); - World world = loc.getWorld(); - assert world != null; - world.dropItem(loc, getEgg()); - world.playSound(loc, Sound.ENTITY_CHICKEN_EGG, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - } else if (reason == SpawnReason.EGG) { - Chicken chicken = ((Chicken) e.getEntity()); - if (alwaysBaby) { - chicken.setBaby(); - chicken.setAge(-babyTicks); - } else if (!chicken.isAdult()) { - chicken.setAge(-babyTicks); - } - } - } - } - - @EventHandler - private void onEggThrown(PlayerEggThrowEvent e) { - if (isFromBreeding(e.getEgg())) { - e.setHatching(true); - e.setNumHatches((byte) 1); - } - } - - private ItemStack getEgg() { - int ran = maxEggs > 1 ? rand.nextInt(maxEggs) + 1 : 1; - return Item.BREEDING_EGG.getItem(ran); - } - - @SuppressWarnings("ConstantConditions") - private boolean isFromBreeding(Egg egg) { - ItemStack itemStack = egg.getItem(); - ItemMeta meta = itemStack.getItemMeta(); - - assert meta != null; - PersistentDataContainer container = meta.getPersistentDataContainer(); - if (container.has(key, PersistentDataType.BYTE)) { - // Old egg method (changed on sept 4/2020) - // Will keep for a while incase players have old eggs - return container.get(key, PersistentDataType.BYTE) == (byte) 1; - } else if (Item.BREEDING_EGG.compare(itemStack)) { - return true; - } - return false; - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/entity/LivingSlime.java b/src/main/java/tk/shanebee/survival/listeners/entity/LivingSlime.java deleted file mode 100644 index 5a2ead3..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/entity/LivingSlime.java +++ /dev/null @@ -1,84 +0,0 @@ -package tk.shanebee.survival.listeners.entity; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import tk.shanebee.survival.util.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.block.Block; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Item; -import org.bukkit.entity.Slime; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.ItemSpawnEvent; -import org.bukkit.inventory.ItemStack; - -import tk.shanebee.survival.Survival; - -public class LivingSlime implements Listener { - - private Survival plugin; - - public LivingSlime(Survival plugin) { - this.plugin = plugin; - } - - @EventHandler - private void onGhastTearSlimeBlock(ItemSpawnEvent e) { - if (e.getEntityType() == EntityType.DROPPED_ITEM) { - Item i = e.getEntity(); - if (i.getItemStack().getType() == Material.GHAST_TEAR) { - Bukkit.getScheduler().runTaskLater(plugin, initRunnable(i), 20); - } - } - } - - private Runnable initRunnable(Item i) { - final Item f_i = i; - return () -> { - List slimeBlocks = new ArrayList<>(); - slimeBlocks.add(f_i.getLocation().add(0, -1, 0).getBlock()); - slimeBlocks.add(f_i.getLocation().add(0, -1, 1).getBlock()); - slimeBlocks.add(f_i.getLocation().add(0, -1, -1).getBlock()); - slimeBlocks.add(f_i.getLocation().add(1, -1, 0).getBlock()); - slimeBlocks.add(f_i.getLocation().add(-1, -1, 0).getBlock()); - slimeBlocks.add(f_i.getLocation().add(0, 0, 1).getBlock()); - slimeBlocks.add(f_i.getLocation().add(0, 0, -1).getBlock()); - slimeBlocks.add(f_i.getLocation().add(1, 0, 0).getBlock()); - slimeBlocks.add(f_i.getLocation().add(-1, 0, 0).getBlock()); - slimeBlocks.add(f_i.getLocation().add(1, 0, 1).getBlock()); - slimeBlocks.add(f_i.getLocation().add(1, 0, -1).getBlock()); - slimeBlocks.add(f_i.getLocation().add(-1, 0, 1).getBlock()); - slimeBlocks.add(f_i.getLocation().add(-1, 0, -1).getBlock()); - - ItemStack i_f_i = f_i.getItemStack(); - Iterator it = slimeBlocks.iterator(); - Block slimeBlock; - while (it.hasNext()) { - slimeBlock = it.next(); - if (slimeBlock != null && slimeBlock.getType() == Material.SLIME_BLOCK && f_i.isOnGround()) { - if (i_f_i.getAmount() > 1) - i_f_i.setAmount(i_f_i.getAmount() - 1); - else - f_i.remove(); - - if (i_f_i.getAmount() <= 0) - f_i.remove(); - - slimeBlock.setType(Material.AIR); - - Slime slime = (Slime) f_i.getWorld().spawnEntity(slimeBlock.getLocation(), EntityType.SLIME); - slime.setSize(2); - - Utils.spawnParticle(slimeBlock.getLocation().add(0.5, 0.5, 0.5), Particle.CLOUD, 20, 0.5, 0.5, 0.5); - break; - } - } - }; - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/entity/MerchantTrades.java b/src/main/java/tk/shanebee/survival/listeners/entity/MerchantTrades.java deleted file mode 100644 index 9c456eb..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/entity/MerchantTrades.java +++ /dev/null @@ -1,27 +0,0 @@ -package tk.shanebee.survival.listeners.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.inventory.Merchant; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.MerchantManager; - -public class MerchantTrades implements Listener { - - private MerchantManager merchantManager; - - public MerchantTrades(Survival plugin) { - this.merchantManager = plugin.getMerchantManager(); - } - - @EventHandler - private void onClickVillager(PlayerInteractEntityEvent event) { - Entity entity = event.getRightClicked(); - if (entity instanceof Merchant) { - this.merchantManager.updateRecipes(entity); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/entity/PiglinBarter.java b/src/main/java/tk/shanebee/survival/listeners/entity/PiglinBarter.java deleted file mode 100644 index 29616c0..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/entity/PiglinBarter.java +++ /dev/null @@ -1,97 +0,0 @@ -package tk.shanebee.survival.listeners.entity; - -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.EntityType; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDropItemEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionType; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.item.Item; - -import java.util.Random; - -public class PiglinBarter implements Listener { - - private final boolean SLOW_ARMOR; - private final boolean THIRST_ENABLED; - private final boolean DROP_WATER; - private final boolean ALT_DROPS; - private final Random RANDOM; - - public PiglinBarter(Survival plugin) { - Config config = plugin.getSurvivalConfig(); - this.SLOW_ARMOR = config.MECHANICS_SLOW_ARMOR; - this.THIRST_ENABLED = config.MECHANICS_THIRST_ENABLED; - this.DROP_WATER = config.ENTITY_MECHANICS_PIGLIN_DROP_WATER; - this.ALT_DROPS = config.ENTITY_MECHANICS_PIGLIN_ALT_DROP; - this.RANDOM = new Random(); - } - - @EventHandler - private void onPiglinDrop(EntityDropItemEvent event) { - if (event.getEntityType() != EntityType.PIGLIN) return; - - org.bukkit.entity.Item itemDrop = event.getItemDrop(); - ItemStack itemDropStack = itemDrop.getItemStack(); - Material itemDropMaterial = itemDropStack.getType(); - - // If water bottle is dropped, let's change it - if (itemDropMaterial == Material.POTION && THIRST_ENABLED && DROP_WATER) { - PotionMeta meta = ((PotionMeta) itemDropStack.getItemMeta()); - assert meta != null; - if (meta.getBasePotionData().getType() == PotionType.WATER) { - if (RANDOM.nextFloat() < 0.25f) { - itemDrop.setItemStack(Item.PURIFIED_WATER.getItem()); - } else { - itemDrop.setItemStack(Item.CLEAN_WATER.getItem()); - } - return; - } - } - - // If alt drops are disabled let's get outta here - if (!ALT_DROPS) return; - - // If slow armor is enabled let's always drop custom iron boots - if (itemDropMaterial == Material.IRON_BOOTS && SLOW_ARMOR) { - ItemStack boots = Item.IRON_BOOTS.getItem(); - boots.addEnchantment(Enchantment.SOUL_SPEED, RANDOM.nextInt(3) + 1); - itemDrop.setItemStack(boots); - return; - } - - // If anything else we have some random drops - ItemStack altItem = null; - switch (itemDropMaterial) { - case LEATHER: - altItem = Item.SUSPICIOUS_MEAT.getItem(); - break; - case NETHER_BRICK: - altItem = Item.COFFEE_BEAN.getItem(RANDOM.nextInt(4) + 1); - break; - case GRAVEL: - altItem = Item.FIRESTRIKER.getItem(); - break; - case SOUL_SAND: - altItem = Item.CAMPFIRE.getItem(); - break; - case POTION: - altItem = Item.MEDIC_KIT.getItem(); - break; - case SPLASH_POTION: - altItem = Item.GRAPPLING_HOOK.getItem(); - break; - case ENCHANTED_BOOK: - altItem = Item.RECURVE_CROSSBOW.getItem(); - } - if (altItem != null && RANDOM.nextFloat() > 0.5f) { - itemDrop.setItemStack(altItem); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/BlazeSword.java b/src/main/java/tk/shanebee/survival/listeners/item/BlazeSword.java deleted file mode 100644 index 87b6570..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/BlazeSword.java +++ /dev/null @@ -1,138 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import org.bukkit.*; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockIgniteEvent; -import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; - -public class BlazeSword implements Listener { - - @EventHandler - private void onItemClick(PlayerInteractEvent event) { - if (event.hasItem()) { - Player player = event.getPlayer(); - ItemStack mainItem = player.getInventory().getItemInMainHand(); - if (ItemManager.compare(mainItem, Item.BLAZE_SWORD)) { - if (player.isSneaking()) { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - Material mat = event.getClickedBlock().getType(); - if (Tag.BEDS.isTagged(mat) || Tag.DOORS.isTagged(mat) || Tag.TRAPDOORS.isTagged(mat) || Utils.isWoodGate(mat)) { - return; - } - switch (event.getClickedBlock().getType()) { - case ENCHANTING_TABLE: - case ANVIL: - case BREWING_STAND: - case TRAPPED_CHEST: - case CHEST: - case BARREL: - case NOTE_BLOCK: - case FURNACE: - case BLAST_FURNACE: - case SMOKER: - case HOPPER: - case CRAFTING_TABLE: - case SMITHING_TABLE: - case FLETCHING_TABLE: - case GRINDSTONE: - case CARTOGRAPHY_TABLE: - case COMPOSTER: - case LECTERN: - case LOOM: - case DROPPER: - case DISPENSER: - return; - default: - } - Location loc = event.getClickedBlock().getRelative(event.getBlockFace()).getLocation(); - ignite(player, loc); - } - - if (event.getAction() == Action.RIGHT_CLICK_AIR) { - Location loc = player.getLocation(); - loc.add(-0.5, -0.5, -0.5); - ignite(player, loc); - } - - ItemMeta meta = mainItem.getItemMeta(); - assert meta != null; - ((Damageable) meta).setDamage(((Damageable) meta).getDamage() + 1); - mainItem.setItemMeta(meta); - if (((Damageable) meta).getDamage() >= mainItem.getType().getMaxDurability()) { - Random rand = new Random(); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - player.getInventory().setItemInMainHand(null); - } - player.updateInventory(); - } - } - } - } - } - - private void ignite(Player igniter, Location loc) { - Random rand = new Random(); - - loc.add(0.5, 0.5, 0.5); - - BlockIgniteEvent igniteEvent = new BlockIgniteEvent(loc.getBlock(), - IgniteCause.FLINT_AND_STEEL, igniter); - Bukkit.getServer().getPluginManager().callEvent(igniteEvent); - if (igniteEvent.isCancelled()) { - return; - } - - List locations = new ArrayList<>(); - - for (double x = loc.getX() - 2; x <= loc.getX() + 2; x++) { - for (double y = loc.getY() - 1; y <= loc.getY() + 1; y++) { - for (double z = loc.getZ() - 2; z <= loc.getZ() + 2; z++) { - locations.add(new Location(loc.getWorld(), x, y, z)); - } - } - } - - for (Location l : locations) { - BlockIgniteEvent igniteEvent2 = new BlockIgniteEvent(l.getBlock(), - IgniteCause.FLINT_AND_STEEL, igniter); - Bukkit.getServer().getPluginManager().callEvent(igniteEvent2); - if (igniteEvent2.isCancelled()) { - continue; - } - - BlockState blockState = l.getBlock().getState(); - BlockPlaceEvent placeEvent = new BlockPlaceEvent(l.getBlock(), blockState, l.getBlock(), - igniter.getInventory().getItemInMainHand(), igniter, true, EquipmentSlot.HAND); - Bukkit.getServer().getPluginManager().callEvent(placeEvent); - - if (placeEvent.isCancelled() || !placeEvent.canBuild()) { - continue; - } - - if (l.getBlock().getType() == Material.AIR) - l.getBlock().setType(Material.FIRE); - } - - loc.getWorld().playSound(loc, Sound.ITEM_FIRECHARGE_USE, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/Bow.java b/src/main/java/tk/shanebee/survival/listeners/item/Bow.java deleted file mode 100644 index 31bed0e..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/Bow.java +++ /dev/null @@ -1,67 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.entity.EntityShootBowEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.CrossbowMeta; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -public class Bow implements Listener { - - private Lang lang; - - public Bow(Survival plugin) { - this.lang = plugin.getLang(); - } - - @EventHandler - private void onShootWithoutArrows(EntityShootBowEvent event) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - ItemStack mainHand = player.getInventory().getItemInMainHand(); - if (event.getBow() != null && mainHand.getType() == event.getBow().getType()) { - if (Survival.getInstance().getPlayerManager().isArrowOffHand(player)) { - event.setCancelled(false); - } else { - if (mainHand.getType() != Material.CROSSBOW) { - event.setCancelled(true); - Utils.sendColoredMsg(player, lang.arrows_off_hand); - player.updateInventory(); - } - } - } else { - event.setCancelled(true); - Utils.sendColoredMsg(player, lang.bow_main_hand); - player.updateInventory(); - } - } - } - - @EventHandler - private void onLoadCrossbow(PlayerInteractEvent event) { - Player player = event.getPlayer(); - ItemStack mainHand = player.getInventory().getItemInMainHand(); - ItemStack offHand = player.getInventory().getItemInOffHand(); - if (mainHand.getType() == Material.CROSSBOW && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { - if (event.getHand() == EquipmentSlot.OFF_HAND) return; - if (mainHand.getItemMeta() != null && ((CrossbowMeta) mainHand.getItemMeta()).hasChargedProjectiles()) return; - if (!Survival.getInstance().getPlayerManager().isArrowOffHand(player)) { - event.setCancelled(true); - Utils.sendColoredMsg(player, lang.arrows_off_hand_crossbow); - } - } else if (offHand.getType() == Material.CROSSBOW) { - if (event.getHand() == EquipmentSlot.HAND) return; - event.setCancelled(true); - Utils.sendColoredMsg(player, lang.bow_main_hand); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/CauldronWaterBottle.java b/src/main/java/tk/shanebee/survival/listeners/item/CauldronWaterBottle.java deleted file mode 100644 index ae30709..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/CauldronWaterBottle.java +++ /dev/null @@ -1,66 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.Levelled; -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.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.Cauldron; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -public class CauldronWaterBottle implements Listener { - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.HIGHEST) - private void onItemClick(PlayerInteractEvent event) { - if (event.isCancelled()) return; - if (event.hasItem()) { - Player player = event.getPlayer(); - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - ItemStack mainItem = player.getInventory().getItemInMainHand(); - if (mainItem.getType() == Material.GLASS_BOTTLE) { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (event.getClickedBlock().getType() == Material.CAULDRON) { - Levelled cauldron = (Levelled) (event.getClickedBlock().getBlockData()); - if (cauldron.getLevel() > 0) { - Block fire = event.getClickedBlock().getRelative(BlockFace.DOWN); - event.setCancelled(true); - - event.getClickedBlock().getState().setData(new Cauldron()); - cauldron.setLevel(cauldron.getLevel() - 1); - event.getClickedBlock().setBlockData(cauldron); - - ItemStack waterBottle = ItemManager.get(Item.DIRTY_WATER); - - if (fire.getType() == Material.FIRE) { - waterBottle = ItemManager.get(Item.PURIFIED_WATER); - } - player.playSound(event.getClickedBlock().getLocation(), Sound.ITEM_BOTTLE_FILL, 1, 1); - - if (mainItem.getAmount() > 1) { - mainItem.setAmount(mainItem.getAmount() - 1); - if (player.getInventory().firstEmpty() != -1) - player.getInventory().addItem(waterBottle); - else - player.getWorld().dropItem(player.getLocation(), waterBottle); - } else { - player.getInventory().setItemInMainHand(waterBottle); - } - } - } - } - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/listeners/item/Clownfish.java b/src/main/java/tk/shanebee/survival/listeners/item/Clownfish.java deleted file mode 100644 index 30bfe14..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/Clownfish.java +++ /dev/null @@ -1,41 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import java.util.Random; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.Sound; -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.PlayerItemConsumeEvent; - -public class Clownfish implements Listener { - - @EventHandler(priority = EventPriority.HIGHEST) - private void onConsume(PlayerItemConsumeEvent event) { - if (event.isCancelled()) return; - Player player = event.getPlayer(); - if (event.getItem().getType() == Material.TROPICAL_FISH) { - Random rand = new Random(); - Location originLoc = player.getLocation(); - originLoc.getWorld().spawnParticle(Particle.PORTAL, originLoc, 200, 0.5, 0.5, 0.5); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ITEM_CHORUS_FRUIT_TELEPORT, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - - if (player.getCompassTarget() != null) { - Location teleportLoc = player.getCompassTarget(); - player.teleport(teleportLoc); - teleportLoc.getWorld().spawnParticle(Particle.PORTAL, teleportLoc, 200, 0.5, 0.5, 0.5); - player.getLocation().getWorld().playSound(teleportLoc, Sound.BLOCK_PORTAL_TRAVEL, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - } else { - Location teleportLoc = player.getWorld().getSpawnLocation(); - player.teleport(teleportLoc); - teleportLoc.getWorld().spawnParticle(Particle.PORTAL, teleportLoc, 200, 0.5, 0.5, 0.5); - player.getLocation().getWorld().playSound(teleportLoc, Sound.BLOCK_PORTAL_TRAVEL, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/listeners/item/Consume.java b/src/main/java/tk/shanebee/survival/listeners/item/Consume.java deleted file mode 100644 index b5c696c..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/Consume.java +++ /dev/null @@ -1,221 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Entity; -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.PlayerDeathEvent; -import org.bukkit.event.player.PlayerItemConsumeEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.event.player.PlayerFishEvent; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.events.ThirstLevelChangeEvent; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.managers.StatusManager; -import tk.shanebee.survival.util.Utils; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -public class Consume implements Listener { - - private final Survival plugin; - private final Config config; - private final Lang lang; - private final PlayerManager playerManager; - - public Consume(Survival plugin) { - this.plugin = plugin; - this.config = plugin.getSurvivalConfig(); - this.lang = plugin.getLang(); - this.playerManager = plugin.getPlayerManager(); - } - - @EventHandler(priority = EventPriority.HIGHEST) - private void onConsume(PlayerItemConsumeEvent event) { - if (event.isCancelled()) return; - final Player player = event.getPlayer(); - PlayerData playerData = playerManager.getPlayerData(player); - ItemStack item = event.getItem(); - int change = 0; - switch (event.getItem().getType()) { - case POTION: - if (config.MECHANICS_THIRST_PURIFY_WATER) { - if (checkWaterBottle(item)) { - if (ItemManager.compare(item, Item.DIRTY_WATER)) { - change = config.MECHANICS_THIRST_REP_DIRTY_WATER; - Random rand = new Random(); - if (rand.nextInt(10) + 1 <= 5) { - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 100, 0)); - player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 200, 0)); - } - } else if (ItemManager.compare(item, Item.CLEAN_WATER)) { - change = config.MECHANICS_THIRST_REP_CLEAN_WATER; - Random rand = new Random(); - if (rand.nextInt(10) + 1 <= 2) { - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 100, 0)); - player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 200, 0)); - } - } else if (ItemManager.compare(item, Item.PURIFIED_WATER)) { - change = config.MECHANICS_THIRST_REP_PURE_WATER; - } else if (ItemManager.compare(item, Item.COFFEE)) { - change = config.MECHANICS_THIRST_REP_COFFEE; - } else if (ItemManager.compare(item, Item.COLD_MILK)) { - change = config.MECHANICS_THIRST_REP_COLD_MILK; - } else if (ItemManager.compare(item, Item.HOT_MILK)) { - change = config.MECHANICS_THIRST_REP_HOT_MILK; - player.damage(2); - player.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, 100, 0)); - Utils.sendColoredMsg(player, lang.hot_milk_drink); - } else if (ItemManager.compare(item, Item.WATER_BOWL)) { - event.setCancelled(true); - change = handleWaterBowl(player); - } else { - change = config.MECHANICS_THIRST_REP_OTHER_WATER; - } - } - } else { - change = config.MECHANICS_THIRST_REP_WATER; - } - break; - case BEETROOT_SOUP: //OLD Water Bowl (removed in 3.11.0 - keep for a few versions) - if (ItemManager.compare(event.getPlayer().getInventory().getItemInMainHand(), Item.WATER_BOWL_OLD)) { - event.setCancelled(true); - change = handleWaterBowl(player); - } else { - change = config.MECHANICS_THIRST_REP_BEET_SOUP; // Regular beetroot soup (if player somehow gets one) - } - break; - case MILK_BUCKET: - change = config.MECHANICS_THIRST_REP_MILK_BUCKET; - break; - case MELON_SLICE: - change = config.MECHANICS_THIRST_REP_MELON_SLICE; - break; - case MUSHROOM_STEW: - change = config.MECHANICS_THIRST_REP_MUSH_STEW; - break; - case HONEY_BOTTLE: - change = config.MECHANICS_THIRST_REP_HONEY_BOTTLE; - break; - case SUSPICIOUS_STEW: - if (Item.SUSPICIOUS_MEAT.compare(item)) { - // Remove the bowl from the player's hand afterwards - BukkitRunnable runnable = new BukkitRunnable() { - @Override - public void run() { - PlayerInventory inv = player.getInventory(); - if (inv.getItemInMainHand().getType() == Material.BOWL) { - inv.setItemInMainHand(null); - } else if (inv.getItemInOffHand().getType() == Material.BOWL) { - inv.setItemInOffHand(null); - } - } - }; - runnable.runTaskLater(plugin, 1); - return; - } - } - ThirstLevelChangeEvent thirstEvent = new ThirstLevelChangeEvent(player, change, playerData.getThirst() + change); - Bukkit.getPluginManager().callEvent(thirstEvent); - if (!thirstEvent.isCancelled()) { - playerData.setThirst(playerData.getThirst() + change); - } - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { - if (!config.MECHANICS_STATUS_SCOREBOARD) { - player.sendMessage(plugin.getPlayerManager().ShowHunger(player).get(1) + plugin.getPlayerManager().ShowHunger(player).get(2) + " " + plugin.getPlayerManager().ShowHunger(player).get(0).toUpperCase()); - player.sendMessage(plugin.getPlayerManager().ShowThirst(player).get(1) + plugin.getPlayerManager().ShowThirst(player).get(2) + " " + plugin.getPlayerManager().ShowThirst(player).get(0).toUpperCase()); - } - }, 1L); - } - - private int handleWaterBowl(Player player) { - int change = config.MECHANICS_THIRST_REP_WATER_BOWL; - player.getInventory().setItemInMainHand(new ItemStack(Material.BOWL)); - if (config.MECHANICS_THIRST_PURIFY_WATER) { - Random rand = new Random(); - if (rand.nextInt(10) + 1 <= 8) { - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 100, 0)); - player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 200, 0)); - } - } - return change; - } - - @EventHandler //if player catches a water bottle/potion give them dirty water instead - private void onFish(PlayerFishEvent event) { - if (!config.MECHANICS_THIRST_PURIFY_WATER) return; - if (event.isCancelled()) return; - if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH) { - Entity caught = event.getCaught(); - if (caught instanceof org.bukkit.entity.Item) { - org.bukkit.entity.Item item = ((org.bukkit.entity.Item) caught); - ItemStack stack = item.getItemStack(); - if (stack.getType() == Material.POTION && checkWaterBottle(stack)) { - item.setItemStack(Item.CLEAN_WATER.getItem()); - } - } - } - } - - // This map is to tell if the player actually DIED before respawning - // Using the portal in the end causes the respawn event to fire - // when the player re-enters the overworld - private final List HUNGER_CHANGE = new ArrayList<>(); - - @EventHandler - private void onRespawn(PlayerRespawnEvent event) { - Player player = event.getPlayer(); - if (HUNGER_CHANGE.contains(player)) { - HUNGER_CHANGE.remove(player); - - PlayerData playerData = playerManager.getPlayerData(player); - int thirst = config.MECHANICS_THIRST_RESPAWN_AMOUNT; - playerData.setThirst(thirst); - playerManager.getPlayerData(player).setThirst(thirst); - - int hunger = config.MECHANICS_HUNGER_RESPAWN_AMOUNT; - Bukkit.getScheduler().runTaskLater(plugin, () -> StatusManager.setHunger(player, hunger), 1); - } - } - - @EventHandler - private void onDeath(PlayerDeathEvent event) { - Player player = event.getEntity(); - if (!HUNGER_CHANGE.contains(player)) { - HUNGER_CHANGE.add(player); - } - } - - private boolean checkWaterBottle(ItemStack bottle) { - ItemMeta meta = bottle.getItemMeta(); - assert meta != null; - switch (((PotionMeta) meta).getBasePotionData().getType()) { - case WATER: - case MUNDANE: - case THICK: - case AWKWARD: - return true; - default: - return false; - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/FirestrikerClick.java b/src/main/java/tk/shanebee/survival/listeners/item/FirestrikerClick.java deleted file mode 100644 index ab485b3..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/FirestrikerClick.java +++ /dev/null @@ -1,187 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.Tag; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.Lightable; -import org.bukkit.entity.LivingEntity; -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.BlockIgniteEvent; -import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.item.items.FireStriker; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.util.Utils; - -import java.util.Random; - -public class FirestrikerClick implements Listener { - - private final Lang lang; - - public FirestrikerClick(Survival plugin) { - this.lang = plugin.getLang(); - } - - @EventHandler - private void onItemClick(PlayerInteractEvent event) { - if (event.hasItem()) { - Player player = event.getPlayer(); - Block clickedBlock = event.getClickedBlock(); - ItemStack tool = event.getItem(); - Action action = event.getAction(); - if (clickedBlock == null || tool == null) return; - - Material clickedBlockType = clickedBlock.getType(); - Material toolType = tool.getType(); - if (ItemManager.compare(tool, Item.FIRESTRIKER)) { - if (player.isSneaking()) { - if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) { - Random rand = new Random(); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ITEM_SHOVEL_FLATTEN, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - - event.setCancelled(true); - FireStriker fireStriker = new FireStriker(player, tool.clone()); - fireStriker.open(); - tool.setAmount(0); - player.updateInventory(); - } - } else { - if (action == Action.RIGHT_CLICK_BLOCK) { - switch (clickedBlockType) { - case ENCHANTING_TABLE: - case ANVIL: - case BREWING_STAND: - case SPRUCE_DOOR: - case BIRCH_DOOR: - case OAK_DOOR: - case JUNGLE_DOOR: - case ACACIA_DOOR: - case DARK_OAK_DOOR: - case IRON_DOOR: - case TRAPPED_CHEST: - case CHEST: - case NOTE_BLOCK: - case IRON_TRAPDOOR: - case FURNACE: - case HOPPER: - case CRAFTING_TABLE: - case DROPPER: - case DISPENSER: - case REDSTONE_WALL_TORCH: - case REDSTONE_TORCH: - return; - default: - } - if (Tag.BEDS.isTagged(clickedBlockType)) return; - if (Utils.isWoodGate(clickedBlockType)) return; - if (Tag.TRAPDOORS.isTagged(clickedBlockType)) return; - if (clickedBlockType == Material.CAMPFIRE) { - Lightable camp = ((Lightable) clickedBlock.getBlockData()); - if (camp.isLit()) return; - camp.setLit(true); - clickedBlock.setBlockData(camp); - } - // Cancel turning grass block into grass path - if (clickedBlockType == Material.GRASS_BLOCK) { - event.setCancelled(true); - } - Location loc = clickedBlock.getRelative(event.getBlockFace()).getLocation(); - if (ignite(player, loc)) { - Random rand = new Random(); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ITEM_SHOVEL_FLATTEN, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - - ItemMeta meta = tool.getItemMeta(); - ((Damageable) meta).setDamage(((Damageable) meta).getDamage() + 7); - tool.setItemMeta(meta); - if (((Damageable) tool.getItemMeta()).getDamage() >= 56) { - player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - if (player.getInventory().getItemInMainHand().getType() == toolType) - player.getInventory().setItemInMainHand(null); - else if (player.getInventory().getItemInOffHand().getType() == toolType) - player.getInventory().setItemInOffHand(null); - } - player.updateInventory(); - } - } - } - } - } - } - - private boolean ignite(Player igniter, Location loc) { - Random rand = new Random(); - - loc.add(0.5, 0.5, 0.5); - - BlockIgniteEvent igniteEvent = new BlockIgniteEvent(loc.getBlock(), - IgniteCause.FLINT_AND_STEEL, igniter); - Bukkit.getServer().getPluginManager().callEvent(igniteEvent); - if (igniteEvent.isCancelled()) { - return false; - } - - BlockState blockState = loc.getBlock().getState(); - - BlockPlaceEvent placeEvent = new BlockPlaceEvent(loc.getBlock(), - blockState, loc.getBlock(), igniter.getInventory().getItemInMainHand(), igniter, true, EquipmentSlot.HAND); - Bukkit.getServer().getPluginManager().callEvent(placeEvent); - - if (placeEvent.isCancelled() || !placeEvent.canBuild()) { - placeEvent.getBlockPlaced().getState().setType(Material.AIR); - return false; - } - - - loc.getWorld().playSound(loc, Sound.ITEM_FLINTANDSTEEL_USE, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - loc.getBlock().setType(Material.FIRE); - - return true; - } - - @EventHandler - private void onCloseInventory(InventoryCloseEvent event) { - if (event.getView().getTitle().equalsIgnoreCase(Utils.getColoredString(lang.firestriker))) { - Inventory inv = event.getInventory(); - if (inv.getHolder() instanceof FireStriker) { - ((FireStriker) inv.getHolder()).close(); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - private void onAttack(EntityDamageByEntityEvent event) { - if (event.isCancelled()) return; - if (event.getDamager() instanceof Player && event.getEntity() instanceof LivingEntity && event.getCause() == DamageCause.ENTITY_ATTACK) { - Player player = (Player) event.getDamager(); - ItemStack item = player.getInventory().getItemInMainHand(); - if (ItemManager.compare(item, Item.FIRESTRIKER)) { - ItemMeta meta = item.getItemMeta(); - assert meta != null; - ((Damageable) meta).setDamage(((Damageable) meta).getDamage() - 2); - item.setItemMeta(meta); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/GiantBlade.java b/src/main/java/tk/shanebee/survival/listeners/item/GiantBlade.java deleted file mode 100644 index 67170b5..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/GiantBlade.java +++ /dev/null @@ -1,207 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import java.util.Collection; -import java.util.Random; - -import org.bukkit.block.Block; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.meta.ItemMeta; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.data.Stat; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; -import org.bukkit.*; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -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.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.util.Vector; - -import tk.shanebee.survival.Survival; - -public class GiantBlade implements Listener { - - private final Survival plugin; - private final Lang lang; - private final PlayerManager playerManager; - - public GiantBlade(Survival plugin) { - this.plugin = plugin; - this.lang = plugin.getLang(); - this.playerManager = plugin.getPlayerManager(); - } - - @EventHandler(priority = EventPriority.HIGHEST) - private void onAttack(EntityDamageByEntityEvent event) { - if (event.isCancelled()) return; - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (Utils.isCitizensNPC(player)) return; - PlayerData playerData = playerManager.getPlayerData(player); - ItemStack offItem = player.getInventory().getItemInOffHand(); - ItemMeta offItemMeta = offItem.getItemMeta(); - assert offItemMeta != null; - - if (playerData.getStat(Stat.DUAL_WIELD) == 1) { - event.setCancelled(true); - return; - } - - Random rand = new Random(); - - if (ItemManager.compare(offItem, Item.ENDER_GIANT_BLADE)) { - if (event.getDamager() instanceof LivingEntity && event.getCause() == DamageCause.ENTITY_ATTACK) { - LivingEntity enemy = (LivingEntity) event.getDamager(); - enemy.damage(event.getDamage() * 40 / 100, player); - } - - int chance_reduceDur = rand.nextInt(10) + 1; - if (chance_reduceDur == 1) { - ((Damageable) offItemMeta).setDamage(((Damageable) offItemMeta).getDamage() + 1); - offItem.setItemMeta(offItemMeta); - } - - if (((Damageable) offItemMeta).getDamage() >= offItem.getType().getMaxDurability()) { - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - player.getInventory().setItemInOffHand(null); - } - } - } - } - - //To prevent double messages send to player. - - @EventHandler - private void onItemClick(PlayerInteractEvent event) { - Player player = event.getPlayer(); - PlayerData playerData = playerManager.getPlayerData(player); - ItemStack mainItem = player.getInventory().getItemInMainHand(); - ItemStack offItem = player.getInventory().getItemInOffHand(); - ItemMeta mainItemMeta = mainItem.getItemMeta(); - ItemMeta offItemMeta = offItem.getItemMeta();; - assert mainItemMeta != null; - assert offItemMeta != null; - - if (ItemManager.compare(mainItem, Item.ENDER_GIANT_BLADE)) { - if (playerData.getStat(Stat.DUAL_WIELD) == 0) { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { - Block clickedBlock = event.getClickedBlock(); - // Prevent giant blade for turning dirt/grass into farmland - if (clickedBlock != null && (clickedBlock.getType() == Material.GRASS_BLOCK || clickedBlock.getType() == Material.DIRT)) { - event.setCancelled(true); - } - if (event.getHand() != EquipmentSlot.HAND) return; // prevent double message - - if (player.isSprinting()) { - if (playerData.getStat(Stat.CHARGE) == 0) { - Random rand = new Random(); - - ChargeForward(player); - - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) - player.setFoodLevel(player.getFoodLevel() - 1); - - int chance_reduceDur = rand.nextInt(10) + 1; - if (chance_reduceDur == 1) { - ((Damageable) mainItemMeta).setDamage(((Damageable) mainItemMeta).getDamage() + 1); - mainItem.setItemMeta(mainItemMeta); - } - - if (((Damageable) mainItemMeta).getDamage() >= mainItem.getType().getMaxDurability()) { - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - player.getInventory().setItemInMainHand(null); - } - player.updateInventory(); - } else { - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.charge_unable)); - } - } - } - } else { - if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) - playerData.setStat(Stat.DUAL_WIELD_MSG, playerData.getStat(Stat.DUAL_WIELD_MSG) + 1); - else if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) - playerData.setStat(Stat.DUAL_WIELD_MSG, playerData.getStat(Stat.DUAL_WIELD_MSG) + 2); - if (playerData.getStat(Stat.DUAL_WIELD_MSG) >= 2) { - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.ender_giant_blade_unable_duel)); - } - } - } else if (ItemManager.compare(offItem, Item.ENDER_GIANT_BLADE)) { - if (playerData.getStat(Stat.DUAL_WIELD) != 0) { - if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) - playerData.setStat(Stat.DUAL_WIELD_MSG, playerData.getStat(Stat.DUAL_WIELD_MSG) + 1); - else if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) - playerData.setStat(Stat.DUAL_WIELD_MSG, playerData.getStat(Stat.DUAL_WIELD_MSG) + 2); - if (playerData.getStat(Stat.DUAL_WIELD_MSG) >= 2) { - player.sendMessage(ChatColor.RED + Utils.getColoredString(lang.ender_giant_blade_unable_duel)); - } - } - } - playerData.setStat(Stat.DUAL_WIELD_MSG, 0); - } - - private void ChargeForward(Player player) { - PlayerData playerData = playerManager.getPlayerData(player); - player.sendMessage(ChatColor.BLUE + Utils.getColoredString(lang.charge)); - - playerData.setStat(Stat.CHARGE, 1); - - - Location loc = player.getLocation(); - if (loc.getPitch() < 0) - loc.setPitch(0); - - Vector vel = loc.getDirection(); - - Vector newVel = vel.multiply(3); - - player.setVelocity(newVel); - - final Player chargingPlayer = player; - playerData.setStat(Stat.CHARGING, 8); - - final Runnable task = new Runnable() { - public void run() { - damageNearbyEnemies(chargingPlayer); - - Random rand = new Random(); - chargingPlayer.getLocation().getWorld().playSound(chargingPlayer.getLocation(), Sound.ENTITY_SHULKER_BULLET_HIT, 1.5F, rand.nextFloat() * 0.4F + 0.8F); - Utils.spawnParticle(chargingPlayer.getLocation(), Particle.EXPLOSION_NORMAL, 10, 0, 0, 0); - - int times = playerData.getStat(Stat.CHARGING); - if (--times > 1) - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, this, 1L); - playerData.setStat(Stat.CHARGING, times); - } - }; - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, task, -1L); - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { - playerData.setStat(Stat.CHARGE, 0); - chargingPlayer.sendMessage(ChatColor.GREEN + Utils.getColoredString(lang.charge_ready)); - }, 100L); - } - - private void damageNearbyEnemies(Player player) { - Collection enemies = player.getLocation().getWorld().getNearbyEntities(player.getLocation(), 2, 2, 2); - for (Entity e : enemies) { - if (e instanceof LivingEntity && e != player) { - LivingEntity enemy = (LivingEntity) e; - enemy.damage(8, player); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/GrapplingHook.java b/src/main/java/tk/shanebee/survival/listeners/item/GrapplingHook.java deleted file mode 100644 index 04218bf..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/GrapplingHook.java +++ /dev/null @@ -1,127 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import java.util.List; - -import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerFishEvent; -import org.bukkit.event.player.PlayerFishEvent.State; -import org.bukkit.util.Vector; - -import tk.shanebee.survival.Survival; - -public class GrapplingHook implements Listener { - - private Lang lang; - - public GrapplingHook(Survival plugin) { - this.lang = plugin.getLang(); - } - - @EventHandler - private void onPlayerFish(PlayerFishEvent event) { - Player p = event.getPlayer(); - ItemStack mainHand = p.getInventory().getItemInMainHand(); - ItemStack offHand = p.getInventory().getItemInOffHand(); - - if (mainHand.getType() == Material.FISHING_ROD) { - p.getInventory().getItemInOffHand(); - if (offHand.getType() == Material.AIR) { - - if (ItemManager.compare(mainHand, Item.GRAPPLING_HOOK)) { - if (event.getState() == State.IN_GROUND) { - List nearbyEntities = p.getNearbyEntities(50, 50, 50); - - Entity hook = null; - - for (Entity e : nearbyEntities) // loop through entities - { - if (e.getType() == EntityType.FISHING_HOOK) //Hook found - { - hook = e; - break; - } - } - - if (hook != null) { - Location hookLoc = hook.getLocation(); - Location playerLoc = p.getLocation(); - - playerLoc.setY(playerLoc.getY() + 0.5); - - - Vector vector = hookLoc.toVector().subtract(playerLoc.toVector()); - if (vector.getY() > 0) - vector.setY(Math.sqrt(vector.getY())); - - p.teleport(playerLoc); - p.setVelocity(vector.multiply(0.5)); - } - } else if (event.getState() == State.CAUGHT_ENTITY) { - if (event.getCaught() != null) { - Location playerLoc = p.getLocation(); - Location entityLoc = event.getCaught().getLocation(); - - playerLoc.setY(playerLoc.getY() + 0.5); - entityLoc.setY(entityLoc.getY() + 0.5); - - if (event.getCaught().getType() != EntityType.DROPPED_ITEM) { - Vector vector = entityLoc.toVector().subtract(playerLoc.toVector()); - if (vector.getY() > 0) - vector.setY(Math.sqrt(vector.getY()) * 4); - - p.teleport(playerLoc); - p.setVelocity(vector.multiply(0.5).multiply(0.25)); - } - - Vector reverseVector = playerLoc.toVector().subtract(entityLoc.toVector()); - - if (reverseVector.getY() > 0) - reverseVector.setY(Math.sqrt(reverseVector.getY())); - - if (event.getCaught().getType() != EntityType.DROPPED_ITEM) { - event.getCaught().teleport(entityLoc); - event.getCaught().setVelocity(reverseVector.multiply(0.5).multiply(0.125)); - } else { - if (reverseVector.getY() > 0) - reverseVector.setY(Math.sqrt(reverseVector.getY()) * 0.5); - - event.getCaught().teleport(entityLoc); - event.getCaught().setVelocity(reverseVector.multiply(0.5).multiply(0.00625)); - } - } - } else if (event.getState() == State.BITE || event.getState() == State.CAUGHT_FISH) { - event.setCancelled(true); - p.updateInventory(); - } - } - } else { - event.setCancelled(true); - if (ItemManager.compare(mainHand, Item.GRAPPLING_HOOK)) - p.sendMessage(ChatColor.RED + Utils.getColoredString(lang.grappling_off_hand)); - else - p.sendMessage(ChatColor.RED + Utils.getColoredString(lang.fishing_off_hand)); - p.updateInventory(); - } - } else { - event.setCancelled(true); - if (ItemManager.compare(offHand, Item.GRAPPLING_HOOK)) - p.sendMessage(ChatColor.RED + Utils.getColoredString(lang.grappling_main_hand)); - else - p.sendMessage(ChatColor.RED + Utils.getColoredString(lang.fishing_main_hand)); - p.updateInventory(); - } - } - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/listeners/item/MedicKit.java b/src/main/java/tk/shanebee/survival/listeners/item/MedicKit.java deleted file mode 100644 index a4a3f98..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/MedicKit.java +++ /dev/null @@ -1,184 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.*; -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.entity.EntityDamageByEntityEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.data.Stat; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.Random; - -public class MedicKit implements Listener { - - private Survival plugin; - private Lang lang; - private PlayerManager playerManager; - - public MedicKit(Survival plugin) { - this.plugin = plugin; - this.lang = plugin.getLang(); - this.playerManager = plugin.getPlayerManager(); - } - - - - @EventHandler(priority = EventPriority.HIGHEST) - private void onDamaged(EntityDamageByEntityEvent event) { - if (event.isCancelled()) return; - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - PlayerData playerData = playerManager.getPlayerData(player); - playerData.setStat(Stat.HEALING, 0); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - private void onClickEntity(PlayerInteractEntityEvent event) { - if (event.isCancelled()) return; - final Player player = event.getPlayer(); - PlayerData playerData = playerManager.getPlayerData(player); - final ItemStack mainItem = player.getInventory().getItemInMainHand(); - - if (ItemManager.compare(mainItem, Item.MEDIC_KIT)) { - if (playerData.getStat(Stat.HEALING) <= 0) { - if (!player.isSneaking()) { - if (event.getRightClicked() instanceof Player) { - final Player healed = (Player) event.getRightClicked(); - PlayerData healedData = playerManager.getPlayerData(healed); - - if (healedData.getStat(Stat.HEALING) <= 0) { - if (player.getLocation().distance(healed.getLocation()) <= 4) { - playerData.setStat(Stat.HEALING, 1); - healedData.setStat(Stat.HEALING, 1); - healed.teleport(playerManager.lookAt(healed.getLocation(), player.getLocation())); - player.sendMessage(Utils.getColoredString(lang.healing) + ChatColor.RESET + healed.getDisplayName() + Utils.getColoredString(lang.keep) + ChatColor.DARK_GREEN + Utils.getColoredString(lang.medical_kit) + Utils.getColoredString(lang.on_hand)); - healed.sendMessage(Utils.getColoredString(lang.being_healed) + ChatColor.RESET + player.getDisplayName() + Utils.getColoredString(lang.stay_still)); - - playerData.setStat(Stat.HEAL_TIMES, 5); - final Runnable task = new Runnable() { - public void run() { - int times = playerData.getStat(Stat.HEAL_TIMES); - if (player.getInventory().getItemInMainHand().getType() == Material.CLOCK && player.getLocation().distance(healed.getLocation()) <= 4 && playerData.getStat(Stat.HEALING) > 0 && healedData.getStat(Stat.HEALING) > 0) { - if (times-- > 0) { - player.teleport(playerManager.lookAt(player.getLocation(), healed.getLocation())); - - Random rand = new Random(); - - player.removePotionEffect(PotionEffectType.SLOW); - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20, 6, true, false)); - player.removePotionEffect(PotionEffectType.JUMP); - player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20, 199, true, false)); - - healed.getWorld().playSound(healed.getLocation(), Sound.ENTITY_LEASH_KNOT_PLACE, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - healed.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 0)); - - Location particleLoc = healed.getLocation(); - particleLoc.setY(particleLoc.getY() + 1); - Utils.spawnParticle(particleLoc, Particle.VILLAGER_HAPPY, 10, 0.5, 0.5, 0.5); - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, this, 20L); - playerData.setStat(Stat.HEAL_TIMES, times); - } else { - playerData.setStat(Stat.HEALING, 0); - healedData.setStat(Stat.HEALING, 0); - - player.sendMessage(ChatColor.DARK_GREEN + Utils.getColoredString(lang.healing_complete)); - healed.sendMessage(ChatColor.DARK_GREEN + Utils.getColoredString(lang.healing_complete)); - - player.getInventory().removeItem(ItemManager.get(Item.MEDIC_KIT)); - } - } else { - playerData.setStat(Stat.HEALING, 0); - healedData.setStat(Stat.HEALING, 0); - - player.sendMessage(ChatColor.DARK_RED + Utils.getColoredString(lang.healing_interrupted)); - healed.sendMessage(ChatColor.DARK_RED + Utils.getColoredString(lang.healing_interrupted)); - - player.getInventory().removeItem(ItemManager.get(Item.MEDIC_KIT)); - } - } - }; - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, task, -1L); - } - } - } - } - } - } - } - - @EventHandler - private void onSelfClick(PlayerInteractEvent event) { - if (event.hasItem() && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { - final Player player = event.getPlayer(); - PlayerData playerData = playerManager.getPlayerData(player); - ItemStack mainItem = player.getInventory().getItemInMainHand(); - if (ItemManager.compare(mainItem, Item.MEDIC_KIT)) { - if (playerData.getStat(Stat.HEALING) <= 0) { - if (player.isSneaking()) { - playerData.setStat(Stat.HEALING, 1); - player.sendMessage(Utils.getColoredString(lang.healing_self) + Utils.getColoredString(lang.keep) + ChatColor.DARK_GREEN + Utils.getColoredString(lang.medical_kit) + Utils.getColoredString(lang.on_hand)); - - playerData.setStat(Stat.HEAL_TIMES, 5); - final Runnable task = new Runnable() { - public void run() { - int times = playerData.getStat(Stat.HEAL_TIMES); - if (ItemManager.compare(player.getInventory().getItemInMainHand(), Item.MEDIC_KIT) && playerData.getStat(Stat.HEALING) > 0) { - if (times-- > 0) { - Random rand = new Random(); - - player.removePotionEffect(PotionEffectType.SLOW); - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20, 6, true, false)); - player.removePotionEffect(PotionEffectType.JUMP); - player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20, 199, true, false)); - - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_LEASH_KNOT_PLACE, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 0)); - - Location particleLoc = player.getLocation(); - particleLoc.setY(particleLoc.getY() + 1); - Utils.spawnParticle(particleLoc, Particle.VILLAGER_HAPPY, 10, 0.5, 0.5, 0.5); - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, this, 20L); - playerData.setStat(Stat.HEAL_TIMES, times); - } else { - playerData.setStat(Stat.HEALING, 0); - - player.sendMessage(ChatColor.DARK_GREEN + Utils.getColoredString(lang.healing_complete)); - - player.getInventory().removeItem(ItemManager.get(Item.MEDIC_KIT)); - } - } else { - playerData.setStat(Stat.HEALING, 0); - - player.sendMessage(ChatColor.DARK_RED + Utils.getColoredString(lang.healing_interrupted)); - - player.getInventory().removeItem(ItemManager.get(Item.MEDIC_KIT)); - } - } - }; - - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, task, -1L); - } - } - } - } - } - - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/listeners/item/ObsidianMaceWeakness.java b/src/main/java/tk/shanebee/survival/listeners/item/ObsidianMaceWeakness.java deleted file mode 100644 index a6bfa51..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/ObsidianMaceWeakness.java +++ /dev/null @@ -1,65 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Material; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.managers.EffectManager; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; -import org.bukkit.entity.LivingEntity; -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.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.inventory.ItemStack; - -public class ObsidianMaceWeakness implements Listener { - - private EffectManager effectManager; - private Config config; - - public ObsidianMaceWeakness(Survival plugin) { - this.effectManager = plugin.getEffectManager(); - this.config = plugin.getSurvivalConfig(); - } - - @EventHandler(priority = EventPriority.HIGHEST) - private void onAttack(EntityDamageByEntityEvent event) { - if (event.isCancelled()) return; - if (event.getDamager() instanceof Player && event.getEntity() instanceof LivingEntity && event.getCause() == DamageCause.ENTITY_ATTACK) { - Player player = (Player) event.getDamager(); - if (Utils.isCitizensNPC(player)) return; - ItemStack mainItem = player.getInventory().getItemInMainHand(); - LivingEntity enemy = (LivingEntity) event.getEntity(); - - if (ItemManager.compare(mainItem, Item.OBSIDIAN_MACE)) { - effectManager.applyObsidianMaceEffects(player, enemy); - } - } - } - - // Prevent obsidian mace turning dirt/grass block into farmland - @EventHandler - private void onInteractBlock(PlayerInteractEvent event) { - if (!this.config.LEGENDARY_OBSIDIAN_MACE) return; - - if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - ItemStack tool = event.getItem(); - if (event.getClickedBlock() == null || tool == null) return; - - Material clickedBlock = event.getClickedBlock().getType(); - - if (ItemManager.compare(tool, Item.OBSIDIAN_MACE)) { - if (clickedBlock == Material.GRASS_BLOCK || clickedBlock == Material.DIRT) { - event.setCancelled(true); - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/listeners/item/RecurvedBow.java b/src/main/java/tk/shanebee/survival/listeners/item/RecurvedBow.java deleted file mode 100644 index 33e8e7b..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/RecurvedBow.java +++ /dev/null @@ -1,81 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Bukkit; -import org.bukkit.Sound; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityShootBowEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.events.ShootRecurvedBowEvent; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; - -import java.util.Random; - -public class RecurvedBow implements Listener { - - private Survival plugin; - - public RecurvedBow(Survival plugin) { - this.plugin = plugin; - } - - @EventHandler - private void onShoot(EntityShootBowEvent event) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (Utils.isCitizensNPC(player)) return; - ItemStack mainItem = event.getBow(); - - assert mainItem != null; - if (ItemManager.compare(mainItem, Item.RECURVE_BOW) || ItemManager.compare(mainItem, Item.RECURVE_CROSSBOW)) { - Random rand = new Random(); - if (event.getForce() >= 1.0F) { - final Entity arrow = event.getProjectile(); - final Vector velocity = player.getLocation().getDirection().add(new Vector(0, 0.025, 0)).multiply(4); - Item item; - if (ItemManager.compare(mainItem, Item.RECURVE_BOW)) { - item = Item.RECURVE_BOW; - } else { - item = Item.RECURVE_CROSSBOW; - } - // Call new ShootRecurvedBowEvent - ShootRecurvedBowEvent shootEvent = new ShootRecurvedBowEvent(player, mainItem, item); - Bukkit.getPluginManager().callEvent(shootEvent); - if (shootEvent.isCancelled()) { - event.setCancelled(true); - return; - } - - arrow.setVelocity(velocity); - - player.getWorld().playSound(player.getLocation(), Sound.BLOCK_LEVER_CLICK, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_SHULKER_BULLET_HURT, 0.5F, rand.nextFloat() * 0.4F + 0.8F); - final Runnable task = new Runnable() { - int times = 4; - - public void run() { - if (!arrow.isOnGround()) { - arrow.setVelocity(velocity); - if (times-- > 0) - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, this, 5); - } - } - }; - - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, task, -1); - } else { - event.setCancelled(true); - player.updateInventory(); - player.getWorld().playSound(player.getLocation(), Sound.BLOCK_LEVER_CLICK, 0.5F, rand.nextFloat() * 0.4F + 0.8F); - } - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/RepairCrafting.java b/src/main/java/tk/shanebee/survival/listeners/item/RepairCrafting.java deleted file mode 100644 index 63505d6..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/RepairCrafting.java +++ /dev/null @@ -1,138 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Keyed; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.event.inventory.PrepareAnvilEvent; -import org.bukkit.event.inventory.PrepareItemCraftEvent; -import org.bukkit.inventory.AnvilInventory; -import org.bukkit.inventory.CraftingInventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Recipe; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import tk.shanebee.survival.item.Item; - -import java.util.ArrayList; -import java.util.List; - -public class RepairCrafting implements Listener { - - @EventHandler - private void onCraft(PrepareItemCraftEvent event) { - Recipe recipe = event.getRecipe(); - if (recipe instanceof Keyed && ((Keyed) recipe).getKey().getNamespace().equalsIgnoreCase("survivalplus")) { - // If this is a legit recipe, let's get outta here - return; - } - CraftingInventory inventory = event.getInventory(); - - List items = new ArrayList<>(); - for (ItemStack itemStack : inventory.getMatrix()) { - if (itemStack != null) { - items.add(itemStack); - } - } - - if (items.size() == 2) { - ItemStack iOne = items.get(0); - ItemStack iTwo = items.get(1); - Item itemOne = Item.getFromStack(iOne); - Item itemTwo = Item.getFromStack(iTwo); - if (itemOne != null && itemOne == itemTwo) { - ItemStack result = repair(iOne, iTwo, itemOne); - if (inventory.getType() == InventoryType.CRAFTING || itemOne.getRepairCostMultiplier() >= 0) { - // No repairing in player inventory - // Cost >= 0 signifies it requires an anvil - result = null; - } - // Since we're using a crafting table we're going to reset defaults - // ie: remove enchantments - result = resetItem(result); - inventory.setResult(result); - - } else if ((itemOne != null && itemTwo == null) || (itemOne == null && itemTwo != null)) { - // Prevent repairing custom items with vanilla items - inventory.setResult(null); - - } - } - items.clear(); - } - - @EventHandler - private void onAnvilRepair(PrepareAnvilEvent event) { - AnvilInventory inventory = event.getInventory(); - ItemStack iOne = inventory.getContents()[0]; - ItemStack iTwo = inventory.getContents()[1]; - if (iOne != null && iTwo != null) { - if (iOne.getType() != iTwo.getType()) { - // If two different items, lets get outta here - // ie: enchanting - return; - } - Item itemOne = Item.getFromStack(iOne); - Item itemTwo = Item.getFromStack(iTwo); - // Let's make sure we're joining two of the same item - if (itemOne != null && itemOne == itemTwo) { - ItemStack result = repair(iOne, iTwo, itemOne); - event.setResult(result); - double cost = itemOne.getRepairCostMultiplier(); - if (cost > 0) { - inventory.setRepairCost((int) Math.round(inventory.getRepairCost() * cost)); - } - } else if ((itemOne != null && itemTwo == null) || (itemOne == null && itemTwo != null)) { - // Prevent repairing custom items with vanilla items - event.setResult(null); - } - } - - } - - private ItemStack repair(ItemStack itemStackOne, ItemStack itemStackTwo, Item item) { - double repairPercent = item.getRepairPercent(); - if (repairPercent <= 0) { - return null; - } - - ItemStack result = itemStackOne.clone(); - double max = itemStackOne.getType().getMaxDurability(); - int dura1 = getRemainingDurability(itemStackOne); - int dura2 = getRemainingDurability(itemStackTwo); - int repair = (int) Math.min((dura1 + dura2 + Math.floor(max / 20)) * repairPercent, max); - - ItemMeta meta = result.getItemMeta(); - assert meta != null; - ((Damageable) meta).setDamage((int) (max - repair)); - result.setItemMeta(meta); - return result; - } - - private ItemStack resetItem(ItemStack itemStack) { - Item item = Item.getFromStack(itemStack); - - ItemMeta itemMeta = itemStack.getItemMeta(); - assert itemMeta != null; - int damage = ((Damageable) itemMeta).getDamage(); - - assert item != null; - ItemStack newItemStack = item.getItem(); - ItemMeta newItemMeta = newItemStack.getItemMeta(); - assert newItemMeta != null; - ((Damageable) newItemMeta).setDamage(damage); - newItemStack.setItemMeta(newItemMeta); - - return newItemStack; - } - - private int getRemainingDurability(ItemStack itemStack) { - ItemMeta meta = itemStack.getItemMeta(); - - if (meta instanceof Damageable) { - return itemStack.getType().getMaxDurability() - ((Damageable) meta).getDamage(); - } - return 0; - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/WaterBottleCrafting.java b/src/main/java/tk/shanebee/survival/listeners/item/WaterBottleCrafting.java deleted file mode 100644 index d1132d8..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/WaterBottleCrafting.java +++ /dev/null @@ -1,100 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Bukkit; -import org.bukkit.FluidCollisionMode; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Waterlogged; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.CraftItemEvent; -import org.bukkit.event.inventory.PrepareItemCraftEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.CraftingInventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionType; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.config.Config; - -import java.util.Objects; - - -public class WaterBottleCrafting implements Listener { - - private Survival plugin; - private Config config; - - public WaterBottleCrafting(Survival plugin) { - this.plugin = plugin; - this.config = plugin.getSurvivalConfig(); - } - - @EventHandler - private void onCraft(CraftItemEvent e) { - final Player player = (Player) e.getWhoClicked(); - final CraftingInventory inv = e.getInventory(); - - ItemStack[] bottles = inv.getMatrix(); - ItemStack result = inv.getResult(); - - if (result != null && result.getType() == Material.CLAY) { - for (int i = 0; i < bottles.length; i++) { - if (bottles[i] == null) continue; - if (bottles[i].getType() == Material.POTION) { - final int slot = i + 1; - Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> { - inv.setItem(slot, new ItemStack(Material.BOWL)); - player.updateInventory(); - }, 1); - } - } - } - } - - @EventHandler - private void onFillWaterBottle(PlayerInteractEvent e) { - if (!config.MECHANICS_THIRST_PURIFY_WATER) return; - Player player = e.getPlayer(); - ItemStack item = e.getItem(); - if (item != null && item.getType() == Material.GLASS_BOTTLE) { - Block targetBlock = player.getTargetBlockExact(5, FluidCollisionMode.ALWAYS); - if (targetBlock == null) return; - if (isWaterBlock(targetBlock)) { - e.setCancelled(true); - if (item.getAmount() > 1) { - if (player.getInventory().addItem(ItemManager.get(Item.DIRTY_WATER)).size() > 0) { - player.getWorld().dropItem(player.getLocation(), Item.DIRTY_WATER.getItem()); - } - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) - item.setAmount(item.getAmount() - 1); - } else { - if (player.getInventory().getItemInMainHand().getType() == item.getType()) - player.getInventory().setItemInMainHand(ItemManager.get(Item.DIRTY_WATER)); - else if (player.getInventory().getItemInOffHand().getType() == item.getType()) - player.getInventory().setItemInOffHand(ItemManager.get(Item.DIRTY_WATER)); - } - } - } - } - - private boolean isWaterBlock(Block block) { - if (block.getType() == Material.WATER) { - return true; - } - BlockData data = block.getBlockData(); - return data instanceof Waterlogged && ((Waterlogged) data).isWaterlogged(); - } - - private boolean checkWaterBottle(ItemStack bottle) { - - return ((PotionMeta) Objects.requireNonNull(bottle.getItemMeta())).getBasePotionData().getType() == PotionType.WATER; - - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/item/WaterBowl.java b/src/main/java/tk/shanebee/survival/listeners/item/WaterBowl.java deleted file mode 100644 index 9fb632f..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/item/WaterBowl.java +++ /dev/null @@ -1,85 +0,0 @@ -package tk.shanebee.survival.listeners.item; - -import org.bukkit.Bukkit; -import org.bukkit.Keyed; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.ItemSpawnEvent; -import org.bukkit.event.inventory.PrepareItemCraftEvent; -import org.bukkit.event.player.PlayerItemConsumeEvent; -import org.bukkit.inventory.CraftingInventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Recipe; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.events.WaterBowlFillEvent; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.ItemManager; - -public class WaterBowl implements Listener { - - private final Survival plugin; - private final boolean THIRST_ENABLED; - private final boolean CLAY_ENABLED; - - public WaterBowl(Survival plugin) { - this.plugin = plugin; - this.THIRST_ENABLED = plugin.getSurvivalConfig().MECHANICS_THIRST_ENABLED; - this.CLAY_ENABLED = plugin.getSurvivalConfig().RECIPES_CLAY; - } - - @EventHandler(priority = EventPriority.HIGHEST) - private void onConsume(PlayerItemConsumeEvent event) { - if (!THIRST_ENABLED) { - if (event.isCancelled()) return; - if (ItemManager.compare(event.getItem(), Item.WATER_BOWL)) { - event.setCancelled(true); - } - } - } - - @EventHandler - private void onDrop(ItemSpawnEvent event) { - if (event.isCancelled()) return; - if (THIRST_ENABLED || CLAY_ENABLED) { - final org.bukkit.entity.Item itemDrop = event.getEntity(); - if (itemDrop.getItemStack().getType() == Material.BOWL) { - final Runnable task = () -> { - Location itemLocation = itemDrop.getLocation(); - if (itemLocation.getBlock().getType() == Material.WATER) { - WaterBowlFillEvent bowlFillEvent = new WaterBowlFillEvent(itemDrop.getItemStack()); - Bukkit.getPluginManager().callEvent(bowlFillEvent); - if (bowlFillEvent.isCancelled()) return; - int amount = itemDrop.getItemStack().getAmount(); - itemDrop.remove(); - for (int i = 0; i < amount; i++) { - itemDrop.getWorld().dropItem(itemLocation, Item.WATER_BOWL.getItem()); - } - } - }; - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, task, 20L); - } - } - } - - // Prevent water bowls turning into glass bottles - @EventHandler - private void onCraft(PrepareItemCraftEvent event) { - Recipe recipe = event.getRecipe(); - if (recipe instanceof Keyed) { - String key = ((Keyed) recipe).getKey().getKey(); - if (key.equalsIgnoreCase("glass_bottle")) { - CraftingInventory inventory = event.getInventory(); - for (ItemStack itemStack : inventory.getMatrix()) { - if (itemStack != null && Item.WATER_BOWL.compare(itemStack)) { - inventory.setResult(null); - } - } - } - } - - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/player/EnergyChange.java b/src/main/java/tk/shanebee/survival/listeners/player/EnergyChange.java deleted file mode 100644 index 65bc3c3..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/player/EnergyChange.java +++ /dev/null @@ -1,144 +0,0 @@ -package tk.shanebee.survival.listeners.player; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.inventory.CraftItemEvent; -import org.bukkit.event.player.PlayerItemConsumeEvent; -import org.bukkit.event.world.TimeSkipEvent; -import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.events.EnergyLevelChangeEvent; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.util.Utils; - -public class EnergyChange implements Listener { - - private final Survival plugin; - private final PlayerManager playerManager; - private final Config config; - private final Lang lang; - private final double ENERGY_RESPAWN; - - public EnergyChange(Survival plugin) { - this.plugin = plugin; - this.playerManager = plugin.getPlayerManager(); - this.config = plugin.getSurvivalConfig(); - this.lang = plugin.getLang(); - this.ENERGY_RESPAWN = config.MECHANICS_ENERGY_RESPAWN; - } - - @EventHandler - private void onRespawn(PlayerDeathEvent event) { - Player player = event.getEntity(); - if (Utils.isCitizensNPC(player)) return; - PlayerData playerData = playerManager.getPlayerData(player); - - double change = ENERGY_RESPAWN - playerData.getEnergy(); - EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, change, ENERGY_RESPAWN); - Bukkit.getPluginManager().callEvent(energyEvent); - if (energyEvent.isCancelled()) return; - playerData.setEnergy(ENERGY_RESPAWN); - } - - @EventHandler - private void onDrinkCoffee(PlayerItemConsumeEvent e) { - ItemStack item = e.getItem(); - Player player = e.getPlayer(); - PlayerData playerData = playerManager.getPlayerData(player); - - if (ItemManager.compare(item, Item.COFFEE)) { - EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, 20.0 - playerData.getEnergy(), 20.0); - Bukkit.getPluginManager().callEvent(energyEvent); - if (energyEvent.isCancelled()) return; - playerData.setEnergy(20); - } - } - - // Removes empty water bottles from crafting grid when brewing coffee - @EventHandler - private void onCraftCoffee(CraftItemEvent e) { - if (ItemManager.compare(e.getRecipe().getResult(), Item.COFFEE)) { - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> e.getInventory().remove(Material.GLASS_BOTTLE), 2); - } - } - - // Decrease energy when player does exhaustive tasks - @EventHandler - private void onSaturationReached(FoodLevelChangeEvent event) { - double modifier = config.MECHANICS_ENERGY_EXHAUSTION; - if (modifier <= 0) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (event.getFoodLevel() > player.getFoodLevel()) return; - GameMode mode = player.getGameMode(); - if (mode == GameMode.SURVIVAL || mode == GameMode.ADVENTURE) { - PlayerData playerData = playerManager.getPlayerData(player); - EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, -modifier, playerData.getEnergy() - modifier); - Bukkit.getPluginManager().callEvent(energyEvent); - if (energyEvent.isCancelled()) return; - playerData.increaseEnergy(-modifier); - } - } - - // Send messages when energy level decreases - @EventHandler - private void onEnergyDrop(EnergyLevelChangeEvent event) { - if (!config.MECHANICS_ENERGY_WARNING) return; - if (event.getChanged() < 0) { - Player player = event.getPlayer(); - PlayerData playerData = playerManager.getPlayerData(player); - double level = event.getEnergyLevel(); - double newLevel = playerData.getEnergy(); - - if (targetMatch(10.0, level, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_10); - } else if (targetMatch(6.5, level, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_6_5); - } else if (targetMatch(3.5, level, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_3_5); - } else if (targetMatch(2, level, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_2); - } else if (targetMatch(1, level, newLevel)) { - Utils.sendColoredMsg(player, lang.energy_level_1); - } - } - } - - // Check if the change passed a certain amount - private boolean targetMatch(double target, double level, double newLevel) { - return level <= target && newLevel > target; - } - - // Increase players energy when they wakeup after the night skips - // Or cancel the night skip event if true in config (forcing players to lay in bed and let energy increase) - @EventHandler - private void onSkipNight(TimeSkipEvent event) { - if (config.MECHANICS_PREVENT_NIGHT_SKIP) { - if (event.getSkipReason() == TimeSkipEvent.SkipReason.NIGHT_SKIP) { - event.setCancelled(true); - } - } else { - for (Player player : event.getWorld().getPlayers()) { - if (!player.isSleeping()) continue; - PlayerData playerData = playerManager.getPlayerData(player); - - EnergyLevelChangeEvent energyEvent = new EnergyLevelChangeEvent(player, 20.0 - playerData.getEnergy(), 20.0); - Bukkit.getPluginManager().callEvent(energyEvent); - if (energyEvent.isCancelled()) return; - playerData.setEnergy(20); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/server/Guide.java b/src/main/java/tk/shanebee/survival/listeners/server/Guide.java deleted file mode 100644 index 4b50fd1..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/server/Guide.java +++ /dev/null @@ -1,44 +0,0 @@ -package tk.shanebee.survival.listeners.server; - -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.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -public class Guide implements Listener { - - private Survival plugin; - private Lang lang; - private Config config; - - public Guide(Survival plugin) { - this.plugin = plugin; - this.lang = plugin.getLang(); - this.config = plugin.getSurvivalConfig(); - } - - @EventHandler - private void onJoin(PlayerJoinEvent e) { - if (e.getPlayer().hasPlayedBefore() && config.WELCOME_GUIDE_NEW_PLAYERS) return; - int delay = config.WELCOME_GUIDE_DELAY; - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { - Player player = e.getPlayer(); - TextComponent msg = new TextComponent(Utils.getColoredString(lang.survival_guide_msg)); - TextComponent link = new TextComponent(Utils.getColoredString(lang.survival_guide_click_msg)); - link.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, lang.survival_guide_link)); - link.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, - new ComponentBuilder(Utils.getColoredString(lang.survival_guide_hover_msg)).create())); - player.spigot().sendMessage(msg, link); - }, 20 * delay); - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/server/InventoryUpdate.java b/src/main/java/tk/shanebee/survival/listeners/server/InventoryUpdate.java deleted file mode 100644 index 7722bbb..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/server/InventoryUpdate.java +++ /dev/null @@ -1,57 +0,0 @@ -package tk.shanebee.survival.listeners.server; - -import org.bukkit.Material; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryOpenEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -@SuppressWarnings("deprecation") -public class InventoryUpdate implements Listener { - - @EventHandler - private void onJoinUpdate(PlayerJoinEvent e) { // Update old items to new items - Inventory inv = e.getPlayer().getInventory(); - if (needsUpdate(inv)) { - itemCheck(inv); - } - } - - @EventHandler - private void onInventoryOpenUpdate(InventoryOpenEvent e) { // Update old items to new items - Inventory inv = e.getInventory(); - if (needsUpdate(inv)) { - itemCheck(inv); - } - } - - private void itemCheck(Inventory inv) { - for (int i = 0; i < inv.getSize(); i++) { - ItemStack item = inv.getItem(i); - if (item == null) continue; - } - } - - private void itemUpdate(Inventory inv, int slot, ItemStack oldItem, Item newItem) { - assert oldItem.getItemMeta() != null; - int damage = ((Damageable) oldItem.getItemMeta()).getDamage(); - ItemStack item = ItemManager.get(newItem); - ItemMeta meta = item.getItemMeta(); - assert meta != null; - ((Damageable) meta).setDamage(damage); - item.setItemMeta(meta); - inv.setItem(slot, item); - } - - private boolean needsUpdate(Inventory inv) { - return inv.contains(Material.WOODEN_HOE) || inv.contains(Material.GOLDEN_PICKAXE) || inv.contains(Material.GOLDEN_AXE) || - inv.contains(Material.GOLDEN_SHOVEL) || inv.contains(Material.GOLDEN_HOE) || inv.contains(Material.GOLDEN_SWORD); - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/server/NoPos.java b/src/main/java/tk/shanebee/survival/listeners/server/NoPos.java deleted file mode 100644 index 2aae941..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/server/NoPos.java +++ /dev/null @@ -1,105 +0,0 @@ -package tk.shanebee.survival.listeners.server; - -/** - * Originally by Rolyndev's plugin, NoPos - * Modified and implemented by FattyMieo - * Thanks to Rolyndev for allowing implementation! -**/ - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerJoinEvent; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class NoPos implements Listener { - @EventHandler - private void onJoin(PlayerJoinEvent e) { - Player player = e.getPlayer(); - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) - disableF3(player); - } - - @EventHandler - private void onGamemodeChange(PlayerGameModeChangeEvent e) { - Player player = e.getPlayer(); - if (e.getNewGameMode() == GameMode.ADVENTURE || e.getNewGameMode() == GameMode.SURVIVAL) { - disableF3(player); - } else { - enableF3(player); - } - } - - @EventHandler - private void onWorldChange(PlayerChangedWorldEvent e) { - Player player = e.getPlayer(); - if (player.getGameMode() == GameMode.ADVENTURE || player.getGameMode() == GameMode.SURVIVAL) { - disableF3(player); - } - } - - /** - * Disable a player's coordinates in their Minecraft Debug screen - * - * @param player The player to disable coords for - */ - @SuppressWarnings("WeakerAccess") - public static void disableF3(Player player) { - try { - Class packetClass = getNMSClass("PacketPlayOutEntityStatus"); - Constructor packetConstructor = packetClass.getConstructor(getNMSClass("Entity"), Byte.TYPE); - Object packet = packetConstructor.newInstance(getHandle(player), (byte) 22); - Method sendPacket = getNMSClass("PlayerConnection").getMethod("sendPacket", getNMSClass("Packet")); - sendPacket.invoke(getConnection(player), packet); - } catch (Exception e) { - Bukkit.getConsoleSender().sendMessage("[SurvivalPlus] " + ChatColor.RED + e.getMessage()); - } - } - - /** - * Enable a player's coordinates in their Minecraft Debug screen - * - * @param player The player to enable coords for - */ - @SuppressWarnings("WeakerAccess") - public static void enableF3(Player player) { - try { - Class packetClass = getNMSClass("PacketPlayOutEntityStatus"); - Constructor packetConstructor = packetClass.getConstructor(getNMSClass("Entity"), Byte.TYPE); - Object packet = packetConstructor.newInstance(getHandle(player), (byte) 23); - Method sendPacket = getNMSClass("PlayerConnection").getMethod("sendPacket", getNMSClass("Packet")); - sendPacket.invoke(getConnection(player), packet); - } catch (Exception e) { - Bukkit.getConsoleSender().sendMessage("[SurvivalPlus] " + ChatColor.RED + e.getMessage()); - } - } - - private static Class getNMSClass(String nmsClassString) - throws ClassNotFoundException { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3] + "."; - String name = "net.minecraft.server." + version + nmsClassString; - return Class.forName(name); - } - - private static Object getConnection(Player player) - throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { - Field conField = getHandle(player).getClass().getField("playerConnection"); - return conField.get(getHandle(player)); - } - - private static Object getHandle(Player player) - throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { - Method getHandle = player.getClass().getMethod("getHandle"); - return getHandle.invoke(player); - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/server/RecipeDiscovery.java b/src/main/java/tk/shanebee/survival/listeners/server/RecipeDiscovery.java deleted file mode 100644 index 4116279..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/server/RecipeDiscovery.java +++ /dev/null @@ -1,205 +0,0 @@ -package tk.shanebee.survival.listeners.server; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.Tag; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.entity.EntityPickupItemEvent; -import org.bukkit.event.inventory.CraftItemEvent; -import org.bukkit.event.inventory.FurnaceExtractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.inventory.ItemStack; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.managers.RecipeManager.Recipes; - -public class RecipeDiscovery implements Listener { - - private final Survival plugin; - private final boolean UNLOCK_ALL; - - public RecipeDiscovery(Survival plugin) { - this.plugin = plugin; - this.UNLOCK_ALL = plugin.getSurvivalConfig().SURVIVAL_UNLOCK_ALL_RECIPES; - } - - // When a player first joins, give them a few recipes after 10 seconds - @EventHandler - private void onFirstJoin(PlayerJoinEvent e) { - Player player = e.getPlayer(); - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { - if (this.UNLOCK_ALL) { - this.plugin.getRecipeManager().unlockAllRecipes(player); - } else { - player.discoverRecipes(Recipes.HATCHET.getKeys()); - player.discoverRecipes(Recipes.MATTOCK.getKeys()); - player.discoverRecipes(Recipes.SHIV.getKeys()); - player.discoverRecipes(Recipes.HAMMER.getKeys()); - player.discoverRecipes(Recipes.GLASS_BOTTLE.getKeys()); - player.discoverRecipes(Recipes.STICK.getKeys()); - player.discoverRecipes(Recipes.BREAD.getKeys()); - player.discoverRecipes(Recipes.STRING.getKeys()); - player.discoverRecipes(Recipes.WATER_BOTTLES.getKeys()); - } - player.discoverRecipe(NamespacedKey.minecraft("bowl")); - }, 200); - } - - // When a player picks up items, unlock different item based recipes - @EventHandler - private void onPickupItems(EntityPickupItemEvent e) { - if (this.UNLOCK_ALL) return; - if (!(e.getEntity() instanceof Player)) return; - Player player = ((Player) e.getEntity()); - Material item = e.getItem().getItemStack().getType(); - if (item == Material.DIAMOND) { - player.discoverRecipes(Recipes.DIAMOND_BOOTS.getKeys()); - player.discoverRecipes(Recipes.DIAMOND_CHESTPLATE.getKeys()); - player.discoverRecipes(Recipes.DIAMOND_LEGGINGS.getKeys()); - player.discoverRecipes(Recipes.DIAMOND_HELMET.getKeys()); - player.discoverRecipes(Recipes.DIAMOND_HORSE_ARMOR.getKeys()); - player.discoverRecipes(Recipes.VALKYRIES_AXE.getKeys()); - player.discoverRecipes(Recipes.QUARTZ_PICKAXE.getKeys()); - player.discoverRecipes(Recipes.ENDER_GIANT_BLADE.getKeys()); - player.discoverRecipes(Recipes.DIAMOND_SICKLE.getKeys()); - } else if (item == Material.FLINT) { - player.discoverRecipes(Recipes.FIRESTRIKER.getKeys()); - player.discoverRecipes(Recipes.GRAVEL.getKeys()); - player.discoverRecipes(Recipes.FLINT_SICKLE.getKeys()); - } else if (item == Material.FEATHER) { - player.discoverRecipes(Recipes.MEDIC_KIT.getKeys()); - player.discoverRecipes(Recipes.FISHING_ROD.getKeys()); - } else if (item == Material.BLAZE_POWDER || item == Material.BLAZE_ROD) { - player.discoverRecipes(Recipes.BLAZE_SWORD.getKeys()); - } else if (item == Material.LEATHER) { - player.discoverRecipes(Recipes.SADDLE.getKeys()); - player.discoverRecipes(Recipes.LEATHER_HORSE_ARMOR.getKeys()); - } else if (item == Material.GRAVEL) { - player.discoverRecipes(Recipes.FLINT.getKeys()); - } else if (item == Material.ROTTEN_FLESH) { - player.discoverRecipes(Recipes.FERMENTED_SKIN.getKeys()); - } else if (item == Material.STRING) { - player.discoverRecipes(Recipes.COBWEB.getKeys()); - player.discoverRecipes(Recipes.RECURVED_BOW.getKeys()); - } else if (item == Material.SPIDER_EYE) { - player.discoverRecipes(Recipes.FERMENTED_SPIDER_EYE.getKeys()); - } else if (item == Material.POTATO) { - player.discoverRecipes(Recipes.POISONOUS_POTATO.getKeys()); - } else if (item == Material.COBBLESTONE) { - player.discoverRecipes(Recipes.ANDESITE.getKeys()); - player.discoverRecipes(Recipes.DIORITE.getKeys()); - player.discoverRecipes(Recipes.GRANITE.getKeys()); - player.discoverRecipes(Recipes.STONE_SICKLE.getKeys()); - } else if (item == Material.QUARTZ) { - player.discoverRecipes(Recipes.QUARTZ.getKeys()); - } else if (item == Material.DIRT) { - player.discoverRecipes(Recipes.CLAY.getKeys()); - } else if (item == Material.EGG) { - player.discoverRecipes(Recipes.COOKIE.getKeys()); - } else if (ItemManager.compare(e.getItem().getItemStack(), Item.WATER_BOWL)) { - player.discoverRecipes(Recipes.BOWL.getKeys()); - } else if (item == Material.VINE) { - player.discoverRecipes(Recipes.SLIMEBALL.getKeys()); - } else if (item == Material.REDSTONE) { - player.discoverRecipes(Recipes.COMPASS.getKeys()); - } else if (item == Material.HONEYCOMB) { - player.discoverRecipes(Recipes.BEEKEEPER_SUIT.getKeys()); - } - } - - // When a player smelts items, unlock different item based recipes - @EventHandler - private void onFurnaceExtract(FurnaceExtractEvent event) { - if (this.UNLOCK_ALL) return; - Player player = event.getPlayer(); - if (event.getItemType() == Material.IRON_INGOT) { - player.discoverRecipes(Recipes.IRON_BOOTS.getKeys()); - player.discoverRecipes(Recipes.IRON_CHESTPLATE.getKeys()); - player.discoverRecipes(Recipes.IRON_HELMET.getKeys()); - player.discoverRecipes(Recipes.IRON_LEGGINGS.getKeys()); - player.discoverRecipes(Recipes.IRON_HORSE_ARMOR.getKeys()); - player.discoverRecipes(Recipes.IRON_INGOT.getKeys()); - player.discoverRecipes(Recipes.IRON_SICKLE.getKeys()); - player.discoverRecipes(Recipes.IRON_NUGGET.getKeys()); - } else if (event.getItemType() == Material.GOLD_INGOT) { - player.discoverRecipes(Recipes.GOLD_NUGGET.getKeys()); - player.discoverRecipes(Recipes.GOLD_INGOT.getKeys()); - player.discoverRecipes(Recipes.GOLD_CROWN.getKeys()); - player.discoverRecipes(Recipes.GOLD_GREAVES.getKeys()); - player.discoverRecipes(Recipes.GOLD_GUARD.getKeys()); - player.discoverRecipes(Recipes.GOLD_SABATONS.getKeys()); - player.discoverRecipes(Recipes.GOLD_HORSE_ARMOR.getKeys()); - player.discoverRecipes(Recipes.ENCHANTED_GOLDEN_APPLE.getKeys()); - } - } - - // When a player breaks a block, unlock different item based recipes - @EventHandler - private void onPlayerBreakBlock(BlockBreakEvent e) { - if (this.UNLOCK_ALL) return; - Player player = e.getPlayer(); - Material item = e.getBlock().getType(); - if (e.isCancelled()) return; - if (Tag.LOGS.isTagged(item)) { - player.discoverRecipes(Recipes.WORKBENCH.getKeys()); - player.discoverRecipe(NamespacedKey.minecraft("crafting_table")); //unlocks vanilla recipe if custom workbench recipe is set to false - player.discoverRecipes(Recipes.CHEST.getKeys()); - player.discoverRecipes(Recipes.UNLIT_CAMPFIRE.getKeys()); - } else if (item == Material.OBSIDIAN) { - player.discoverRecipes(Recipes.OBSIDIAN_MACE.getKeys()); - } else if (item == Material.ICE || item == Material.BLUE_ICE || item == Material.FROSTED_ICE || item == Material.PACKED_ICE) { - player.discoverRecipes(Recipes.ICE.getKeys()); - player.discoverRecipes(Recipes.PACKED_ICE.getKeys()); - } else if (item == Material.STONE) { - player.discoverRecipe(NamespacedKey.minecraft("furnace")); //unlocks vanilla recipe if custom furnace recipe is set to false - } - } - - // When a player crafts an item, unlock different item based recipes - @EventHandler - private void onCraft(CraftItemEvent e) { - if (this.UNLOCK_ALL) return; - if (!(e.getWhoClicked() instanceof Player)) return; - Player player = ((Player) e.getWhoClicked()); - ItemStack result = e.getRecipe().getResult(); - if (ItemManager.compare(result, Item.FIRESTRIKER)) { - player.discoverRecipes(Recipes.TORCH.getKeys()); - player.discoverRecipes(Recipes.FURNACE.getKeys()); - } else if (result.getType() == Material.FURNACE) { - player.discoverRecipes(Recipes.FURNACE_GOLD_INGOT.getKeys()); - player.discoverRecipes(Recipes.FURNACE_IRON_INGOT.getKeys()); - } else if (result.getType() == Material.BLAST_FURNACE) { - player.discoverRecipes(Recipes.BLAST_GOLD_INGOT.getKeys()); - player.discoverRecipes(Recipes.BLAST_IRON_INGOT.getKeys()); - } else if (result.getType() == Material.CROSSBOW) { - player.discoverRecipes(Recipes.RECURVED_CROSSBOW.getKeys()); - } else if (result.getType() == Material.LEATHER_HELMET || result.getType() == Material.LEATHER_CHESTPLATE - || result.getType() == Material.LEATHER_LEGGINGS || result.getType() == Material.LEATHER_BOOTS) { - player.discoverRecipes(Recipes.REINFORCED_LEATHER_HELMET.getKeys()); - player.discoverRecipes(Recipes.REINFORCED_LEATHER_CHESTPLATE.getKeys()); - player.discoverRecipes(Recipes.REINFORCED_LEATHER_LEGGINGS.getKeys()); - player.discoverRecipes(Recipes.REINFORCED_LEATHER_BOOTS.getKeys()); - } else if (result.getType() == Material.PAPER) { - player.discoverRecipes(Recipes.NAMETAG.getKeys()); - player.discoverRecipes(Recipes.MEDIC_KIT.getKeys()); - } else if (result.getType() == Material.STRING) { - player.discoverRecipes(Recipes.COBWEB.getKeys()); - player.discoverRecipes(Recipes.RECURVED_BOW.getKeys()); - } else if (result.getType() == Material.BRICK || result.getType() == Material.BRICKS) { - player.discoverRecipes(Recipes.CLAY_BRICK.getKeys()); - } else if (result.getType() == Material.FISHING_ROD) { - player.discoverRecipes(Recipes.GRAPPLING_HOOK.getKeys()); - } else if (result.getType() == Material.GLASS_BOTTLE) { - player.discoverRecipes(Recipes.COFFEE.getKeys()); - player.discoverRecipes(Recipes.COFFEE_BEAN.getKeys()); - player.discoverRecipes(Recipes.HOT_MILK.getKeys()); - player.discoverRecipes(Recipes.COLD_MILK.getKeys()); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/listeners/server/SetResourcePack.java b/src/main/java/tk/shanebee/survival/listeners/server/SetResourcePack.java deleted file mode 100644 index e1433c3..0000000 --- a/src/main/java/tk/shanebee/survival/listeners/server/SetResourcePack.java +++ /dev/null @@ -1,67 +0,0 @@ -package tk.shanebee.survival.listeners.server; - -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.PlayerQuitEvent; -import org.bukkit.event.player.PlayerResourcePackStatusEvent; -import org.bukkit.event.player.PlayerResourcePackStatusEvent.Status; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -public class SetResourcePack implements Listener { - - private Survival plugin; - private Config config; - private Lang lang; - private PlayerManager playerManager; - private String prefix; - - public SetResourcePack(Survival plugin) { - this.plugin = plugin; - this.config = plugin.getSurvivalConfig(); - this.lang = plugin.getLang(); - this.playerManager = plugin.getPlayerManager(); - this.prefix = lang.prefix; - } - - - - @EventHandler - private void onPlayerJoin(PlayerJoinEvent event) { - if (config.RESOURCE_PACK_ENABLED) - playerManager.applyResourcePack(event.getPlayer(), 20); - } - - /* Not sure why this was added, leaving here for now just in case its actually needed - @EventHandler - public void onPlayerChangedWorld(PlayerChangedWorldEvent event) { - if (resourcePack) - applyResourcePack(event.getPlayer()); - } - */ - - @EventHandler - private void onPlayerLeave(PlayerQuitEvent event) { - plugin.getUsingPlayers().remove(event.getPlayer()); - } - - @EventHandler - private void resourcePackEvent(PlayerResourcePackStatusEvent e) { - Player player = e.getPlayer(); - if (config.RESOURCE_PACK_ENABLED && config.RESOURCE_PACK_NOTIFY) - if (e.getStatus() == Status.DECLINED) { - Utils.sendColoredMsg(player, " "); - Utils.sendColoredMsg(player, prefix + "&c" + lang.resource_pack_declined); - Utils.sendColoredMsg(player, " &6" + lang.resource_pack_apply); - Utils.sendColoredMsg(player, " &6" + lang.resource_pack_required); - } else if (e.getStatus() == Status.ACCEPTED) { - Utils.sendColoredMsg(player, prefix + "&a" + lang.resource_pack_accepted); - } - } - -} \ No newline at end of file diff --git a/src/main/java/tk/shanebee/survival/managers/BlockManager.java b/src/main/java/tk/shanebee/survival/managers/BlockManager.java deleted file mode 100644 index 898449c..0000000 --- a/src/main/java/tk/shanebee/survival/managers/BlockManager.java +++ /dev/null @@ -1,186 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Lightable; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Objects; - -public class BlockManager { - - private final Survival plugin; - private FileConfiguration data; - private File data_file; - private final Lang lang; - - private final int seconds; - - public BlockManager(Survival plugin) { - this.plugin = plugin; - this.lang = plugin.getLang(); - this.seconds = plugin.getSurvivalConfig().MECHANICS_BURNOUT_TORCH_TIME; - loadDataFile(plugin.getServer().getConsoleSender()); - toBurnout(); - } - - /** Sets a torch to burn out after a preset time (in config) - * @param block The torch to burn out - */ - public void burnoutTorch(Block block) { - burnoutTorch(block, seconds); - } - - /** - * Sets a torch to burn out after x seconds - * - * @param seconds The time to wait for burnout in seconds - * @param block The torch to burn out - */ - @SuppressWarnings("WeakerAccess") - public void burnoutTorch(Block block, int seconds) { - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { - BlockData data = block.getBlockData(); - if (data.getMaterial() == Material.TORCH) - data = Material.REDSTONE_TORCH.createBlockData(); - else if (data.getMaterial() == Material.WALL_TORCH) { - BlockFace face = ((Directional) data).getFacing(); - data = Material.REDSTONE_WALL_TORCH.createBlockData(); - ((Directional) data).setFacing(face); - } else { - if (isNonPersistent(block)) - unsetNonPersistent(block); - return; - } - ((Lightable) data).setLit(false); - block.setBlockData(data); - }, 20 * seconds); - } - - private void loadDataFile(CommandSender sender) { - String loaded; - data_file = new File(plugin.getDataFolder(), "data.yml"); - if (!data_file.exists()) { - plugin.saveResource("data.yml", true); - loaded = "&aNew data.yml created"; - } else { - loaded = "&7data.yml &aloaded"; - } - data = YamlConfiguration.loadConfiguration(data_file); - Utils.sendColoredMsg(sender, lang.prefix + loaded); - } - - /** - * Adds a non persistent torch to the data.yml file - * - * @param block The torch to make non persistent - */ - public void setNonPersistent(Block block) { - List list = data.getStringList("NonPersistent Torches"); - long time = System.currentTimeMillis(); - time = time + (1000 * seconds); - list.add(locToString(block.getLocation()) + " time:" + time); - data.set("NonPersistent Torches", list); - try { - data.save(data_file); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Removes a non persistent torch from the data.yml file - * - * @param block The torch to remove as non persistent - */ - public void unsetNonPersistent(Block block) { - List list = data.getStringList("NonPersistent Torches"); - for (Object string : list.toArray()) { - if (stringMatchLoc(((String) string), block.getLocation())) { - list.remove(string); - } - } - data.set("NonPersistent Torches", list); - try { - data.save(data_file); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Checks if a torch is non persistent - * - * @param block The torch to check - * @return Whether its persistent or not - */ - public boolean isNonPersistent(Block block) { - return containsLoc(block.getLocation()); - } - - private String locToString(Location loc) { - assert loc.getWorld() != null; - return ("world:" + loc.getWorld().getName() + " x:" + loc.getX() + " y:" + loc.getY() + " z:" + loc.getZ()) - .replace(".0", ""); - } - - private boolean stringMatchLoc(String string, Location location) { - String[] loc = string.split(" "); - assert location.getWorld() != null; - String world = location.getWorld().getName(); - String x = String.valueOf(location.getX()).replace(".0", ""); - String y = String.valueOf(location.getY()).replace(".0", ""); - String z = String.valueOf(location.getZ()).replace(".0", ""); - if (loc[0].equalsIgnoreCase("world:" + world)) { - if (loc[1].equalsIgnoreCase("x:" + x)) { - if (loc[2].equalsIgnoreCase("y:" + y)) { - return loc[3].equalsIgnoreCase("z:" + z); - } - } - } - return false; - } - - private boolean containsLoc(Location loc) { - List list = data.getStringList("NonPersistent Torches"); - for (String torch : list) { - if (stringMatchLoc(torch, loc)) - return true; - } - return false; - } - - private void toBurnout() { - Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> { - List list = data.getStringList("NonPersistent Torches"); - for (String string : list) { - String[] loc = string.split(" "); - long time = Long.parseLong(loc[4].replace("time:", "")); - if (time < System.currentTimeMillis()) { - String world = loc[0].replace("world:", ""); - int x = Integer.parseInt(loc[1].replace("x:", "")); - int y = Integer.parseInt(loc[2].replace("y:", "")); - int z = Integer.parseInt(loc[3].replace("z:", "")); - Block block = Objects.requireNonNull(Bukkit.getServer().getWorld(world)).getBlockAt(x, y, z); - if (block.getType() == Material.TORCH || block.getType() == Material.WALL_TORCH) { - burnoutTorch(block, 20); - } - } - } - }, 20 * 60, 20 * 60); - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/EffectManager.java b/src/main/java/tk/shanebee/survival/managers/EffectManager.java deleted file mode 100644 index 053ab9e..0000000 --- a/src/main/java/tk/shanebee/survival/managers/EffectManager.java +++ /dev/null @@ -1,80 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.tasks.tool.*; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.util.Utils; - -public class EffectManager { - - private final Survival plugin; - private final Config config; - - // Effect Tasks - private BlazeSwordEffects blazeSwordEffects = null; - private BlazeSwordSound blazeSwordSound = null; - private GiantBlade giantBlade = null; - private ObsidianMace obsidianMace = null; - private QuartzPickaxe quartzPickaxe = null; - private Valkyrie valkyrie = null; - - public EffectManager(Survival plugin) { - this.plugin = plugin; - this.config = plugin.getSurvivalConfig(); - loadEffects(); - } - - private void loadEffects() { - if (config.LEGENDARY_BLAZESWORD) { - this.blazeSwordEffects = new BlazeSwordEffects(plugin); - this.blazeSwordSound = new BlazeSwordSound(plugin); - } - if (config.LEGENDARY_GIANTBLADE) - this.giantBlade = new GiantBlade(plugin); - if (config.LEGENDARY_OBSIDIAN_MACE) - this.obsidianMace = new ObsidianMace(plugin); - if (config.LEGENDARY_VALKYRIE) - this.valkyrie = new Valkyrie(plugin); - if (config.LEGENDARY_QUARTZPICKAXE) - this.quartzPickaxe = new QuartzPickaxe(plugin); - } - - /** - * Stop all effect tasks - */ - @SuppressWarnings("unused") - public void cancelTasks() { - if (blazeSwordEffects != null) - blazeSwordEffects.cancel(); - if (blazeSwordSound != null) - blazeSwordSound.cancel(); - if (giantBlade != null) - giantBlade.cancel(); - if (obsidianMace != null) - obsidianMace.cancel(); - if (quartzPickaxe != null) - quartzPickaxe.cancel(); - if (valkyrie != null) - valkyrie.cancel(); - } - - /** Apply obsidian mace effects to player and enemy - * @param player Player to apply Regeneration to - * @param enemy Enemy to apply weakness and slowness to - */ - public void applyObsidianMaceEffects(Player player, LivingEntity enemy) { - enemy.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, 100, 0, false)); - enemy.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 100, 0, false)); - player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 48, 2, true)); - Location particleLoc = player.getLocation(); - particleLoc.setY(particleLoc.getY() + 2); - Utils.spawnParticle(particleLoc, Particle.HEART, 2, 0.5, 0.5, 0.5); - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/ItemManager.java b/src/main/java/tk/shanebee/survival/managers/ItemManager.java deleted file mode 100644 index 0ff1521..0000000 --- a/src/main/java/tk/shanebee/survival/managers/ItemManager.java +++ /dev/null @@ -1,965 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.ChatColor; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Campfire; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BlockDataMeta; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.inventory.meta.SuspiciousStewMeta; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.UUID; - -/** - * Manager for custom SurvivalPlus items - */ -@SuppressWarnings("ConstantConditions") -public class ItemManager { - - private static final Lang lang = Survival.getInstance().getLang(); - - /** - * Get a custom SurvivalPlus item - * - * @param item The item you would like to get - * @return An ItemStack from a custom item enum - */ - public static ItemStack get(Item item) { - if (item == Item.HATCHET) { - ItemStack i_hatchet = new ItemStack(Item.HATCHET.getMaterialType(), 1); - ItemMeta hatchetMeta = i_hatchet.getItemMeta(); - hatchetMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.hatchet)); - hatchetMeta.setCustomModelData(Item.HATCHET.getModelData()); - i_hatchet.setItemMeta(hatchetMeta); - return i_hatchet; - } else if (item == Item.MATTOCK) { - ItemStack i_mattock = new ItemStack(Item.MATTOCK.getMaterialType(), 1); - ItemMeta mattockMeta = i_mattock.getItemMeta(); - mattockMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.mattock)); - mattockMeta.setCustomModelData(Item.MATTOCK.getModelData()); - i_mattock.setItemMeta(mattockMeta); - return i_mattock; - } else if (item == Item.SHIV) { - ItemStack i_shiv = new ItemStack(Item.SHIV.getMaterialType(), 1); - ItemMeta i_shivMeta = i_shiv.getItemMeta(); - i_shivMeta.setCustomModelData(Item.SHIV.getModelData()); - - int shiv_dmg = 4; - float shiv_spd = 1.8f; - - AttributeModifier i_shivDamage = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c56"), - "generic.attackDamage", shiv_dmg - 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_shivMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_DAMAGE, i_shivDamage); - - AttributeModifier i_shivSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c57"), - "generic.attackSpeed", shiv_spd - 4, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_shivMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, i_shivSpeed); - - i_shivMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - - i_shivMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.shiv)); - i_shivMeta.setLore(Arrays.asList( - ChatColor.RESET + Utils.getColoredString(lang.poisoned_enemy), - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_main_hand), - ChatColor.DARK_GREEN + " " + shiv_spd + " " + Utils.getColoredString(lang.attack_speed), - ChatColor.DARK_GREEN + " " + shiv_dmg + " " + Utils.getColoredString(lang.attack_damage), - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_off_hand), - ChatColor.GRAY + " " + Utils.getColoredString(lang.poisoned_retain), - ChatColor.GRAY + " " + Utils.getColoredString(lang.reduce_50) - ) - ); - i_shiv.setItemMeta(i_shivMeta); - return i_shiv; - } else if (item == Item.HAMMER) { - ItemStack i_hammer = new ItemStack(Item.HAMMER.getMaterialType(), 1); - ItemMeta hammerMeta = i_hammer.getItemMeta(); - hammerMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.hammer)); - hammerMeta.setCustomModelData(Item.HAMMER.getModelData()); - i_hammer.setItemMeta(hammerMeta); - return i_hammer; - } else if (item == Item.VALKYRIES_AXE) { - ItemStack i_gAxe = new ItemStack(Item.VALKYRIES_AXE.getMaterialType(), 1); - ItemMeta i_gAxeMeta = i_gAxe.getItemMeta(); - i_gAxeMeta.setCustomModelData(Item.VALKYRIES_AXE.getModelData()); - - int gAxe_spd = 1; - int gAxe_dmg = 8; - - AttributeModifier i_gAxeSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c58"), - "generic.attackSpeed", gAxe_spd - 4, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gAxeMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, i_gAxeSpeed); - - i_gAxeMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - - i_gAxeMeta.setDisplayName(ChatColor.RESET + "" + Utils.getColoredString(lang.valkyrie_axe)); - i_gAxeMeta.setLore(Arrays.asList( - ChatColor.RESET + Utils.getColoredString(lang.valkyrie_axe_unable_dual), - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_main_hand), - ChatColor.DARK_GREEN + " " + gAxe_spd + " " + Utils.getColoredString(lang.attack_speed), - ChatColor.DARK_GREEN + " " + gAxe_dmg + " " + Utils.getColoredString(lang.attack_damage), - ChatColor.RESET + Utils.getColoredString(lang.valkyrie_axe_spin), - ChatColor.RESET + " " + Utils.getColoredString(lang.valkyrie_axe_cooldown), - ChatColor.RESET + " " + Utils.getColoredString(lang.decrease_hunger_value) - ) - ); - i_gAxeMeta.addEnchant(Enchantment.DURABILITY, 5, true); - i_gAxe.setItemMeta(i_gAxeMeta); - return i_gAxe; - } else if (item == Item.QUARTZ_PICKAXE) { - ItemStack i_gPickaxe = new ItemStack(Item.QUARTZ_PICKAXE.getMaterialType(), 1); - ItemMeta i_gPickaxeMeta = i_gPickaxe.getItemMeta(); - i_gPickaxeMeta.setCustomModelData(Item.QUARTZ_PICKAXE.getModelData()); - - int gPickaxe_dmg = 5; - float gPickaxe_spd = 0.8f; - - AttributeModifier i_gPickDamage = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c59"), - "generic.attackDamage", gPickaxe_dmg - 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gPickaxeMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_DAMAGE, i_gPickDamage); - - AttributeModifier i_gPickSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c60"), - "generic.attackSpeed", gPickaxe_spd - 4, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gPickaxeMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, i_gPickSpeed); - - i_gPickaxeMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - - i_gPickaxeMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.quartz_breaker)); - i_gPickaxeMeta.setLore(Arrays.asList( - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_main_hand), - ChatColor.DARK_GREEN + " " + gPickaxe_spd + " " + Utils.getColoredString(lang.attack_speed), - ChatColor.DARK_GREEN + " " + gPickaxe_dmg + " " + Utils.getColoredString(lang.attack_damage), - ChatColor.GRAY + " " + Utils.getColoredString(lang.haste) - ) - ); - i_gPickaxeMeta.addEnchant(Enchantment.SILK_TOUCH, 1, false); - i_gPickaxeMeta.addEnchant(Enchantment.MENDING, 1, false); - i_gPickaxeMeta.addEnchant(Enchantment.BINDING_CURSE, 1, false); - i_gPickaxe.setItemMeta(i_gPickaxeMeta); - return i_gPickaxe; - } else if (item == Item.OBSIDIAN_MACE) { - ItemStack i_gSpade = new ItemStack(Item.OBSIDIAN_MACE.getMaterialType(), 1); - ItemMeta i_gSpadeMeta = i_gSpade.getItemMeta(); - i_gSpadeMeta.setCustomModelData(Item.OBSIDIAN_MACE.getModelData()); - - int gSpade_dmg = 4; - float gSpade_spd = 0.8f; - float gSpade_knockbackPercent = 0.5f; - - AttributeModifier i_gSpadeDamage = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c61"), - "generic.attackDamage", gSpade_dmg - 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gSpadeMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_DAMAGE, i_gSpadeDamage); - - AttributeModifier i_gSpadeSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c62"), - "generic.attackSpeed", gSpade_spd - 4, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gSpadeMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, i_gSpadeSpeed); - - AttributeModifier i_gSpadeKnock = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c63"), - "generic.knockbackResistance", gSpade_knockbackPercent, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HAND); - i_gSpadeMeta.addAttributeModifier(Attribute.GENERIC_KNOCKBACK_RESISTANCE, i_gSpadeKnock); - - i_gSpadeMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - - i_gSpadeMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.obsidian_mace)); - i_gSpadeMeta.setLore(Arrays.asList( - ChatColor.RESET + Utils.getColoredString(lang.cripple_hit), - ChatColor.RESET + Utils.getColoredString(lang.drain_hit), - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_main_hand), - ChatColor.DARK_GREEN + " " + gSpade_spd + " " + Utils.getColoredString(lang.attack_speed), - ChatColor.DARK_GREEN + " " + gSpade_dmg + " " + Utils.getColoredString(lang.attack_damage), - ChatColor.RESET + " " + Utils.getColoredString(lang.exhausted_slow), - ChatColor.RESET + " " + Utils.getColoredString(lang.expire_disarm), - ChatColor.RESET + " " + Utils.getColoredString(lang.knockback_resistance) - ) - ); - i_gSpadeMeta.addEnchant(Enchantment.KNOCKBACK, 3, true); - i_gSpadeMeta.addEnchant(Enchantment.DURABILITY, 5, true); - i_gSpadeMeta.addEnchant(Enchantment.BINDING_CURSE, 1, false); - i_gSpade.setItemMeta(i_gSpadeMeta); - return i_gSpade; - } else if (item == Item.ENDER_GIANT_BLADE) { - ItemStack i_gHoe = new ItemStack(Item.ENDER_GIANT_BLADE.getMaterialType(), 1); - ItemMeta i_gHoeMeta = i_gHoe.getItemMeta(); - i_gHoeMeta.setCustomModelData(Item.ENDER_GIANT_BLADE.getModelData()); - - int gHoe_dmg = 8; - int gHoe_spd = 1; - float gHoe_move = -0.5f; - - AttributeModifier i_gHoeDamage = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c64"), - "generic.attackDamage", gHoe_dmg - 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gHoeMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_DAMAGE, i_gHoeDamage); - - AttributeModifier i_gHoeSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c65"), - "generic.attackSpeed", gHoe_spd - 4, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gHoeMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, i_gHoeSpeed); - - AttributeModifier i_gHoeMove = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c66"), - "generic.movementSpeed", gHoe_move, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.OFF_HAND); - i_gHoeMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_gHoeMove); - - i_gHoeMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - - i_gHoeMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.ender_giant_blade)); - i_gHoeMeta.setLore(Arrays.asList( - ChatColor.RESET + Utils.getColoredString(lang.ender_giant_blade_unable_duel), - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_main_hand), - ChatColor.DARK_GREEN + " " + gHoe_spd + " " + Utils.getColoredString(lang.attack_speed), - ChatColor.DARK_GREEN + " " + gHoe_dmg + " " + Utils.getColoredString(lang.attack_damage), - ChatColor.GRAY + " " + Utils.getColoredString(lang.right_click_sprinting), - ChatColor.RESET + " " + Utils.getColoredString(lang.ender_giant_blade_charge), - ChatColor.RESET + " " + Utils.getColoredString(lang.ender_giant_blade_cooldown), - ChatColor.RESET + " " + Utils.getColoredString(lang.decrease_hunger_value), - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_off_hand), - ChatColor.RESET + " " + Utils.getColoredString(lang.half_shield_resistance), - ChatColor.RESET + " " + Utils.getColoredString(lang.reflecting_coming) - ) - ); - i_gHoeMeta.addEnchant(Enchantment.DURABILITY, 5, true); - i_gHoe.setItemMeta(i_gHoeMeta); - return i_gHoe; - } else if (item == Item.BLAZE_SWORD) { - ItemStack i_gSword = new ItemStack(Item.BLAZE_SWORD.getMaterialType(), 1); - ItemMeta i_gSwordMeta = i_gSword.getItemMeta(); - i_gSwordMeta.setCustomModelData(Item.BLAZE_SWORD.getModelData()); - - int gSword_dmg = 6; - float gSword_spd = 1.6f; - int gSword_health = -6; - - AttributeModifier i_gSwordDamage = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c67"), - "generic.attackDamage", gSword_dmg - 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gSwordMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_DAMAGE, i_gSwordDamage); - - AttributeModifier i_gSwordSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c68"), - "generic.attackSpeed", gSword_spd - 4, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gSwordMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, i_gSwordSpeed); - - AttributeModifier i_gSwordHealth = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c69"), - "generic.maxHealth", gSword_health, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - i_gSwordMeta.addAttributeModifier(Attribute.GENERIC_MAX_HEALTH, i_gSwordHealth); - - i_gSwordMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - - i_gSwordMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.blaze_sword)); - i_gSwordMeta.setLore(Arrays.asList( - "", - ChatColor.GRAY + Utils.getColoredString(lang.in_main_hand), - ChatColor.DARK_GREEN + " " + gSword_spd + " " + Utils.getColoredString(lang.attack_speed), - ChatColor.DARK_GREEN + " " + gSword_dmg + " " + Utils.getColoredString(lang.attack_damage), - ChatColor.RESET + " " + Utils.getColoredString(lang.blaze_sword_fire_resistance), - ChatColor.RESET + " " + Utils.getColoredString(lang.blaze_sword_fiery), - "", - ChatColor.GRAY + Utils.getColoredString(lang.right_click_sneaking), - ChatColor.RESET + " " + Utils.getColoredString(lang.blaze_sword_spread_fire), - ChatColor.RESET + " " + Utils.getColoredString(lang.blaze_sword_cost) - ) - ); - i_gSwordMeta.addEnchant(Enchantment.FIRE_ASPECT, 2, true); - i_gSwordMeta.addEnchant(Enchantment.DURABILITY, 3, false); - i_gSword.setItemMeta(i_gSwordMeta); - return i_gSword; - } else if (item == Item.WORKBENCH) { - ItemStack workbench = new ItemStack(Item.WORKBENCH.getMaterialType(), 1); - ItemMeta workbenchMeta = workbench.getItemMeta(); - workbenchMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.workbench)); - workbench.setItemMeta(workbenchMeta); - return workbench; - } else if (item == Item.FIRESTRIKER) { - ItemStack i_firestriker = new ItemStack(Item.FIRESTRIKER.getMaterialType(), 1); - ItemMeta i_firestrikerMeta = i_firestriker.getItemMeta(); - i_firestrikerMeta.setCustomModelData(Item.FIRESTRIKER.getModelData()); - - float firestriker_spd = 4f; - - AttributeModifier i_firestrikerSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c55"), - "generic.attackSpeed", - firestriker_spd - 4, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND); - - i_firestrikerMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, i_firestrikerSpeed); - i_firestrikerMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - i_firestrikerMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.firestriker)); - String lore = Utils.getColoredString(lang.firestriker_lore); - i_firestrikerMeta.setLore(Arrays.asList(lore.split("\\|\\|"))); - i_firestriker.setItemMeta(i_firestrikerMeta); - return i_firestriker; - } else if (item == Item.FERMENTED_SKIN) { - ItemStack i_fermentedSkin = new ItemStack(Item.FERMENTED_SKIN.getMaterialType(), 1); - ItemMeta fermentedSkinMeta = i_fermentedSkin.getItemMeta(); - fermentedSkinMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.fermented_skin)); - i_fermentedSkin.setItemMeta(fermentedSkinMeta); - return i_fermentedSkin; - } else if (item == Item.MEDIC_KIT) { - ItemStack i_medicKit = new ItemStack(Item.MEDIC_KIT.getMaterialType(), 1); - ItemMeta medicKitMeta = i_medicKit.getItemMeta(); - medicKitMeta.setCustomModelData(Item.MEDIC_KIT.getModelData()); - medicKitMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.medical_kit)); - i_medicKit.setItemMeta(medicKitMeta); - return i_medicKit; - } else if (item == Item.REINFORCED_LEATHER_BOOTS) { - ItemStack i_leatherBoots = new ItemStack(Item.REINFORCED_LEATHER_BOOTS.getMaterialType(), 1); - ItemMeta i_leatherBootsMeta = i_leatherBoots.getItemMeta(); - i_leatherBootsMeta.setCustomModelData(Item.REINFORCED_LEATHER_BOOTS.getModelData()); - - AttributeModifier i_leatherBootsArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c70"), - "generic.armor", 2, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.FEET); - i_leatherBootsMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_leatherBootsArmor); - - i_leatherBootsMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.reinforced_boots)); - - i_leatherBoots.setItemMeta(i_leatherBootsMeta); - return i_leatherBoots; - } else if (item == Item.REINFORCED_LEATHER_TUNIC) { - ItemStack i_leatherChestplate = new ItemStack(Item.REINFORCED_LEATHER_TUNIC.getMaterialType(), 1); - - ItemMeta leatherChestplateMeta = i_leatherChestplate.getItemMeta(); - leatherChestplateMeta.setCustomModelData(Item.REINFORCED_LEATHER_TUNIC.getModelData()); - leatherChestplateMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.reinforced_tunic)); - - i_leatherChestplate.setItemMeta(leatherChestplateMeta); - return i_leatherChestplate; - } else if (item == Item.REINFORCED_LEATHER_TROUSERS) { - ItemStack i_leatherLeggings = new ItemStack(Item.REINFORCED_LEATHER_TROUSERS.getMaterialType(), 1); - - ItemMeta leatherLeggingsMeta = i_leatherLeggings.getItemMeta(); - leatherLeggingsMeta.setCustomModelData(Item.REINFORCED_LEATHER_TROUSERS.getModelData()); - leatherLeggingsMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.reinforced_pants)); - - i_leatherLeggings.setItemMeta(leatherLeggingsMeta); - return i_leatherLeggings; - } else if (item == Item.REINFORCED_LEATHER_HELMET) { - //Reinforced Leather Helmet - ItemStack i_leatherHelmet = new ItemStack(Item.REINFORCED_LEATHER_HELMET.getMaterialType(), 1); - - ItemMeta leatherHelmetMeta = i_leatherHelmet.getItemMeta(); - leatherHelmetMeta.setCustomModelData(Item.REINFORCED_LEATHER_HELMET.getModelData()); - leatherHelmetMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.reinforced_hat)); - - i_leatherHelmet.setItemMeta(leatherHelmetMeta); - return i_leatherHelmet; - } else if (item == Item.GOLDEN_SABATONS) { - ItemStack i_goldBoots = new ItemStack(Item.GOLDEN_SABATONS.getMaterialType(), 1); - ItemMeta i_goldBootsMeta = i_goldBoots.getItemMeta(); - - AttributeModifier i_goldBootsArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c71"), - "generic.armor", 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.FEET); - i_goldBootsMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_goldBootsArmor); - - AttributeModifier i_goldBootsSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f088c71"), - "generic.movementSpeed", -0.0125, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.FEET); - i_goldBootsMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_goldBootsSpeed); - - i_goldBootsMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.golden_sabatons)); - i_goldBootsMeta.addEnchant(org.bukkit.enchantments.Enchantment.PROTECTION_FALL, 4, true); - - i_goldBoots.setItemMeta(i_goldBootsMeta); - return i_goldBoots; - } else if (item == Item.GOLDEN_GUARD) { - ItemStack i_goldChestplate = new ItemStack(Item.GOLDEN_GUARD.getMaterialType(), 1); - ItemMeta i_goldChestplateMeta = i_goldChestplate.getItemMeta(); - - AttributeModifier i_goldChestArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c72"), - "generic.armor", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.CHEST); - i_goldChestplateMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_goldChestArmor); - - AttributeModifier i_goldChestSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f088c72"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.CHEST); - i_goldChestplateMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_goldChestSpeed); - - i_goldChestplateMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.golden_guard)); - i_goldChestplateMeta.addEnchant(org.bukkit.enchantments.Enchantment.PROTECTION_EXPLOSIONS, 4, true); - - i_goldChestplate.setItemMeta(i_goldChestplateMeta); - return i_goldChestplate; - } else if (item == Item.GOLDEN_GREAVES) { - ItemStack i_goldLeggings = new ItemStack(Item.GOLDEN_GREAVES.getMaterialType(), 1); - ItemMeta i_goldLeggingsMeta = i_goldLeggings.getItemMeta(); - - AttributeModifier i_goldLeggingsArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c73"), - "generic.armor", 2, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.LEGS); - i_goldLeggingsMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_goldLeggingsArmor); - - AttributeModifier i_goldLeggingsSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f088c73"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.LEGS); - i_goldLeggingsMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_goldLeggingsSpeed); - - i_goldLeggingsMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.golden_greaves)); - i_goldLeggingsMeta.addEnchant(Enchantment.PROTECTION_EXPLOSIONS, 4, true); - - i_goldLeggings.setItemMeta(i_goldLeggingsMeta); - return i_goldLeggings; - } else if (item == Item.GOLDEN_CROWN) { - ItemStack i_goldHelmet = new ItemStack(Item.GOLDEN_CROWN.getMaterialType(), 1); - ItemMeta i_goldHelmetMeta = i_goldHelmet.getItemMeta(); - - AttributeModifier i_goldHelmetArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c74"), - "generic.armor", 1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - i_goldHelmetMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_goldHelmetArmor); - - AttributeModifier i_goldHelmetSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f088c74"), - "generic.movementSpeed", -0.0125, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HEAD); - i_goldHelmetMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_goldHelmetSpeed); - - i_goldHelmetMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.golden_crown)); - i_goldHelmetMeta.addEnchant(org.bukkit.enchantments.Enchantment.MENDING, 1, true); - - i_goldHelmet.setItemMeta(i_goldHelmetMeta); - return i_goldHelmet; - } else if (item == Item.IRON_BOOTS) { - ItemStack i_ironBoots = new ItemStack(Item.IRON_BOOTS.getMaterialType(), 1); - ItemMeta i_ironBootsMeta = i_ironBoots.getItemMeta(); - - AttributeModifier i_ironBootsArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c75"), - "generic.armor", 2, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.FEET); - i_ironBootsMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_ironBootsArmor); - AttributeModifier i_ironBootsSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c76"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.FEET); - i_ironBootsMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_ironBootsSpeed); - - i_ironBoots.setItemMeta(i_ironBootsMeta); - return i_ironBoots; - } else if (item == Item.IRON_CHESTPLATE) { - ItemStack i_ironChestplate = new ItemStack(Item.IRON_CHESTPLATE.getMaterialType(), 1); - ItemMeta i_ironChestplateMeta = i_ironChestplate.getItemMeta(); - - AttributeModifier i_ironChestMove = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c77"), - "generic.movementSpeed", -0.03, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.CHEST); - i_ironChestplateMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_ironChestMove); - - AttributeModifier i_ironChestArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c78"), - "generic.armor", 6, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.CHEST); - i_ironChestplateMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_ironChestArmor); - - i_ironChestplate.setItemMeta(i_ironChestplateMeta); - return i_ironChestplate; - } else if (item == Item.IRON_LEGGINGS) { - ItemStack i_ironLeggings = new ItemStack(Item.IRON_LEGGINGS.getMaterialType(), 1); - ItemMeta i_ironLeggingsMeta = i_ironLeggings.getItemMeta(); - - AttributeModifier i_ironLeggingsArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c79"), - "generic.armor", 5, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.LEGS); - i_ironLeggingsMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_ironLeggingsArmor); - - AttributeModifier i_ironLeggingsSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c80"), - "generic.movementSpeed", -0.03, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.LEGS); - i_ironLeggingsMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_ironLeggingsSpeed); - - i_ironLeggings.setItemMeta(i_ironLeggingsMeta); - return i_ironLeggings; - } else if (item == Item.IRON_HELMET) { - ItemStack i_ironHelmet = new ItemStack(Item.IRON_HELMET.getMaterialType(), 1); - ItemMeta i_ironHelmetMeta = i_ironHelmet.getItemMeta(); - - AttributeModifier i_ironHelmetArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c81"), - "generic.armor", 2, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - i_ironHelmetMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_ironHelmetArmor); - - AttributeModifier i_ironHelmetSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c82"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HEAD); - i_ironHelmetMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_ironHelmetSpeed); - - i_ironHelmet.setItemMeta(i_ironHelmetMeta); - return i_ironHelmet; - } else if (item == Item.DIAMOND_BOOTS) { - ItemStack i_diamondBoots = new ItemStack(Item.DIAMOND_BOOTS.getMaterialType(), 1); - ItemMeta i_diamondBootsMeta = i_diamondBoots.getItemMeta(); - - AttributeModifier i_diamondBootsArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c83"), - "generic.armor", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.FEET); - i_diamondBootsMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_diamondBootsArmor); - - AttributeModifier i_diamondBootsSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c84"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.FEET); - i_diamondBootsMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_diamondBootsSpeed); - - i_diamondBoots.setItemMeta(i_diamondBootsMeta); - return i_diamondBoots; - } else if (item == Item.DIAMOND_CHESTPLATE) { - ItemStack i_diamondChestplate = new ItemStack(Item.DIAMOND_CHESTPLATE.getMaterialType(), 1); - ItemMeta i_diamondChestplateMeta = i_diamondChestplate.getItemMeta(); - - AttributeModifier i_diamondChestArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c85"), - "generic.armor", 8, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.CHEST); - i_diamondChestplateMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_diamondChestArmor); - - AttributeModifier i_diamondChestSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c86"), - "generic.movementSpeed", -0.03, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.CHEST); - i_diamondChestplateMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_diamondChestSpeed); - - i_diamondChestplate.setItemMeta(i_diamondChestplateMeta); - return i_diamondChestplate; - } else if (item == Item.DIAMOND_LEGGINGS) { - ItemStack i_diamondLeggings = new ItemStack(Item.DIAMOND_LEGGINGS.getMaterialType(), 1); - ItemMeta i_diamondLeggingsMeta = i_diamondLeggings.getItemMeta(); - - AttributeModifier i_diamondLegArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c87"), - "generic.armor", 6, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.LEGS); - i_diamondLeggingsMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_diamondLegArmor); - - AttributeModifier i_diamondLegSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c88"), - "generic.movementSpeed", -0.03, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.LEGS); - i_diamondLeggingsMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_diamondLegSpeed); - - i_diamondLeggings.setItemMeta(i_diamondLeggingsMeta); - return i_diamondLeggings; - } else if (item == Item.DIAMOND_HELMET) { - ItemStack i_diamondHelmet = new ItemStack(Item.DIAMOND_HELMET.getMaterialType(), 1); - ItemMeta i_diamondHelmetMeta = i_diamondHelmet.getItemMeta(); - - AttributeModifier i_diamondHelmetArmor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c89"), - "generic.armor", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - i_diamondHelmetMeta.addAttributeModifier(Attribute.GENERIC_ARMOR, i_diamondHelmetArmor); - - AttributeModifier i_diamondHelmetSpeed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c90"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HEAD); - i_diamondHelmetMeta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, i_diamondHelmetSpeed); - - i_diamondHelmet.setItemMeta(i_diamondHelmetMeta); - return i_diamondHelmet; - } else if (item == Item.RECURVE_BOW) { - ItemStack i_recurveBow = new ItemStack(Item.RECURVE_BOW.getMaterialType(), 1); - - ItemMeta recurveBowMeta = i_recurveBow.getItemMeta(); - recurveBowMeta.setCustomModelData(Item.RECURVE_BOW.getModelData()); - recurveBowMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.recurved_bow)); - recurveBowMeta.setLore(Collections.singletonList(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + - Utils.getColoredString(lang.recurved))); - recurveBowMeta.addEnchant(Enchantment.ARROW_KNOCKBACK, 1, true); - i_recurveBow.setItemMeta(recurveBowMeta); - return i_recurveBow; - } else if (item == Item.RECURVE_CROSSBOW) { - ItemStack recurveCrossbow = new ItemStack(Item.RECURVE_CROSSBOW.getMaterialType(), 1); - ItemMeta recurveCrossbowMeta = recurveCrossbow.getItemMeta(); - recurveCrossbowMeta.setCustomModelData(Item.RECURVE_BOW.getModelData()); - recurveCrossbowMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.recurved_crossbow)); - recurveCrossbowMeta.setLore(Collections.singletonList(Utils.getColoredString(lang.recurved))); - recurveCrossbowMeta.addEnchant(Enchantment.ARROW_KNOCKBACK, 1, true); - recurveCrossbow.setItemMeta(recurveCrossbowMeta); - return recurveCrossbow; - } else if (item == Item.DIRTY_WATER) { - ItemStack dirty_water = new ItemStack(Item.CLEAN_WATER.getMaterialType()); - ItemMeta dirtyMeta = dirty_water.getItemMeta(); - dirtyMeta.setCustomModelData(Item.DIRTY_WATER.getModelData()); - ((PotionMeta) dirtyMeta).setBasePotionData(new PotionData(PotionType.WATER)); - ((PotionMeta) dirtyMeta).setColor(Color.fromRGB(lang.dirty_water_color)); - dirtyMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.dirty_water)); - dirtyMeta.setLore(Collections.singletonList(Utils.getColoredString(lang.dirty_water_lore))); - dirtyMeta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); - dirty_water.setItemMeta(dirtyMeta); - return dirty_water; - } else if (item == Item.CLEAN_WATER) { - ItemStack clean_water = new ItemStack(Item.CLEAN_WATER.getMaterialType()); - ItemMeta cleanMeta = clean_water.getItemMeta(); - cleanMeta.setCustomModelData(Item.CLEAN_WATER.getModelData()); - ((PotionMeta) cleanMeta).setBasePotionData(new PotionData(PotionType.WATER)); - ((PotionMeta) cleanMeta).setColor(Color.fromRGB(lang.clean_water_color)); - cleanMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.clean_water)); - cleanMeta.setLore(Collections.singletonList(Utils.getColoredString(lang.clean_water_lore))); - cleanMeta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); - clean_water.setItemMeta(cleanMeta); - return clean_water; - } else if (item == Item.PURIFIED_WATER) { - ItemStack purified_water = new ItemStack(Item.PURIFIED_WATER.getMaterialType()); - ItemMeta meta = purified_water.getItemMeta(); - meta.setCustomModelData(Item.PURIFIED_WATER.getModelData()); - ((PotionMeta) meta).setBasePotionData(new PotionData(PotionType.WATER)); - ((PotionMeta) meta).setColor(Color.fromRGB(lang.purified_water_color)); - meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.purified_water)); - meta.setLore(Collections.singletonList(Utils.getColoredString(lang.purified_water_lore))); - meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); - purified_water.setItemMeta(meta); - return purified_water; - } else if (item == Item.WATER_BOWL) { - ItemStack water_bowl = new ItemStack(Item.WATER_BOWL.getMaterialType()); - PotionMeta water_bowlMeta = ((PotionMeta) water_bowl.getItemMeta()); - water_bowlMeta.setBasePotionData(new PotionData(PotionType.WATER)); - water_bowlMeta.setCustomModelData(Item.WATER_BOWL.getModelData()); - water_bowlMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.water_bowl)); - water_bowl.setItemMeta(water_bowlMeta); - return water_bowl; - } else if (item == Item.CAMPFIRE) { - ItemStack campfire = new ItemStack(Item.CAMPFIRE.getMaterialType()); - ItemMeta campfireMeta = campfire.getItemMeta(); - campfireMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.campfire_name)); - campfireMeta.setLore(Arrays.asList(Utils.getColoredString(lang.campfire_lore).split("\\|\\|"))); - campfireMeta.setCustomModelData(Item.CAMPFIRE.getModelData()); - BlockData data = Material.CAMPFIRE.createBlockData(); - ((Campfire) data).setLit(false); - ((BlockDataMeta) campfireMeta).setBlockData(data); - campfire.setItemMeta(campfireMeta); - return campfire; - } else if (item == Item.STONE_SICKLE) { - ItemStack stone_sickle = new ItemStack(Item.STONE_SICKLE.getMaterialType()); - ItemMeta stone_sickleMeta = stone_sickle.getItemMeta(); - stone_sickleMeta.setCustomModelData(Item.STONE_SICKLE.getModelData()); - stone_sickleMeta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.stone_sickle)); - stone_sickle.setItemMeta(stone_sickleMeta); - return stone_sickle; - } else if (item == Item.IRON_SICKLE) { - ItemStack iron_sickle_new = new ItemStack(Item.IRON_SICKLE.getMaterialType()); - ItemMeta iron_sickle_new_meta = iron_sickle_new.getItemMeta(); - iron_sickle_new_meta.setCustomModelData(Item.IRON_SICKLE.getModelData()); - iron_sickle_new_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.iron_sickle)); - iron_sickle_new.setItemMeta(iron_sickle_new_meta); - return iron_sickle_new; - } else if (item == Item.FLINT_SICKLE) { - ItemStack flint_sickle = new ItemStack(Item.FLINT_SICKLE.getMaterialType()); - ItemMeta flint_sickle_meta = flint_sickle.getItemMeta(); - flint_sickle_meta.setCustomModelData(Item.FLINT_SICKLE.getModelData()); - flint_sickle_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.flint_sickle)); - flint_sickle.setItemMeta(flint_sickle_meta); - return flint_sickle; - } else if (item == Item.DIAMOND_SICKLE) { - ItemStack diamond_sickle = new ItemStack(Item.DIAMOND_SICKLE.getMaterialType()); - ItemMeta diamond_sickle_meta = diamond_sickle.getItemMeta(); - diamond_sickle_meta.setCustomModelData(Item.DIAMOND_SICKLE.getModelData()); - diamond_sickle_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.diamond_sickle)); - diamond_sickle.setItemMeta(diamond_sickle_meta); - return diamond_sickle; - } else if (item == Item.GRAPPLING_HOOK) { - ItemStack grappling_hook = new ItemStack(Item.GRAPPLING_HOOK.getMaterialType()); - ItemMeta grappling_meta = grappling_hook.getItemMeta(); - grappling_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.grappling_hook)); - grappling_meta.setCustomModelData(Item.GRAPPLING_HOOK.getModelData()); - grappling_hook.setItemMeta(grappling_meta); - return grappling_hook; - } else if (item == Item.COFFEE) { - ItemStack coffee = new ItemStack(Item.COFFEE.getMaterialType()); - ItemMeta coffee_meta = coffee.getItemMeta(); - coffee_meta.setCustomModelData(Item.COFFEE.getModelData()); - ((PotionMeta) coffee_meta).setBasePotionData(new PotionData(PotionType.WATER)); - ((PotionMeta) coffee_meta).setColor(Color.fromRGB(lang.coffee_color)); - coffee_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.coffee_name)); - coffee_meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); - coffee.setItemMeta(coffee_meta); - return coffee; - } else if (item == Item.HOT_MILK) { - ItemStack hot_milk = new ItemStack(Item.HOT_MILK.getMaterialType()); - ItemMeta hot_milk_meta = hot_milk.getItemMeta(); - hot_milk_meta.setCustomModelData(Item.HOT_MILK.getModelData()); - ((PotionMeta) hot_milk_meta).setBasePotionData(new PotionData(PotionType.WATER)); - ((PotionMeta) hot_milk_meta).setColor(Color.fromRGB(lang.hot_milk_color)); - hot_milk_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.hot_milk_name)); - hot_milk_meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); - hot_milk.setItemMeta(hot_milk_meta); - return hot_milk; - } else if (item == Item.COLD_MILK) { - ItemStack cold_milk = new ItemStack(Item.COLD_MILK.getMaterialType()); - ItemMeta cold_milk_meta = cold_milk.getItemMeta(); - cold_milk_meta.setCustomModelData(Item.COLD_MILK.getModelData()); - ((PotionMeta) cold_milk_meta).setBasePotionData(new PotionData(PotionType.WATER)); - ((PotionMeta) cold_milk_meta).setColor(Color.fromRGB(lang.cold_milk_color)); - cold_milk_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.cold_milk_name)); - cold_milk_meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); - cold_milk.setItemMeta(cold_milk_meta); - return cold_milk; - } else if (item == Item.COFFEE_BEAN) { - ItemStack coffee_bean = new ItemStack(Item.COFFEE_BEAN.getMaterialType()); - ItemMeta coffee_bean_meta = coffee_bean.getItemMeta(); - coffee_bean_meta.setCustomModelData(Item.COFFEE_BEAN.getModelData()); - coffee_bean_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.coffee_bean_name)); - coffee_bean.setItemMeta(coffee_bean_meta); - return coffee_bean; - } else if (item == Item.BREEDING_EGG) { - ItemStack breeding_egg = new ItemStack(Item.BREEDING_EGG.getMaterialType()); - ItemMeta breeding_egg_meta = breeding_egg.getItemMeta(); - breeding_egg_meta.setCustomModelData(Item.BREEDING_EGG.getModelData()); - breeding_egg_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.breeding_egg_name)); - breeding_egg.setItemMeta(breeding_egg_meta); - return breeding_egg; - } else if (item == Item.COMPASS) { - ItemStack compass = new ItemStack(Item.COMPASS.getMaterialType()); - ItemMeta compass_meta = compass.getItemMeta(); - List compass_lore = new ArrayList<>(); - for (int i = 0; i < lang.compass_lore.size(); i++) { - compass_lore.add(Utils.getColoredString(lang.compass_lore.get(i))); - } - compass_meta.setLore(compass_lore); - compass.setItemMeta(compass_meta); - return compass; - } else if (item == Item.PERSISTENT_TORCH) { - // TODO Experimental - ItemStack persistent_torch = new ItemStack(Item.PERSISTENT_TORCH.getMaterialType()); - ItemMeta p_torch_meta = persistent_torch.getItemMeta(); - p_torch_meta.setCustomModelData(Item.PERSISTENT_TORCH.getModelData()); - p_torch_meta.setLore(Collections.singletonList(ChatColor.AQUA + "Persistent")); - persistent_torch.setItemMeta(p_torch_meta); - return persistent_torch; - } else if (item == Item.BEEKEEPER_HELMET) { - ItemStack beeHelmet = new ItemStack(Item.BEEKEEPER_HELMET.getMaterialType()); - ItemMeta bhMeta = beeHelmet.getItemMeta(); - bhMeta.setCustomModelData(Item.BEEKEEPER_HELMET.getModelData()); - bhMeta.setDisplayName(Utils.getColoredString(lang.bee_helmet_name)); - bhMeta.setLore(Collections.singletonList(Utils.getColoredString(lang.bee_suit_lore))); - ((LeatherArmorMeta) bhMeta).setColor(Color.WHITE); - bhMeta.addItemFlags(ItemFlag.HIDE_DYE); - beeHelmet.setItemMeta(bhMeta); - return beeHelmet; - } else if (item == Item.BEEKEEPER_CHESTPLATE) { - ItemStack beeChest = new ItemStack(Item.BEEKEEPER_CHESTPLATE.getMaterialType()); - ItemMeta bcMeta = beeChest.getItemMeta(); - bcMeta.setCustomModelData(Item.BEEKEEPER_CHESTPLATE.getModelData()); - bcMeta.setDisplayName(Utils.getColoredString(lang.bee_chest_name)); - bcMeta.setLore(Collections.singletonList(Utils.getColoredString(lang.bee_suit_lore))); - ((LeatherArmorMeta) bcMeta).setColor(Color.WHITE); - bcMeta.addItemFlags(ItemFlag.HIDE_DYE); - beeChest.setItemMeta(bcMeta); - return beeChest; - } else if (item == Item.BEEKEEPER_LEGGINGS) { - ItemStack beeLegs = new ItemStack(Item.BEEKEEPER_LEGGINGS.getMaterialType()); - ItemMeta blMeta = beeLegs.getItemMeta(); - blMeta.setCustomModelData(Item.BEEKEEPER_LEGGINGS.getModelData()); - blMeta.setDisplayName(Utils.getColoredString(lang.bee_legs_name)); - blMeta.setLore(Collections.singletonList(Utils.getColoredString(lang.bee_suit_lore))); - ((LeatherArmorMeta) blMeta).setColor(Color.WHITE); - blMeta.addItemFlags(ItemFlag.HIDE_DYE); - beeLegs.setItemMeta(blMeta); - return beeLegs; - } else if (item == Item.BEEKEEPER_BOOTS) { - ItemStack beeBoots = new ItemStack(Item.BEEKEEPER_BOOTS.getMaterialType()); - ItemMeta bbMeta = beeBoots.getItemMeta(); - bbMeta.setCustomModelData(Item.BEEKEEPER_BOOTS.getModelData()); - bbMeta.setDisplayName(Utils.getColoredString(lang.bee_boots_name)); - bbMeta.setLore(Collections.singletonList(Utils.getColoredString(lang.bee_suit_lore))); - ((LeatherArmorMeta) bbMeta).setColor(Color.WHITE); - bbMeta.addItemFlags(ItemFlag.HIDE_DYE); - beeBoots.setItemMeta(bbMeta); - return beeBoots; - } else if (item == Item.SUSPICIOUS_MEAT) { - ItemStack suspicious_meat = new ItemStack(Item.SUSPICIOUS_MEAT.getMaterialType()); - SuspiciousStewMeta suspicious_meat_meta = ((SuspiciousStewMeta) suspicious_meat.getItemMeta()); - suspicious_meat_meta.setCustomModelData(Item.SUSPICIOUS_MEAT.getModelData()); - suspicious_meat_meta.addCustomEffect(getRandomPotionEffect(), false); - suspicious_meat_meta.setDisplayName(Utils.getColoredString(lang.suspicious_meat)); - suspicious_meat.setItemMeta(suspicious_meat_meta); - return suspicious_meat; - } else if (item == Item.NETHERITE_HELMET) { - ItemStack n_helmet = new ItemStack(Item.NETHERITE_HELMET.getMaterialType()); - ItemMeta n_h_meta = n_helmet.getItemMeta(); - - AttributeModifier n_h_armor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f086c91"), - "generic.armor", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_h_meta.addAttributeModifier(Attribute.GENERIC_ARMOR, n_h_armor); - - AttributeModifier n_h_tough = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f085c91"), - "generic.toughness", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_h_meta.addAttributeModifier(Attribute.GENERIC_ARMOR_TOUGHNESS, n_h_tough); - - AttributeModifier n_h_knock = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f084c91"), - "generic.knock", 0.1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_h_meta.addAttributeModifier(Attribute.GENERIC_KNOCKBACK_RESISTANCE, n_h_knock); - - AttributeModifier n_h_speed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c91"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HEAD); - n_h_meta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, n_h_speed); - - n_helmet.setItemMeta(n_h_meta); - return n_helmet; - } else if (item == Item.NETHERITE_CHESTPLATE) { - ItemStack n_chest = new ItemStack(Item.NETHERITE_CHESTPLATE.getMaterialType()); - ItemMeta n_c_meta = n_chest.getItemMeta(); - - AttributeModifier n_c_armor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f086c92"), - "generic.armor", 8, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_c_meta.addAttributeModifier(Attribute.GENERIC_ARMOR, n_c_armor); - - AttributeModifier n_c_tough = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f085c92"), - "generic.toughness", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_c_meta.addAttributeModifier(Attribute.GENERIC_ARMOR_TOUGHNESS, n_c_tough); - - AttributeModifier n_c_knock = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f084c92"), - "generic.knock", 0.1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_c_meta.addAttributeModifier(Attribute.GENERIC_KNOCKBACK_RESISTANCE, n_c_knock); - - AttributeModifier n_c_speed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c92"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HEAD); - n_c_meta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, n_c_speed); - - n_chest.setItemMeta(n_c_meta); - return n_chest; - } else if (item == Item.NETHERITE_LEGGINGS) { - ItemStack n_leg = new ItemStack(Item.NETHERITE_LEGGINGS.getMaterialType()); - ItemMeta n_l_meta = n_leg.getItemMeta(); - - AttributeModifier n_l_armor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f086c93"), - "generic.armor", 6, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_l_meta.addAttributeModifier(Attribute.GENERIC_ARMOR, n_l_armor); - - AttributeModifier n_l_tough = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f085c93"), - "generic.toughness", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_l_meta.addAttributeModifier(Attribute.GENERIC_ARMOR_TOUGHNESS, n_l_tough); - - AttributeModifier n_l_knock = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f084c93"), - "generic.knock", 0.1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_l_meta.addAttributeModifier(Attribute.GENERIC_KNOCKBACK_RESISTANCE, n_l_knock); - - AttributeModifier n_l_speed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c93"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HEAD); - n_l_meta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, n_l_speed); - - n_leg.setItemMeta(n_l_meta); - return n_leg; - } else if (item == Item.NETHERITE_BOOTS) { - ItemStack n_boot = new ItemStack(Item.NETHERITE_BOOTS.getMaterialType()); - ItemMeta n_b_meta = n_boot.getItemMeta(); - - AttributeModifier n_b_armor = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f086c94"), - "generic.armor", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_b_meta.addAttributeModifier(Attribute.GENERIC_ARMOR, n_b_armor); - - AttributeModifier n_b_tough = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f085c94"), - "generic.toughness", 3, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_b_meta.addAttributeModifier(Attribute.GENERIC_ARMOR_TOUGHNESS, n_b_tough); - - AttributeModifier n_b_knock = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f084c94"), - "generic.knock", 0.1, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HEAD); - n_b_meta.addAttributeModifier(Attribute.GENERIC_KNOCKBACK_RESISTANCE, n_b_knock); - - AttributeModifier n_b_speed = new AttributeModifier(UUID.fromString("95c4f950-1631-4cc4-9f67-f45d8f087c94"), - "generic.movementSpeed", -0.02, AttributeModifier.Operation.ADD_SCALAR, EquipmentSlot.HEAD); - n_b_meta.addAttributeModifier(Attribute.GENERIC_MOVEMENT_SPEED, n_b_speed); - - n_boot.setItemMeta(n_b_meta); - return n_boot; - } else if (item == Item.SNOW_BOOTS) { - ItemStack snow_boots = new ItemStack(Item.SNOW_BOOTS.getMaterialType()); - ItemMeta snow_boots_meta = snow_boots.getItemMeta(); - if (snow_boots_meta instanceof LeatherArmorMeta) { - ((LeatherArmorMeta) snow_boots_meta).setColor(Color.fromRGB(158, 201, 202)); - } - snow_boots_meta.setCustomModelData(Item.SNOW_BOOTS.getModelData()); - snow_boots_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.snow_boots_name)); - snow_boots_meta.setLore(Collections.singletonList(Utils.getColoredString(lang.snow_boots_lore))); - snow_boots.setItemMeta(snow_boots_meta); - - return snow_boots; - } else if (item == Item.RAIN_BOOTS) { - ItemStack rain_boots = new ItemStack(Item.RAIN_BOOTS.getMaterialType()); - ItemMeta rain_boots_meta = rain_boots.getItemMeta(); - if (rain_boots_meta instanceof LeatherArmorMeta) { - ((LeatherArmorMeta) rain_boots_meta).setColor(Color.fromRGB(214, 231, 3)); - } - rain_boots_meta.setCustomModelData(Item.RAIN_BOOTS.getModelData()); - rain_boots_meta.setDisplayName(ChatColor.RESET + Utils.getColoredString(lang.rain_boots_name)); - rain_boots_meta.setLore(Collections.singletonList(Utils.getColoredString(lang.rain_boots_lore))); - rain_boots.setItemMeta(rain_boots_meta); - - return rain_boots; - } else { - return new ItemStack(Material.AIR); - } - } - - /** - * Compare an ItemStack with a custom {@link Item} - *

- * NOTE: Will only compare a custom item's {@link Material} and CustomModelData tag - *

- * - * @param itemStack The ItemStack to check - * @param type The custom item enum to check - * @return Whether these two items match or not - */ - public static boolean compare(ItemStack itemStack, Item type) { - if (itemStack.getType() == type.getMaterialType()) { - if (itemStack.getItemMeta() != null && itemStack.getItemMeta().hasCustomModelData()) { - return itemStack.getItemMeta().getCustomModelData() == type.getModelData(); - } else { - return type.getModelData() == 0; - } - } - return false; - } - - /** - * Compare an ItemStack with several custom {@link Item} - * - * @param itemStack The ItemStack to check - * @param type The custom item enums to check - * @return Whether these items match or not - */ - public static boolean compare(ItemStack itemStack, Item... type) { - for (Item item : type) { - if (compare(itemStack, item)) { - return true; - } - } - return false; - } - - /** - * Apply the attributes from an {@link Item} to an existing ItemStack - * - * @param itemStack Current ItemStack to apply attributes to - * @param items Item to grab data from - */ - public static void applyAttribute(ItemStack itemStack, Item items) { - ItemStack from = items.getItem(); - ItemMeta metaTo = itemStack.getItemMeta(); - ItemMeta metaFrom = from.getItemMeta(); - Map enchants = metaTo.getEnchants(); - for (Enchantment enchantment : enchants.keySet()) { - metaFrom.addEnchant(enchantment, enchants.get(enchantment), true); - } - itemStack.setItemMeta(metaFrom); - } - - private static final List POTION_EFFECTS; - - static { - POTION_EFFECTS = new ArrayList<>(); - // BAD - POTION_EFFECTS.add(PotionEffectType.BAD_OMEN); - POTION_EFFECTS.add(PotionEffectType.CONFUSION); - POTION_EFFECTS.add(PotionEffectType.POISON); - POTION_EFFECTS.add(PotionEffectType.UNLUCK); - POTION_EFFECTS.add(PotionEffectType.HUNGER); - POTION_EFFECTS.add(PotionEffectType.HARM); - POTION_EFFECTS.add(PotionEffectType.SLOW); - // GOOD - POTION_EFFECTS.add(PotionEffectType.DOLPHINS_GRACE); - POTION_EFFECTS.add(PotionEffectType.ABSORPTION); - POTION_EFFECTS.add(PotionEffectType.FAST_DIGGING); - POTION_EFFECTS.add(PotionEffectType.LUCK); - POTION_EFFECTS.add(PotionEffectType.HEALTH_BOOST); - POTION_EFFECTS.add(PotionEffectType.REGENERATION); - POTION_EFFECTS.add(PotionEffectType.SPEED); - } - - private static PotionEffect getRandomPotionEffect() { - Random random = new Random(); - int randomEffect = random.nextInt(POTION_EFFECTS.size()); - int randomDuration = random.nextInt(200) + 200; - return new PotionEffect(POTION_EFFECTS.get(randomEffect), randomDuration, 0); - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/MerchantManager.java b/src/main/java/tk/shanebee/survival/managers/MerchantManager.java deleted file mode 100644 index 56f149e..0000000 --- a/src/main/java/tk/shanebee/survival/managers/MerchantManager.java +++ /dev/null @@ -1,139 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.Material; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.MerchantRecipe; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.item.Item; - -import java.util.HashMap; -import java.util.Map; - -/** - * Manager for Merchant Recipes - */ -public class MerchantManager { - - private final Config config; - - public MerchantManager(Survival plugin) { - this.config = plugin.getSurvivalConfig(); - } - - /** - * Update a merchants recipes - *

Replaces existing MerchantRecipes with ones that use custom {@link Item}

- * - * @param entity Merchant to update - */ - public void updateRecipes(Entity entity) { - if (entity instanceof Merchant) { - Merchant merchant = ((Merchant) entity); - - for (int i = 0; i < merchant.getRecipes().size(); i++) { - MerchantRecipe merchantRecipe = merchant.getRecipe(i); - Material result = merchantRecipe.getResult().getType(); - Recipe recipe = Recipe.getByMaterial(result); - if (recipe != null && canUpdate(result)) { - merchant.setRecipe(i, recipe.updateRecipe(merchantRecipe)); - } - } - } - } - - private boolean canUpdate(Material material) { - switch (material) { - case CHAINMAIL_HELMET: - case CHAINMAIL_CHESTPLATE: - case CHAINMAIL_LEGGINGS: - case CHAINMAIL_BOOTS: - return this.config.MECHANICS_REINFORCED_ARMOR; - case IRON_HELMET: - case IRON_CHESTPLATE: - case IRON_LEGGINGS: - case IRON_BOOTS: - case DIAMOND_HELMET: - case DIAMOND_CHESTPLATE: - case DIAMOND_LEGGINGS: - case DIAMOND_BOOTS: - return this.config.MECHANICS_SLOW_ARMOR; - case STONE_HOE: - return this.config.SURVIVAL_SICKLE_STONE; - case DIAMOND_HOE: - return this.config.SURVIVAL_SICKLE_DIAMOND; - } - return false; - } - - /** - * Merchant recipes overrides - *

These will take vanilla recipes and replace them with custom {@link Item}s

- */ - public enum Recipe { - IRON_HELMET(Material.IRON_HELMET, Item.IRON_HELMET), - IRON_CHESTPLATE(Material.IRON_CHESTPLATE, Item.IRON_CHESTPLATE), - IRON_LEGGINGS(Material.IRON_LEGGINGS, Item.IRON_LEGGINGS), - IRON_BOOTS(Material.IRON_BOOTS, Item.IRON_BOOTS), - DIAMOND_HELMET(Material.DIAMOND_HELMET, Item.DIAMOND_HELMET), - DIAMOND_CHESTPLATE(Material.DIAMOND_CHESTPLATE, Item.DIAMOND_CHESTPLATE), - DIAMOND_LEGGINGS(Material.DIAMOND_LEGGINGS, Item.DIAMOND_LEGGINGS), - DIAMOND_BOOTS(Material.DIAMOND_BOOTS, Item.DIAMOND_BOOTS), - REINFORCED_LEATHER_HELMET(Material.CHAINMAIL_HELMET, Item.REINFORCED_LEATHER_HELMET), - REINFORCED_LEATHER_TUNIC(Material.CHAINMAIL_CHESTPLATE, Item.REINFORCED_LEATHER_TUNIC), - REINFORCED_LEATHER_TROUSERS(Material.CHAINMAIL_LEGGINGS, Item.REINFORCED_LEATHER_TROUSERS), - REINFORCED_LEATHER_BOOTS(Material.CHAINMAIL_BOOTS, Item.REINFORCED_LEATHER_BOOTS), - STONE_SICKLE(Material.STONE_HOE, Item.STONE_SICKLE), - DIAMOND_SICKLE(Material.DIAMOND_HOE, Item.DIAMOND_SICKLE); - - private final Material material; - private final Item item; - private static final Map recipeByMaterialMap; - - static { - recipeByMaterialMap = new HashMap<>(); - for (Recipe recipe : values()) { - recipeByMaterialMap.put(recipe.material, recipe); - } - } - - Recipe(Material material, Item item) { - this.material = material; - this.item = item; - } - - /** - * Get an updated MerchantRecipe based on an existing MerchantRecipe - * - * @param oldRecipe Old MerchantRecipe to replace - * @return Updated MerchantRecipe using custom items - */ - public MerchantRecipe updateRecipe(MerchantRecipe oldRecipe) { - ItemStack old = oldRecipe.getResult().clone(); - - ItemManager.applyAttribute(old, this.item); - MerchantRecipe recipe = new MerchantRecipe(old, oldRecipe.getUses(), oldRecipe.getMaxUses(), - oldRecipe.hasExperienceReward(), oldRecipe.getVillagerExperience(), - oldRecipe.getPriceMultiplier()); - recipe.setIngredients(oldRecipe.getIngredients()); - return recipe; - } - - /** - * Get a Recipe by material - * - * @param material Material to get recipe from - * @return Recipe based on material - */ - public static Recipe getByMaterial(Material material) { - if (recipeByMaterialMap.containsKey(material)) { - return recipeByMaterialMap.get(material); - } - return null; - } - - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/Placeholders.java b/src/main/java/tk/shanebee/survival/managers/Placeholders.java deleted file mode 100644 index a43a8dc..0000000 --- a/src/main/java/tk/shanebee/survival/managers/Placeholders.java +++ /dev/null @@ -1,120 +0,0 @@ -package tk.shanebee.survival.managers; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.entity.Player; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.Nutrient; -import tk.shanebee.survival.data.PlayerData; - -@SuppressWarnings("unused") -public class Placeholders extends PlaceholderExpansion { - - private final Survival plugin; - private final PlayerManager playerManager; - - public Placeholders(Survival plugin) { - this.plugin = plugin; - this.playerManager = plugin.getPlayerManager(); - } - - @Override - public boolean persist() { - return true; - } - - @Override - public boolean canRegister() { - return true; - } - - @Override - public String getIdentifier() { - return "survivalplus"; - } - - @Override - public String getAuthor() { - return plugin.getDescription().getAuthors().toString(); - } - - @Override - public String getVersion() { - return plugin.getDescription().getVersion(); - } - - @Override - public String onPlaceholderRequest(Player p, String identifier) { - PlayerData playerData = playerManager.getPlayerData(p); - - // Shows player's health, kinda useless but here it is - if (identifier.equalsIgnoreCase("player_health")) { - return String.format("%.2f", p.getHealth()); - } - // Shows a player's total hunger (including saturation) - if (identifier.equalsIgnoreCase("player_hunger_total")) { - return String.valueOf(p.getFoodLevel() + p.getSaturation()); - } - // Shows player's hunger - if (identifier.equalsIgnoreCase("player_hunger")) { - return String.valueOf(p.getFoodLevel()); - } - // Shows player's saturation - if (identifier.equalsIgnoreCase("player_saturation")) { - return String.valueOf(p.getSaturation()); - } - // Shows player's hunger bar (hunger part) - if (identifier.equalsIgnoreCase("player_hunger_bar_1")) { - return playerManager.ShowHunger(p).get(1); - } - // Shows player's hunger bar (saturation part) - if (identifier.equalsIgnoreCase("player_hunger_bar_2")) { - return playerManager.ShowHunger(p).get(2); - } - // Shows player's thirst - if (identifier.equalsIgnoreCase("player_thirst")) { - return String.valueOf(playerData.getThirst()); - } - // Shows player's thirst bar (top part - first half out of 40) - if (identifier.equalsIgnoreCase("player_thirst_bar_1")) { - return playerManager.ShowThirst(p).get(1); - } - // Shows player's thirst bar (bottom part - second half out of 40) - if (identifier.equalsIgnoreCase("player_thirst_bar_2")) { - return playerManager.ShowThirst(p).get(2); - } - // Shows player's fatigue // Deprecated - if (identifier.equalsIgnoreCase("player_fatigue")) { - return "0"; // removed - } - // Shows player's energy level (as a number) - if (identifier.equalsIgnoreCase("player_energy")) { - return String.format("%.2f", playerData.getEnergy()); - } - // Shows player's energy level (as a colored bar) - if (identifier.equalsIgnoreCase("player_energy_bar")) { - return playerManager.showEnergy(p).get(1); - } - // Shows player's nutrients bars ( ) - if (identifier.equalsIgnoreCase("player_nutrients_carbs_bar")) { - return playerManager.ShowNutrients(p).get(0); - } - if (identifier.equalsIgnoreCase("player_nutrients_proteins_bar")) { - return playerManager.ShowNutrients(p).get(1); - } - if (identifier.equalsIgnoreCase("player_nutrients_salts_bar")) { - return playerManager.ShowNutrients(p).get(2); - } - // Shows player's nutrients (just the ) - if (identifier.equalsIgnoreCase("player_nutrients_carbs")) { - return String.valueOf(playerData.getNutrient(Nutrient.CARBS)); - } - if (identifier.equalsIgnoreCase("player_nutrients_proteins")) { - return String.valueOf(playerData.getNutrient(Nutrient.PROTEIN)); - } - if (identifier.equalsIgnoreCase("player_nutrients_salts")) { - return String.valueOf(playerData.getNutrient(Nutrient.SALTS)); - } - return null; - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/PlayerManager.java b/src/main/java/tk/shanebee/survival/managers/PlayerManager.java deleted file mode 100644 index f51a7c2..0000000 --- a/src/main/java/tk/shanebee/survival/managers/PlayerManager.java +++ /dev/null @@ -1,366 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.*; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.scoreboard.Scoreboard; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.config.PlayerDataConfig; -import tk.shanebee.survival.data.Nutrient; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.util.Utils; - -import java.util.*; - -/** - * Manager for players - *

Get an instance of this class from {@link Survival#getPlayerManager()}

- */ -public class PlayerManager implements Listener { - - private final String url; - private final Lang lang; - private final Survival plugin; - private final PlayerDataConfig playerDataConfig; - private final int THIRST; - private final int HUNGER; - private final double ENERGY; - private final int PROTEIN; - private final int CARBS; - private final int SALTS; - - // Store all the active PlayerData - private final Map playerDataMap; - - public PlayerManager(Survival plugin, Map playerDataMap) { - this.plugin = plugin; - this.playerDataMap = playerDataMap; - this.lang = plugin.getLang(); - this.url = plugin.getSurvivalConfig().RESOURCE_PACK_URL; - this.playerDataConfig = plugin.getPlayerDataConfig(); - Config config = plugin.getSurvivalConfig(); - THIRST = config.MECHANICS_THIRST_START_AMOUNT; - HUNGER = config.MECHANICS_HUNGER_START_AMOUNT; - ENERGY = config.MECHANICS_ENERGY_START; - PROTEIN = config.MECHANICS_FOOD_START_PROTEINS; - CARBS = config.MECHANICS_FOOD_START_CARBS; - SALTS = config.MECHANICS_FOOD_START_SALTS; - loadPlayerData(); - } - - /** - * Get PlayerData for a player - * - * @param player Player to get data for - * @return PlayerData for player - */ - public PlayerData getPlayerData(Player player) { - return playerDataMap.get(player.getUniqueId()); - } - - /** - * Get a collection of all PlayerData - * - * @return Collection of all PlayerData - */ - @SuppressWarnings("unused") - public Collection getAllPlayerData() { - return playerDataMap.values(); - } - - /** - * Create player data for a new player - * - * @param player Player to create data for - * @return Newly created player data - */ - public PlayerData createNewPlayerData(Player player) { - UUID uuid = player.getUniqueId(); - setHunger(player, HUNGER); - - PlayerData playerData = new PlayerData(uuid, THIRST, PROTEIN, CARBS, SALTS, ENERGY); - playerDataMap.put(uuid, playerData); - savePlayerData(playerData); - return playerData; - } - - private void setHunger(Player player, int value) { - value = Math.min(value, 40); - int hunger = Math.min(value, 20); - int saturation = value > 20 ? value - 20 : 0; - player.setFoodLevel(hunger); - player.setSaturation(saturation); - } - - /** - * Save PlayerData to file - * - * @param data PlayerData to save - */ - private void savePlayerData(PlayerData data) { - playerDataConfig.savePlayerDataToFile(data); - } - - /** - * Load PlayerData from file into map - * - * @param player Player to load data for - * @return Loaded player data - */ - public PlayerData loadPlayerData(Player player) { - PlayerData playerData = playerDataConfig.getPlayerDataFromFile(player); - playerDataMap.put(player.getUniqueId(), playerData); - return playerData; - } - - /** - * Save/Unload player data - *

This will mainly be used internally for when a player leaves the server, - * their data will be saved to file then removed from the PlayerData map

- * - * @param player Player to save/unload data for - */ - public void unloadPlayerData(Player player) { - PlayerData playerData = getPlayerData(player); - playerDataConfig.savePlayerDataToFile(playerData); - playerDataMap.remove(player.getUniqueId()); - } - - /** - * Set the waypoint of a player's compass to their location - * - * @param player The player to set a waypoint for - * @param particle If particles should show at the location a waypoint is set - */ - @SuppressWarnings("unused") - public void setWaypoint(Player player, boolean particle) { - setWaypoint(player, player.getLocation(), particle); - } - - /** - * Set the waypoint of a player's compass - * - * @param player The player to set a waypoint for - * @param location The location of the waypoint - * @param particle If the particles should show at the location a waypoint is set - */ - public void setWaypoint(Player player, Location location, boolean particle) { - PlayerData playerData = getPlayerData(player); - playerData.setCompassWaypoint(location); - if (particle) - Utils.spawnParticle(location, Particle.CLOUD, 25, 0.5, 0.5, 0.5, player); - savePlayerData(playerData); - } - - /** - * Apply SurvivalPlus' resource pack to a player - * - * @param player The player to apply the resource pack to - * @param delay A delay in ticks - */ - public void applyResourcePack(Player player, int delay) { - if (url != null) { - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { - try { - player.setResourcePack(url); - } catch (Exception e) { - Bukkit.getConsoleSender().sendMessage("ResourcePackURL is null or URL is too long! Plugin disabled."); - Bukkit.getPluginManager().disablePlugin(plugin); - return; - } - plugin.getUsingPlayers().add(player); - }, delay); - } - } - - public Location lookAt(Location loc, Location lookat) { - //Clone the loc to prevent applied changes to the input loc - loc = loc.clone(); - - // Values of change in distance (make it relative) - double dx = lookat.getX() - loc.getX(); - double dy = lookat.getY() - loc.getY(); - double dz = lookat.getZ() - loc.getZ(); - - // Set yaw - if (dx != 0) { - // Set yaw start value based on dx - if (dx < 0) - loc.setYaw((float) (1.5 * Math.PI)); - else - loc.setYaw((float) (0.5 * Math.PI)); - - loc.setYaw(loc.getYaw() - (float) Math.atan(dz / dx)); - } else if (dz < 0) - loc.setYaw((float) Math.PI); - - // Get the distance from dx/dz - double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)); - - // Set pitch - loc.setPitch((float) -Math.atan(dy / dxz)); - - // Set values, convert to degrees (invert the yaw since Bukkit uses a different yaw dimension format) - loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI); - loc.setPitch(loc.getPitch() * 180f / (float) Math.PI); - - return loc; - } - - public List ShowThirst(Player player) { - StringBuilder thirstBar = new StringBuilder(); - PlayerData data = getPlayerData(player); - int thirst = data.getThirst(); - - for (int i = 0; i < thirst; i++) { - thirstBar.append("|"); - } - for (int i = thirst; i < 20; i++) { - thirstBar.append("."); - } - - if (thirst >= 40) - thirstBar.insert(0, ChatColor.GREEN); - else if (thirst <= 6) - thirstBar.insert(0, ChatColor.RED); - else - thirstBar.insert(0, ChatColor.AQUA); - - return Arrays.asList(ChatColor.AQUA + lang.thirst, (thirstBar.length() <= 22 ? thirstBar.toString() : thirstBar.substring(0, 22)), - thirstBar.substring(0, 2) + (thirstBar.length() > 22 ? thirstBar.substring(22) : "") + ChatColor.RESET + ChatColor.RESET); - } - - public List ShowHunger(Player player) { - int hunger = player.getFoodLevel(); - int saturation = Math.round(player.getSaturation()); - StringBuilder hungerBar = new StringBuilder(); - StringBuilder saturationBar = new StringBuilder(ChatColor.YELLOW + ""); - for (int i = 0; i < hunger; i++) { - hungerBar.append("|"); - } - for (int i = hunger; i < 20; i++) { - hungerBar.append("."); - } - for (int i = 0; i < saturation; i++) { - saturationBar.append("|"); - } - - if (hunger >= 20) - hungerBar.insert(0, ChatColor.GREEN); - else if (hunger <= 6) - hungerBar.insert(0, ChatColor.RED); - else - hungerBar.insert(0, ChatColor.GOLD); - - return Arrays.asList(ChatColor.GOLD + lang.hunger, hungerBar.toString() + ChatColor.RESET, saturationBar.toString()); - } - - public List ShowNutrients(Player player) { - List nutrients = new ArrayList<>(); - PlayerData data = getPlayerData(player); - - int carbon = data.getNutrient(Nutrient.CARBS); - int protein = data.getNutrient(Nutrient.PROTEIN); - int salts = data.getNutrient(Nutrient.SALTS); - - String showCarbon = Integer.toString(carbon); - if (carbon >= 480) - showCarbon = ChatColor.GREEN + showCarbon; - else - showCarbon = ChatColor.RED + showCarbon; - nutrients.add(showCarbon + " " + ChatColor.DARK_GREEN + lang.carbohydrates); - - String showProtein = Integer.toString(protein); - if (protein >= 120) - showProtein = ChatColor.GREEN + showProtein; - else - showProtein = ChatColor.RED + showProtein; - nutrients.add(showProtein + " " + ChatColor.DARK_RED + lang.protein); - - String showSalts = Integer.toString(salts); - if (salts >= 180) - showSalts = ChatColor.GREEN + showSalts; - else - showSalts = ChatColor.RED + showSalts; - nutrients.add(showSalts + " " + ChatColor.BLUE + lang.vitamins); - - return nutrients; - } - - public List showEnergy(Player player) { - PlayerData playerData = getPlayerData(player); - double energy = Math.floor(playerData.getEnergy()); - StringBuilder energyBar = new StringBuilder(); - for (int i = 0; i < energy; i++) { - energyBar.append("|"); - } - for (int i = ((int) energy); i < 20; i++) { - energyBar.append("."); - } - if (energy >= 16) { - energyBar.insert(0, ChatColor.GREEN); - } else if (energy <= 3) { - energyBar.insert(0, ChatColor.RED); - } else { - energyBar.insert(0, ChatColor.GOLD); - } - return Arrays.asList(Utils.getColoredString(lang.energy), energyBar.toString()); - } - - /** - * Check if player is holding arrows in their offhand - * - * @param player The player to check - * @return Whether or not the player has arrows in their offhand - */ - public boolean isArrowOffHand(Player player) { - Material mainHand = player.getInventory().getItemInMainHand().getType(); - Material offHand = player.getInventory().getItemInOffHand().getType(); - if (mainHand == Material.CROSSBOW) - return offHand == Material.ARROW || offHand == Material.SPECTRAL_ARROW - || offHand == Material.TIPPED_ARROW || offHand == Material.FIREWORK_ROCKET; - return offHand == Material.ARROW || offHand == Material.SPECTRAL_ARROW || offHand == Material.TIPPED_ARROW; - } - - @SuppressWarnings("ConstantConditions") - private void loadPlayerData() { - OfflinePlayer[] players = Bukkit.getOfflinePlayers(); - Scoreboard scoreboard = plugin.getMainBoard(); - - // Convert previous player data - if (playerDataConfig.needsConversion()) { - int c = 0; - if (scoreboard.getObjective("Thirst") != null) { - Utils.log("&bConverting player data!"); - long time = System.currentTimeMillis(); - - for (OfflinePlayer player : players) { - UUID uuid = player.getUniqueId(); - assert player.getName() != null; - int thirst = scoreboard.getObjective("Thirst").getScore(player.getName()).getScore(); - int proteins = scoreboard.getObjective("Protein").getScore(player.getName()).getScore(); - int carbs = scoreboard.getObjective("Carbs").getScore(player.getName()).getScore(); - int salts = scoreboard.getObjective("Salts").getScore(player.getName()).getScore(); - - boolean s_hunger = scoreboard.getObjective("BoardHunger").getScore(player.getName()).getScore() == 0; - boolean s_thirst = scoreboard.getObjective("BoardThirst").getScore(player.getName()).getScore() == 0; - boolean s_energy = scoreboard.getObjective("BoardEnergy").getScore(player.getName()).getScore() == 0; - boolean s_nutrients = scoreboard.getObjective("BoardNutrients").getScore(player.getName()).getScore() == 0; - - if (thirst > 0 || proteins > 0 || carbs > 0 || salts > 0) { - PlayerData data = new PlayerData(uuid, thirst, proteins, carbs, salts, 20.0); - data.setInfoDisplayed(s_hunger, s_thirst, s_energy, s_nutrients); - savePlayerData(data); - c++; - } - } - Utils.log("Converted players: &b" + c); - Utils.log("&aPlayer data conversion completed in " + (System.currentTimeMillis() - time) + " milliseconds!"); - } - playerDataConfig.createConvertedFile(c); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/RecipeManager.java b/src/main/java/tk/shanebee/survival/managers/RecipeManager.java deleted file mode 100644 index 34666ca..0000000 --- a/src/main/java/tk/shanebee/survival/managers/RecipeManager.java +++ /dev/null @@ -1,1185 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.Server; -import org.bukkit.Tag; -import org.bukkit.entity.Player; -import org.bukkit.inventory.BlastingRecipe; -import org.bukkit.inventory.CampfireRecipe; -import org.bukkit.inventory.FurnaceRecipe; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; -import org.bukkit.inventory.RecipeChoice.ExactChoice; -import org.bukkit.inventory.ShapedRecipe; -import org.bukkit.inventory.ShapelessRecipe; -import org.bukkit.inventory.SmokingRecipe; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.util.Utils; - -import java.util.ArrayList; -import java.util.Collection; - -public class RecipeManager { - - private final Config config; - private final Survival plugin; - - public RecipeManager(Survival plugin) { - this.plugin = plugin; - this.config = plugin.getSurvivalConfig(); - } - - /** - * Load all custom server recipes - */ - @SuppressWarnings("deprecation") - public void loadCustomRecipes() { - removeRecipes(); - Server server = plugin.getServer(); - - // HATCHET RECIPE - ShapedRecipe hatchet1 = new ShapedRecipe(new NamespacedKey(plugin, "hatchet1"), ItemManager.get(Item.HATCHET)); - ShapedRecipe hatchet2 = new ShapedRecipe(new NamespacedKey(plugin, "hatchet2"), ItemManager.get(Item.HATCHET)); - - hatchet1.shape("@@", " 1"); - - hatchet1.setIngredient('@', Material.FLINT); - hatchet1.setIngredient('1', Material.STICK); - hatchet1.setGroup("HATCHET"); - - hatchet2.shape("@@", "1 "); - - hatchet2.setIngredient('@', Material.FLINT); - hatchet2.setIngredient('1', Material.STICK); - hatchet2.setGroup("HATCHET"); - - - // MATTOCK RECIPE - ShapedRecipe mattock = new ShapedRecipe(new NamespacedKey(plugin, "mattock"), ItemManager.get(Item.MATTOCK)); - - mattock.shape("@-", "1@"); - mattock.setIngredient('@', Material.FLINT); - mattock.setIngredient('-', new RecipeChoice.MaterialChoice(Tag.PLANKS)); - mattock.setIngredient('1', Material.STICK); - - - // SHIV RECIPE - ShapedRecipe shiv = new ShapedRecipe(new NamespacedKey(plugin, "shiv"), ItemManager.get(Item.SHIV)); - - shiv.shape("*@", "1&"); - - shiv.setIngredient('@', Material.FLINT); - shiv.setIngredient('1', Material.STICK); - shiv.setIngredient('*', Material.STRING); - shiv.setIngredient('&', Material.SPIDER_EYE); - - - // HAMMER RECIPE - ShapedRecipe hammer = new ShapedRecipe(new NamespacedKey(plugin, "hammer"), ItemManager.get(Item.HAMMER)); - - hammer.shape("@ ", "1@"); - - hammer.setIngredient('@', Material.COBBLESTONE); - hammer.setIngredient('1', Material.STICK); - - - // VALKYRIE's AXE RECIPE - ShapedRecipe valkyries_axe = new ShapedRecipe(new NamespacedKey(plugin, "valkyrie_axe"), ItemManager.get(Item.VALKYRIES_AXE)); - - valkyries_axe.shape("@@@", "@*@", " 1 "); - - valkyries_axe.setIngredient('@', Material.DIAMOND); - valkyries_axe.setIngredient('*', Material.NETHER_STAR); - valkyries_axe.setIngredient('1', Material.STICK); - - - // QUARTZ PICKAXE RECIPE - ShapedRecipe quartz_pickaxe = new ShapedRecipe(new NamespacedKey(plugin, "quartz_pickaxe"), ItemManager.get(Item.QUARTZ_PICKAXE)); - quartz_pickaxe.shape("@B-", "B# ", "- 1"); - - quartz_pickaxe.setIngredient('@', Material.QUARTZ_BLOCK); - quartz_pickaxe.setIngredient('-', Material.DIAMOND); - quartz_pickaxe.setIngredient('B', Material.DIAMOND_BLOCK); - quartz_pickaxe.setIngredient('1', Material.STICK); - quartz_pickaxe.setIngredient('#', Material.DRAGON_EGG); - - - // OBSIDIAN MACE RECIPE - ShapedRecipe obsidian_mace = new ShapedRecipe(new NamespacedKey(plugin, "obsidian_mace"), ItemManager.get(Item.OBSIDIAN_MACE)); - - obsidian_mace.shape(" @@", " &@", "1 "); - - obsidian_mace.setIngredient('@', Material.OBSIDIAN); - obsidian_mace.setIngredient('&', Material.END_CRYSTAL); - obsidian_mace.setIngredient('1', Material.STICK); - - - // ENDER GIANT BLADE RECIPE - ShapedRecipe ender_giant_blade = new ShapedRecipe(new NamespacedKey(plugin, "ender_giant_blade"), ItemManager.get(Item.ENDER_GIANT_BLADE)); - - ender_giant_blade.shape(" @@", "B*@", "1B "); - - ender_giant_blade.setIngredient('*', Material.ENDER_EYE); - ender_giant_blade.setIngredient('@', Material.DIAMOND); - ender_giant_blade.setIngredient('B', Material.DIAMOND_BLOCK); - ender_giant_blade.setIngredient('1', new RecipeChoice.MaterialChoice(Tag.PLANKS)); - - - // BLAZE SWORD RECIPE - ShapedRecipe blaze_sword = new ShapedRecipe(new NamespacedKey(plugin, "blaze_sword"), ItemManager.get(Item.BLAZE_SWORD)); - blaze_sword.shape("*@*", "*@*", "*1*"); - - blaze_sword.setIngredient('@', Material.GOLD_INGOT); - blaze_sword.setIngredient('1', Material.BLAZE_ROD); - blaze_sword.setIngredient('*', Material.BLAZE_POWDER); - - - // NOTCH APPLE RECIPE - ShapedRecipe notchApple = new ShapedRecipe(new NamespacedKey(plugin, "enchanted_golden_apple"), new ItemStack(Material.ENCHANTED_GOLDEN_APPLE, 1)); - notchApple.shape("@@@", "@*@", "@@@"); - - notchApple.setIngredient('@', Material.GOLD_BLOCK); - notchApple.setIngredient('*', Material.APPLE); - - - // SADDLE RECIPE - ShapedRecipe saddle = new ShapedRecipe(new NamespacedKey(plugin, "saddle"), new ItemStack(Material.SADDLE, 1)); - - saddle.shape("@@@", "*-*", "= ="); - - saddle.setIngredient('@', Material.LEATHER); - saddle.setIngredient('*', Material.LEAD); - saddle.setIngredient('-', Material.IRON_INGOT); - saddle.setIngredient('=', Material.IRON_NUGGET); - - - // NAMETAG RECIPE - ShapedRecipe nametag = new ShapedRecipe(new NamespacedKey(plugin, "nametag"), new ItemStack(Material.NAME_TAG, 1)); - - nametag.shape(" -@", " *-", "* "); - - nametag.setIngredient('@', Material.STRING); - nametag.setIngredient('-', Material.IRON_INGOT); - nametag.setIngredient('*', Material.PAPER); - - - // PACKED ICE RECIPE - ShapedRecipe packedIce1 = new ShapedRecipe(new NamespacedKey(plugin, "packed_ice"), new ItemStack(Material.PACKED_ICE, 1)); - - packedIce1.shape("@@ ", "@@ "); - packedIce1.setIngredient('@', Material.ICE); - - - // ICE RECIPE - ShapedRecipe ice = new ShapedRecipe(new NamespacedKey(plugin, "ice1"), new ItemStack(Material.ICE, 1)); - ShapelessRecipe ice2 = new ShapelessRecipe(new NamespacedKey(plugin, "ice2"), new ItemStack(Material.ICE, 4)); - - ice.shape("@@@", "@*@", "@@@"); - - ice.setIngredient('@', Material.SNOWBALL); - ice.setIngredient('*', Material.WATER_BUCKET); - - ice2.addIngredient(Material.PACKED_ICE); - - - // IRON HORSE ARMOR RECIPE - ShapedRecipe iron_horse_armor = new ShapedRecipe(new NamespacedKey(plugin, "iron_horse_armor"), new ItemStack(Material.IRON_HORSE_ARMOR, 1)); - - iron_horse_armor.shape(" @", "#-#", "= ="); - - iron_horse_armor.setIngredient('#', Material.IRON_BLOCK); - iron_horse_armor.setIngredient('@', Material.IRON_INGOT); - iron_horse_armor.setIngredient('-', Material.LEATHER_HORSE_ARMOR); - iron_horse_armor.setIngredient('=', Material.IRON_NUGGET); - - - // GOLD HORSE ARMOR RECIPE - ShapedRecipe goldHorse1 = new ShapedRecipe(new NamespacedKey(plugin, "gold_horse_armor"), new ItemStack(Material.GOLDEN_HORSE_ARMOR, 1)); - - goldHorse1.shape(" @", "#-#", "= ="); - - goldHorse1.setIngredient('#', Material.GOLD_BLOCK); - goldHorse1.setIngredient('@', Material.GOLD_INGOT); - goldHorse1.setIngredient('-', Material.LEATHER_HORSE_ARMOR); - goldHorse1.setIngredient('=', Material.GOLD_NUGGET); - - - // DIAMOND HORSE ARMOR RECIPE - ShapedRecipe diamond_horse_armor = new ShapedRecipe(new NamespacedKey(plugin, "diamond_horse_armor"), new ItemStack(Material.DIAMOND_HORSE_ARMOR, 1)); - - diamond_horse_armor.shape(" H", "@-@", "B B"); - - diamond_horse_armor.setIngredient('@', Material.DIAMOND); - diamond_horse_armor.setIngredient('-', Material.IRON_HORSE_ARMOR); - diamond_horse_armor.setIngredient('H', Material.DIAMOND_HELMET); - diamond_horse_armor.setIngredient('B', Material.DIAMOND_BOOTS); - - - // LEATHER HORSE ARMOR RECIPE - ShapedRecipe leather_horse_armor = new ShapedRecipe(new NamespacedKey(plugin, "leather_horse_armor"), new ItemStack(Material.LEATHER_HORSE_ARMOR, 1)); - - leather_horse_armor.shape(" C", "ABA", "A A"); - - leather_horse_armor.setIngredient('A', Material.LEATHER); - leather_horse_armor.setIngredient('B', Material.SADDLE); - leather_horse_armor.setIngredient('C', Material.LEATHER_HELMET); - - - // CLAY BRICK RECIPE - ShapelessRecipe clayBrick = new ShapelessRecipe(new NamespacedKey(plugin, "clay_brick"), new ItemStack(Material.BRICK, 4)); - - clayBrick.addIngredient(Material.BRICKS); - - - // QUARTZ BLOCK RECIPE - ShapelessRecipe quartz = new ShapelessRecipe(new NamespacedKey(plugin, "quartz"), new ItemStack(Material.QUARTZ, 4)); - - quartz.addIngredient(Material.QUARTZ_BLOCK); - - - // STRING RECIPE - ShapelessRecipe woolString = new ShapelessRecipe(new NamespacedKey(plugin, "string1"), new ItemStack(Material.STRING, 4)); - ShapelessRecipe string = new ShapelessRecipe(new NamespacedKey(plugin, "string2"), new ItemStack(Material.STRING, 2)); - - woolString.addIngredient(new RecipeChoice.MaterialChoice(Tag.WOOL)); - - string.addIngredient(Material.COBWEB); - - // WORKBENCH RECIPE - ShapelessRecipe workbench = new ShapelessRecipe(new NamespacedKey(plugin, "workbench"), ItemManager.get(Item.WORKBENCH)); - - workbench.addIngredient(new RecipeChoice.MaterialChoice(Tag.LOGS)); - workbench.addIngredient(Material.LEATHER); - workbench.addIngredient(Material.STRING); - workbench.addIngredient(new ExactChoice(ItemManager.get(Item.HAMMER))); - - - // FURNACE RECIPE - ShapedRecipe furnace = new ShapedRecipe(new NamespacedKey(plugin, "furnace"), new ItemStack(Material.FURNACE, 1)); - - furnace.shape("@@@", "@*@", "@@@"); - - furnace.setIngredient('@', Material.BRICK); - furnace.setIngredient('*', new ExactChoice(ItemManager.get(Item.FIRESTRIKER))); - - - // CHEST RECIPE - ShapedRecipe chest = new ShapedRecipe(new NamespacedKey(plugin, "chest"), new ItemStack(Material.CHEST, 1)); - - chest.shape("@@@", "@#@", "@@@"); - - chest.setIngredient('@', new RecipeChoice.MaterialChoice(Tag.PLANKS)); - chest.setIngredient('#', Material.IRON_INGOT); - - - // CLAY RECIPE - ShapedRecipe clay = new ShapedRecipe(new NamespacedKey(plugin, "clay"), new ItemStack(Material.CLAY, 1)); - - clay.shape(" ", "123", " "); - clay.setIngredient('1', Material.DIRT); - clay.setIngredient('2', Material.SAND); - clay.setIngredient('3', new ExactChoice(ItemManager.get(Item.WATER_BOWL))); - - - // DIORITE RECIPE - ShapelessRecipe diorite = new ShapelessRecipe(new NamespacedKey(plugin, "diorite"), new ItemStack(Material.DIORITE, 1)); - - diorite.addIngredient(new RecipeChoice.MaterialChoice(Material.BONE_MEAL, Material.WHITE_DYE)); - diorite.addIngredient(Material.COBBLESTONE); - - - // GRANITE RECIPE - ShapelessRecipe granite = new ShapelessRecipe(new NamespacedKey(plugin, "granite"), new ItemStack(Material.GRANITE, 1)); - - granite.addIngredient(Material.NETHERRACK); - granite.addIngredient(Material.COBBLESTONE); - - - // ANDESITE RECIPE - ShapelessRecipe andesite = new ShapelessRecipe(new NamespacedKey(plugin, "andesite"), new ItemStack(Material.ANDESITE, 1)); - - andesite.addIngredient(Material.GRAVEL); - andesite.addIngredient(Material.COBBLESTONE); - - - // GRAVEL RECIPE - ShapedRecipe gravel = new ShapedRecipe(new NamespacedKey(plugin, "gravel"), new ItemStack(Material.GRAVEL, 2)); - - gravel.shape("@B", "B@"); - - gravel.setIngredient('@', Material.SAND); - gravel.setIngredient('B', Material.COBBLESTONE); - - - // FIRESTRIKER RECIPE - ShapelessRecipe firestriker = new ShapelessRecipe(new NamespacedKey(plugin, "firestriker"), ItemManager.get(Item.FIRESTRIKER)); - - firestriker.addIngredient(Material.FLINT); - firestriker.addIngredient(new RecipeChoice.MaterialChoice(Tag.ITEMS_COALS)); - - - // TORCH RECIPE - ShapedRecipe torch1 = new ShapedRecipe(new NamespacedKey(plugin, "torch1"), new ItemStack(Material.TORCH, 8)); - ShapedRecipe torch2 = new ShapedRecipe(new NamespacedKey(plugin, "torch2"), new ItemStack(Material.TORCH, 16)); - - torch1.shape("AAA", "ABA", "AAA"); - torch1.setIngredient('B', new ExactChoice(ItemManager.get(Item.FIRESTRIKER))); - torch1.setIngredient('A', Material.STICK); - //torch1.setGroup("TORCH"); - - torch2.shape("ACA", "ABA", "AAA"); - torch2.setIngredient('C', new RecipeChoice.MaterialChoice(Tag.ITEMS_COALS)); - torch2.setIngredient('B', new ExactChoice(ItemManager.get(Item.FIRESTRIKER))); - torch2.setIngredient('A', Material.STICK); - //torch2.setGroup("TORCH"); - - - // FLINT RECIPE - ShapelessRecipe flint = new ShapelessRecipe(new NamespacedKey(plugin, "flint"), new ItemStack(Material.FLINT, 1)); - - flint.addIngredient(Material.GRAVEL); - - - // FERMENTED SPIDER EYE RECIPE - ShapelessRecipe fermented_spider_eye = new ShapelessRecipe(new NamespacedKey(plugin, "fermented_spider_eye"), - new ItemStack(Material.FERMENTED_SPIDER_EYE, 1)); - - fermented_spider_eye.addIngredient(Material.SPIDER_EYE); - fermented_spider_eye.addIngredient(Material.SUGAR); - fermented_spider_eye.addIngredient(new RecipeChoice.MaterialChoice(Material.RED_MUSHROOM, Material.BROWN_MUSHROOM)); - - - // FERMENTED SKIN RECIPE - ShapelessRecipe fermented_skin = new ShapelessRecipe(new NamespacedKey(plugin, "fermented_skin"), ItemManager.get(Item.FERMENTED_SKIN)); - - fermented_skin.addIngredient(Material.ROTTEN_FLESH); - fermented_skin.addIngredient(Material.SUGAR); - fermented_skin.addIngredient(new RecipeChoice.MaterialChoice(Material.BROWN_MUSHROOM, Material.RED_MUSHROOM)); - - - // POISONOUS POTATO RECIPE - ShapelessRecipe poisonousPotato = new ShapelessRecipe(new NamespacedKey(plugin, "poisonous_potato"), - new ItemStack(Material.POISONOUS_POTATO, 1)); - - poisonousPotato.addIngredient(Material.POTATO); - poisonousPotato.addIngredient(new RecipeChoice.MaterialChoice(Material.BONE_MEAL, Material.WHITE_DYE)); - - - // GLASS BOTTLE RECIPE - ShapelessRecipe glassBottle = new ShapelessRecipe(new NamespacedKey(plugin, "glass_bottle"), new ItemStack(Material.GLASS_BOTTLE, 1)); - - glassBottle.addIngredient(Material.POTION); - - - // BOWL RECIPE - ShapedRecipe bowl = new ShapedRecipe(new NamespacedKey(plugin, "bowl"), new ItemStack(Material.BOWL, 1)); - - bowl.shape(" ", " 1"); - bowl.setIngredient('1', new ExactChoice(ItemManager.get(Item.WATER_BOWL))); - - // CLEAN WATER RECIPES - FurnaceRecipe clean_water_furnace = new FurnaceRecipe(new NamespacedKey(plugin, "clean_water_furnace"), - ItemManager.get(Item.CLEAN_WATER), new ExactChoice(ItemManager.get(Item.DIRTY_WATER)), 0, 600); - - SmokingRecipe clean_water_smoker = new SmokingRecipe(new NamespacedKey(plugin, "clean_water_smoker"), - ItemManager.get(Item.CLEAN_WATER), new ExactChoice(ItemManager.get(Item.DIRTY_WATER)), 0, 300); - - CampfireRecipe clean_water_camp = new CampfireRecipe(new NamespacedKey(plugin, "clean_water_campfire"), - ItemManager.get(Item.CLEAN_WATER), new ExactChoice(ItemManager.get(Item.DIRTY_WATER)), 0, 2400); - - - // MEDIC KIT RECIPE - ShapedRecipe medic_kit = new ShapedRecipe(new NamespacedKey(plugin, "medic_kit"), ItemManager.get(Item.MEDIC_KIT)); - - medic_kit.shape(" @ ", "ABC", " @ "); - - medic_kit.setIngredient('@', Material.GOLD_INGOT); - medic_kit.setIngredient('A', Material.FEATHER); - medic_kit.setIngredient('B', Material.GLISTERING_MELON_SLICE); - medic_kit.setIngredient('C', Material.PAPER); - - - // FISHING ROD RECIPE - ShapedRecipe fishing_rod = new ShapedRecipe(new NamespacedKey(plugin, "fishing_rod"), new ItemStack(Material.FISHING_ROD, 1)); - - fishing_rod.shape("1- ", "1 -", "1@*"); - - fishing_rod.setIngredient('1', Material.STICK); - fishing_rod.setIngredient('@', Material.IRON_INGOT); - fishing_rod.setIngredient('-', Material.STRING); - fishing_rod.setIngredient('*', Material.FEATHER); - - - // IRON INGOT RECIPE - ShapedRecipe ironIngot = new ShapedRecipe(new NamespacedKey(plugin, "iron_ingot"), new ItemStack(Material.IRON_INGOT, 1)); - ironIngot.shape("@@", "@@"); - ironIngot.setIngredient('@', Material.IRON_NUGGET); - - // IRON NUGGET RECIPE - ShapelessRecipe ironNugget = new ShapelessRecipe(new NamespacedKey(plugin, "iron_nugget"), new ItemStack(Material.IRON_NUGGET, 4)); - ironNugget.addIngredient(Material.IRON_INGOT); - - // GOLD INGOT RECIPE - ShapedRecipe goldIngot = new ShapedRecipe(new NamespacedKey(plugin, "gold_ingot"), new ItemStack(Material.GOLD_INGOT, 1)); - goldIngot.shape("@@", "@@"); - goldIngot.setIngredient('@', Material.GOLD_NUGGET); - - // GOLD NUGGET RECIPE - ShapelessRecipe goldNugget = new ShapelessRecipe(new NamespacedKey(plugin, "gold_nugget"), new ItemStack(Material.GOLD_NUGGET, 4)); - goldNugget.addIngredient(Material.GOLD_INGOT); - - // SMELTING RECIPES - FurnaceRecipe smelt_ironIngot = new FurnaceRecipe(new NamespacedKey(plugin, "furnace_iron_ingot"), - new ItemStack(Material.IRON_INGOT, 1), Material.IRON_ORE, 1, 400); - FurnaceRecipe smelt_goldIngot = new FurnaceRecipe(new NamespacedKey(plugin, "furnace_gold_ingot"), - new ItemStack(Material.GOLD_INGOT, 1), Material.GOLD_ORE, 1, 400); - BlastingRecipe blast_ironIngot = new BlastingRecipe(new NamespacedKey(plugin, "blast_iron_ingot"), - new ItemStack(Material.IRON_INGOT, 1), Material.IRON_ORE, 1, 100); - BlastingRecipe blast_goldIngot = new BlastingRecipe(new NamespacedKey(plugin, "blast_gold_ingot"), - new ItemStack(Material.GOLD_INGOT, 1), Material.GOLD_ORE, 1, 100); - - - // BREAD RECIPE - ShapedRecipe bread = new ShapedRecipe(new NamespacedKey(plugin, "bread"), new ItemStack(Material.BREAD, 2)); - - bread.shape(" E ", "WWW"); - - bread.setIngredient('E', Material.EGG); - bread.setIngredient('W', Material.WHEAT); - - - // COOKIE RECIPE - ShapedRecipe cookie = new ShapedRecipe(new NamespacedKey(plugin, "cookie"), new ItemStack(Material.COOKIE, 8)); - - cookie.shape(" E ", "WCW", " S "); - - cookie.setIngredient('E', Material.EGG); - cookie.setIngredient('W', Material.WHEAT); - cookie.setIngredient('S', Material.SUGAR); - cookie.setIngredient('C', Material.COCOA_BEANS); - - - // SLIME BALL RECIPE - ShapelessRecipe slimeball = new ShapelessRecipe(new NamespacedKey(plugin, "slimeball"), new ItemStack(Material.SLIME_BALL, 1)); - - slimeball.addIngredient(Material.MILK_BUCKET); - slimeball.addIngredient(8, Material.VINE); - - - // COBWEB RECIPE - ShapelessRecipe cobweb = new ShapelessRecipe(new NamespacedKey(plugin, "cobweb"), new ItemStack(Material.COBWEB, 1)); - - cobweb.addIngredient(Material.SLIME_BALL); - cobweb.addIngredient(2, Material.STRING); - - - // SAPLING RECIPE - ShapelessRecipe stick = new ShapelessRecipe(new NamespacedKey(plugin, "stick"), new ItemStack(Material.STICK, 4)); - - stick.addIngredient(new RecipeChoice.MaterialChoice(Tag.SAPLINGS)); - - - // REINFORCED LEATHER BOOTS RECIPE - ShapedRecipe reinforced_leather_boots = new ShapedRecipe(new NamespacedKey(plugin, "reinforced_leather_boots"), - ItemManager.get(Item.REINFORCED_LEATHER_BOOTS)); - reinforced_leather_boots.shape("@*@"); - - reinforced_leather_boots.setIngredient('@', Material.IRON_INGOT); - reinforced_leather_boots.setIngredient('*', Material.LEATHER_BOOTS); - - - // REINFORCED LEATHER TUNIC RECIPE - ShapedRecipe reinforced_leather_chestplate = new ShapedRecipe(new NamespacedKey(plugin, "reinforced_leather_chestplate"), - ItemManager.get(Item.REINFORCED_LEATHER_TUNIC)); - reinforced_leather_chestplate.shape(" @ ", "@*@", " @ "); - - reinforced_leather_chestplate.setIngredient('@', Material.IRON_INGOT); - reinforced_leather_chestplate.setIngredient('*', Material.LEATHER_CHESTPLATE); - - - // REINFORCED LEATHER TROUSERS RECIPE - ShapedRecipe reinforced_leather_leggings = new ShapedRecipe(new NamespacedKey(plugin, "reinforced_leather_leggings"), - ItemManager.get(Item.REINFORCED_LEATHER_TROUSERS)); - reinforced_leather_leggings.shape(" @ ", "@*@", " @ "); - - reinforced_leather_leggings.setIngredient('@', Material.IRON_INGOT); - reinforced_leather_leggings.setIngredient('*', Material.LEATHER_LEGGINGS); - - - // REINFORCED LEATHER HELMET RECIPE - ShapedRecipe reinforced_leather_helmet = new ShapedRecipe(new NamespacedKey(plugin, "reinforced_leather_helmet"), - ItemManager.get(Item.REINFORCED_LEATHER_HELMET)); - reinforced_leather_helmet.shape("@*@"); - - reinforced_leather_helmet.setIngredient('@', Material.IRON_INGOT); - reinforced_leather_helmet.setIngredient('*', Material.LEATHER_HELMET); - - - // GOLDEN SABATONS RECIPE - ShapedRecipe gold_sabatons = new ShapedRecipe(new NamespacedKey(plugin, "gold_sabatons"), ItemManager.get(Item.GOLDEN_SABATONS)); - gold_sabatons.shape("@ @", "@ @"); - - gold_sabatons.setIngredient('@', Material.GOLD_INGOT); - - - // GOLDEN GUARD RECIPE - ShapedRecipe gold_guard = new ShapedRecipe(new NamespacedKey(plugin, "gold_guard"), ItemManager.get(Item.GOLDEN_GUARD)); - gold_guard.shape("@ @", "@@@", "@@@"); - - gold_guard.setIngredient('@', Material.GOLD_INGOT); - - - // GOLDEN GREAVES RECIPE - ShapedRecipe gold_greaves = new ShapedRecipe(new NamespacedKey(plugin, "gold_greaves"), ItemManager.get(Item.GOLDEN_GREAVES)); - gold_greaves.shape("@@@", "@ @", "@ @"); - - gold_greaves.setIngredient('@', Material.GOLD_INGOT); - - - // GOLDEN CROWN RECIPE - ShapedRecipe gold_crown = new ShapedRecipe(new NamespacedKey(plugin, "gold_crown"), ItemManager.get(Item.GOLDEN_CROWN)); - gold_crown.shape("@*@", "@@@"); - - gold_crown.setIngredient('@', Material.GOLD_INGOT); - gold_crown.setIngredient('*', Material.EMERALD); - - - // IRON BOOTS RECIPE - ShapedRecipe ironBoots = new ShapedRecipe(new NamespacedKey(plugin, "iron_boots"), ItemManager.get(Item.IRON_BOOTS)); - ironBoots.shape("@ @", "@ @"); - - ironBoots.setIngredient('@', Material.IRON_INGOT); - - - // IRON CHESTPLATE RECIPE - ShapedRecipe ironChestplate = new ShapedRecipe(new NamespacedKey(plugin, "iron_chestplate"), ItemManager.get(Item.IRON_CHESTPLATE)); - ironChestplate.shape("@ @", "@@@", "@@@"); - - ironChestplate.setIngredient('@', Material.IRON_INGOT); - - - // IRON LEGGINGS RECIPE - ShapedRecipe ironLeggings = new ShapedRecipe(new NamespacedKey(plugin, "iron_leggings"), ItemManager.get(Item.IRON_LEGGINGS)); - ironLeggings.shape("@@@", "@ @", "@ @"); - - ironLeggings.setIngredient('@', Material.IRON_INGOT); - - - // IRON HELMET RECIPE - ShapedRecipe ironHelmet = new ShapedRecipe(new NamespacedKey(plugin, "iron_helmet"), ItemManager.get(Item.IRON_HELMET)); - ironHelmet.shape("@@@", "@ @"); - - ironHelmet.setIngredient('@', Material.IRON_INGOT); - - - // DIAMOND BOOTS RECIPE - ShapedRecipe diamondBoots = new ShapedRecipe(new NamespacedKey(plugin, "diamond_boots"), ItemManager.get(Item.DIAMOND_BOOTS)); - diamondBoots.shape("@ @", "@ @"); - - diamondBoots.setIngredient('@', Material.DIAMOND); - - - // DIAMOND CHESTPLATE RECIPE - ShapedRecipe diamondChestplate = new ShapedRecipe(new NamespacedKey(plugin, "diamond_chestplate"), ItemManager.get(Item.DIAMOND_CHESTPLATE)); - diamondChestplate.shape("@ @", "@@@", "@@@"); - - diamondChestplate.setIngredient('@', Material.DIAMOND); - - - // DIAMOND LEGGINGS RECIPE - ShapedRecipe diamondLeggings = new ShapedRecipe(new NamespacedKey(plugin, "diamond_leggings"), ItemManager.get(Item.DIAMOND_LEGGINGS)); - diamondLeggings.shape("@@@", "@ @", "@ @"); - - diamondLeggings.setIngredient('@', Material.DIAMOND); - - - // DIAMOND HELMET RECIPE - ShapedRecipe diamondHelmet = new ShapedRecipe(new NamespacedKey(plugin, "diamond_helmet"), ItemManager.get(Item.DIAMOND_HELMET)); - diamondHelmet.shape("@@@", "@ @"); - - diamondHelmet.setIngredient('@', Material.DIAMOND); - - - // RECURVED BOW RECIPE - ShapedRecipe recurvedBow = new ShapedRecipe(new NamespacedKey(plugin, "recurved_bow"), ItemManager.get(Item.RECURVE_BOW)); - - recurvedBow.shape(" @1", "#^1", " @1"); - recurvedBow.setIngredient('^', Material.BOW); - recurvedBow.setIngredient('#', Material.PISTON); - recurvedBow.setIngredient('@', Material.IRON_INGOT); - recurvedBow.setIngredient('1', Material.STRING); - - - // RECURVED CROSSBOW - ShapedRecipe recurvedCrossbow = new ShapedRecipe(new NamespacedKey(plugin, "recurved_crossbow"), ItemManager.get(Item.RECURVE_CROSSBOW)); - - recurvedCrossbow.shape(" 12", "342", " 12"); - recurvedCrossbow.setIngredient('1', Material.DIAMOND); - recurvedCrossbow.setIngredient('2', Material.PHANTOM_MEMBRANE); - recurvedCrossbow.setIngredient('3', Material.PISTON); - recurvedCrossbow.setIngredient('4', Material.CROSSBOW); - - // NEW CAMPFIRE RECIPE - ShapedRecipe unlit_campfire = new ShapedRecipe(new NamespacedKey(plugin, "unlit_campfire"), ItemManager.get(Item.CAMPFIRE)); - - unlit_campfire.shape(" 1 ", "121", "333"); - unlit_campfire.setIngredient('1', Material.STICK); - unlit_campfire.setIngredient('2', new RecipeChoice.MaterialChoice(Tag.ITEMS_COALS)); - unlit_campfire.setIngredient('3', new RecipeChoice.MaterialChoice(Tag.LOGS)); - - // FLINT SICKLE RECIPE - ShapedRecipe flint_sickle = new ShapedRecipe(new NamespacedKey(plugin, "flint_sickle"), ItemManager.get(Item.FLINT_SICKLE)); - - flint_sickle.shape("11 ", " 2 ", " 2 "); - flint_sickle.setIngredient('1', Material.FLINT); - flint_sickle.setIngredient('2', Material.STICK); - - // STONE SICKLE RECIPE - ShapedRecipe stone_sickle = new ShapedRecipe(new NamespacedKey(plugin, "stone_sickle"), ItemManager.get(Item.STONE_SICKLE)); - - stone_sickle.shape("112", " 3", " 3 "); - stone_sickle.setIngredient('1', Material.COBBLESTONE); - stone_sickle.setIngredient('2', Material.FLINT); - stone_sickle.setIngredient('3', Material.STICK); - - // IRON SICKLE RECIPE - ShapedRecipe iron_sickle = new ShapedRecipe(new NamespacedKey(plugin, "iron_sickle"), ItemManager.get(Item.IRON_SICKLE)); - - iron_sickle.shape("112", " 3", " 3 "); - iron_sickle.setIngredient('1', Material.IRON_INGOT); - iron_sickle.setIngredient('2', Material.FLINT); - iron_sickle.setIngredient('3', Material.STICK); - - // DIAMOND SICKLE RECIPE - ShapedRecipe diamond_sickle = new ShapedRecipe(new NamespacedKey(plugin, "diamond_sickle"), ItemManager.get(Item.DIAMOND_SICKLE)); - - diamond_sickle.shape("112", " 3", " 3 "); - diamond_sickle.setIngredient('1', Material.DIAMOND); - diamond_sickle.setIngredient('2', Material.FLINT); - diamond_sickle.setIngredient('3', Material.STICK); - - // NEW GRAPPLING HOOK RECIPE - ShapedRecipe grappling_hook = new ShapedRecipe(new NamespacedKey(plugin, "grappling_hook"), ItemManager.get(Item.GRAPPLING_HOOK)); - - grappling_hook.shape(" 3 ", "121", " 3 "); - grappling_hook.setIngredient('1', Material.FISHING_ROD); - grappling_hook.setIngredient('2', Material.STRING); - grappling_hook.setIngredient('3', Material.IRON_INGOT); - - // NEW COFFEE RECIPES - SmokingRecipe coffee_bean = new SmokingRecipe(new NamespacedKey(plugin, "coffee_bean"), ItemManager.get(Item.COFFEE_BEAN), - Material.COCOA_BEANS, 0, 200); - - SmokingRecipe hot_milk = new SmokingRecipe(new NamespacedKey(plugin, "hot_milk"), ItemManager.get(Item.HOT_MILK), - new ExactChoice(ItemManager.get(Item.COLD_MILK)), 0, 200); - - ItemStack COFFEE = ItemManager.get(Item.COFFEE); - COFFEE.setAmount(2); - ShapedRecipe coffee = new ShapedRecipe(new NamespacedKey(plugin, "coffee"), COFFEE); - - coffee.shape(" ", "12 ", "34 "); - coffee.setIngredient('1', new ExactChoice(ItemManager.get(Item.COFFEE_BEAN))); - coffee.setIngredient('2', Material.COCOA_BEANS); - coffee.setIngredient('3', new ExactChoice(ItemManager.get(Item.HOT_MILK))); - coffee.setIngredient('4', new ExactChoice(ItemManager.get(Item.PURIFIED_WATER))); - - ShapedRecipe cold_milk = new ShapedRecipe(new NamespacedKey(plugin, "cold_milk"), ItemManager.get(Item.COLD_MILK)); - - cold_milk.shape(" ", "12 ", " "); - cold_milk.setIngredient('1', Material.MILK_BUCKET); - cold_milk.setIngredient('2', Material.GLASS_BOTTLE); - - // NEW COMPASS RECIPE - ShapedRecipe compass_recipe = new ShapedRecipe(new NamespacedKey(plugin, "compass"), ItemManager.get(Item.COMPASS)); - compass_recipe.shape(" 1 ", "121", " 1 "); - compass_recipe.setIngredient('1', Material.IRON_INGOT); - compass_recipe.setIngredient('2', Material.REDSTONE); - - // BEEKEEPER RECIPES - ShapedRecipe beekeeper_helmet = new ShapedRecipe(key("beekeeper_helmet"), ItemManager.get(Item.BEEKEEPER_HELMET)); - beekeeper_helmet.shape("121", "3 3", " "); - beekeeper_helmet.setIngredient('1', Material.HONEYCOMB); - beekeeper_helmet.setIngredient('2', Material.IRON_INGOT); - beekeeper_helmet.setIngredient('3', Material.LEATHER); - - ShapedRecipe beekeeper_chest = new ShapedRecipe(key("beekeeper_chestplate"), ItemManager.get(Item.BEEKEEPER_CHESTPLATE)); - beekeeper_chest.shape("1 1", "232", "323"); - beekeeper_chest.setIngredient('1', Material.HONEYCOMB); - beekeeper_chest.setIngredient('2', Material.IRON_INGOT); - beekeeper_chest.setIngredient('3', Material.LEATHER); - - ShapedRecipe beekeeper_leg = new ShapedRecipe(key("beekeeper_leggings"), ItemManager.get(Item.BEEKEEPER_LEGGINGS)); - beekeeper_leg.shape("131", "3 3", "2 2"); - beekeeper_leg.setIngredient('1', Material.HONEYCOMB); - beekeeper_leg.setIngredient('2', Material.IRON_INGOT); - beekeeper_leg.setIngredient('3', Material.LEATHER); - - ShapedRecipe beekeeper_boot = new ShapedRecipe(key("beekeeper_boots"), ItemManager.get(Item.BEEKEEPER_BOOTS)); - beekeeper_boot.shape(" ", "1 1", "3 3"); - beekeeper_boot.setIngredient('1', Material.HONEYCOMB); - beekeeper_boot.setIngredient('3', Material.LEATHER); - - if (config.ENTITY_MECHANICS_BEEKEEPER_SUIT_ENABLED) { - server.addRecipe(beekeeper_helmet); - server.addRecipe(beekeeper_chest); - server.addRecipe(beekeeper_leg); - server.addRecipe(beekeeper_boot); - } - - if (config.MECHANICS_WEATHER_ENABLED) { - ShapedRecipe snowBoots = new ShapedRecipe(key("snow_boots"), Item.SNOW_BOOTS.getItem()); - snowBoots.shape(" ", "121", " "); - snowBoots.setIngredient('1', Material.DIAMOND); - snowBoots.setIngredient('2', Material.LEATHER_BOOTS); - server.addRecipe(snowBoots); - - ShapedRecipe rainBoots = new ShapedRecipe(key("rain_boots"), Item.RAIN_BOOTS.getItem()); - rainBoots.shape(" ", "121", " "); - rainBoots.setIngredient('1', Material.IRON_INGOT); - rainBoots.setIngredient('2', Material.LEATHER_BOOTS); - server.addRecipe(rainBoots); - } - - - //Add recipes - if (config.SURVIVAL_ENABLED) { - plugin.getServer().addRecipe(hatchet1); - plugin.getServer().addRecipe(hatchet2); - plugin.getServer().addRecipe(mattock); - plugin.getServer().addRecipe(shiv); - plugin.getServer().addRecipe(hammer); - plugin.getServer().addRecipe(firestriker); - plugin.getServer().addRecipe(chest); - plugin.getServer().addRecipe(flint); - plugin.getServer().addRecipe(unlit_campfire); - if (config.BREAK_ONLY_WITH_SICKLE) { - if (config.SURVIVAL_SICKLE_FLINT) - plugin.getServer().addRecipe(flint_sickle); - if (config.SURVIVAL_SICKLE_STONE) - plugin.getServer().addRecipe(stone_sickle); - if (config.SURVIVAL_SICKLE_IRON) - plugin.getServer().addRecipe(iron_sickle); - if (config.SURVIVAL_SICKLE_DIAMOND) - plugin.getServer().addRecipe(diamond_sickle); - } - if (config.RECIPES_WORKBENCH) { - plugin.getServer().addRecipe(workbench); - } - if (config.RECIPES_FURNACE) { - plugin.getServer().addRecipe(furnace); - } - } - if (config.SURVIVAL_TORCH) { - plugin.getServer().addRecipe(torch1); - plugin.getServer().addRecipe(torch2); - } - if (config.RECIPES_WEB_STRING) - plugin.getServer().addRecipe(string); - if (config.RECIPES_SAPLING_STICK) { - plugin.getServer().addRecipe(stick); - } - - if (config.LEGENDARY_VALKYRIE) { - plugin.getServer().addRecipe(valkyries_axe); - } - if (config.LEGENDARY_QUARTZPICKAXE) { - plugin.getServer().addRecipe(quartz_pickaxe); - } - if (config.LEGENDARY_OBSIDIAN_MACE) { - plugin.getServer().addRecipe(obsidian_mace); - } - if (config.LEGENDARY_GIANTBLADE) { - plugin.getServer().addRecipe(ender_giant_blade); - } - if (config.LEGENDARY_BLAZESWORD) { - plugin.getServer().addRecipe(blaze_sword); - } - if (config.LEGENDARY_NOTCH_APPLE) - plugin.getServer().addRecipe(notchApple); - if (config.RECIPES_SADDLE) - plugin.getServer().addRecipe(saddle); - if (config.RECIPES_NAME_TAG) { - plugin.getServer().addRecipe(nametag); - } - if (config.RECIPES_PACKED_ICE) { - plugin.getServer().addRecipe(packedIce1); - plugin.getServer().addRecipe(ice2); - } - if (config.RECIPES_IRON_BARD) { - plugin.getServer().addRecipe(iron_horse_armor); - } - if (config.RECIPES_GOLD_BARD) { - plugin.getServer().addRecipe(goldHorse1); - } - if (config.RECIPES_DIAMOND_BARD) { - plugin.getServer().addRecipe(diamond_horse_armor); - } - if (config.RECIPES_LEATHER_BARD) { - plugin.getServer().addRecipe(leather_horse_armor); - } - if (config.RECIPES_CLAY_BRICK) - plugin.getServer().addRecipe(clayBrick); - if (config.RECIPES_QUARTZ_BLOCK) - plugin.getServer().addRecipe(quartz); - if (config.RECIPES_WOOL_STRING) - plugin.getServer().addRecipe(woolString); - if (config.RECIPES_ICE) - plugin.getServer().addRecipe(ice); - if (config.RECIPES_CLAY) - plugin.getServer().addRecipe(clay); - if (config.RECIPES_DIORITE) - plugin.getServer().addRecipe(diorite); - if (config.RECIPES_GRANITE) - plugin.getServer().addRecipe(granite); - if (config.RECIPES_ANDESITE) - plugin.getServer().addRecipe(andesite); - if (config.RECIPES_GRAVEL) { - plugin.getServer().addRecipe(gravel); - } - /* There is no setting for this in the config?!?! - if (settings.getBoolean("Mechanics.RedMushroomFermentation")) { - survival.getServer().addRecipe(fermented_spider_eye); - } - - */ - if (config.MECHANICS_FERMENTED_SKIN) { - plugin.getServer().addRecipe(fermented_skin); - } - if (config.MECHANICS_POISON_POTATO) - plugin.getServer().addRecipe(poisonousPotato); - if (config.MECHANICS_EMPTY_POTION) { - plugin.getServer().addRecipe(glassBottle); - plugin.getServer().addRecipe(bowl); - } - if (config.MECHANICS_REINFORCED_ARMOR) { - plugin.getServer().addRecipe(reinforced_leather_boots); - plugin.getServer().addRecipe(reinforced_leather_chestplate); - plugin.getServer().addRecipe(reinforced_leather_leggings); - plugin.getServer().addRecipe(reinforced_leather_helmet); - } - if (config.LEGENDARY_GOLDARMORBUFF) { - plugin.getServer().addRecipe(gold_sabatons); - plugin.getServer().addRecipe(gold_guard); - plugin.getServer().addRecipe(gold_greaves); - plugin.getServer().addRecipe(gold_crown); - } - - if (config.MECHANICS_SLOW_ARMOR) { - plugin.getServer().addRecipe(ironBoots); - plugin.getServer().addRecipe(ironChestplate); - plugin.getServer().addRecipe(ironLeggings); - plugin.getServer().addRecipe(ironHelmet); - plugin.getServer().addRecipe(diamondBoots); - plugin.getServer().addRecipe(diamondChestplate); - plugin.getServer().addRecipe(diamondLeggings); - plugin.getServer().addRecipe(diamondHelmet); - } - - if (config.MECHANICS_MEDIC_KIT) { - plugin.getServer().addRecipe(medic_kit); - } - - if (config.RECIPES_FISHING_ROD) { - plugin.getServer().addRecipe(fishing_rod); - } - - if (config.MECHANICS_REDUCED_IRON_NUGGET) { - plugin.getServer().addRecipe(ironNugget); - plugin.getServer().addRecipe(ironIngot); - plugin.getServer().addRecipe(smelt_ironIngot); - plugin.getServer().addRecipe(blast_ironIngot); - } - - if (config.MECHANICS_REDUCED_GOLD_NUGGET) { - plugin.getServer().addRecipe(goldNugget); - plugin.getServer().addRecipe(goldIngot); - plugin.getServer().addRecipe(smelt_goldIngot); - plugin.getServer().addRecipe(blast_goldIngot); - } - - if (config.MECHANICS_FARMING_PRODUCTS_BREAD) - plugin.getServer().addRecipe(bread); - if (config.MECHANICS_FARMING_PRODUCTS_COOKIE) - plugin.getServer().addRecipe(cookie); - if (config.RECIPES_SLIMEBALL) - plugin.getServer().addRecipe(slimeball); - if (config.RECIPES_COBWEB) - plugin.getServer().addRecipe(cobweb); - if (config.MECHANICS_RECURVED_BOW) { - plugin.getServer().addRecipe(recurvedBow); - plugin.getServer().addRecipe(recurvedCrossbow); - } - if (config.MECHANICS_GRAPPLING_HOOK) - plugin.getServer().addRecipe(grappling_hook); - if (config.MECHANICS_THIRST_PURIFY_WATER) { - plugin.getServer().addRecipe(clean_water_furnace); - plugin.getServer().addRecipe(clean_water_smoker); - plugin.getServer().addRecipe(clean_water_camp); - } - if (config.MECHANICS_ENERGY_COFFEE_ENABLED) { - plugin.getServer().addRecipe(coffee_bean); - plugin.getServer().addRecipe(cold_milk); - plugin.getServer().addRecipe(hot_milk); - plugin.getServer().addRecipe(coffee); - } - if (config.MECHANICS_COMPASS_WAYPOINT) { - plugin.getServer().addRecipe(compass_recipe); - } - } - - /** - * Enums of all custom recipes - */ - public enum Recipes { - // CUSTOM TOOLS/ITEMS - HATCHET("hatchet1", "hatchet2"), - MATTOCK("mattock"), - SHIV("shiv"), - HAMMER("hammer"), - WORKBENCH("workbench"), - FIRESTRIKER("firestriker"), - VALKYRIES_AXE("valkyrie_axe"), - QUARTZ_PICKAXE("quartz_pickaxe"), - OBSIDIAN_MACE("obsidian_mace"), - ENDER_GIANT_BLADE("ender_giant_blade"), - BLAZE_SWORD("blaze_sword"), - FERMENTED_SKIN("fermented_skin"), - MEDIC_KIT("medic_kit"), - REINFORCED_LEATHER_BOOTS("reinforced_leather_boots"), - REINFORCED_LEATHER_CHESTPLATE("reinforced_leather_chestplate"), - REINFORCED_LEATHER_LEGGINGS("reinforced_leather_leggings"), - REINFORCED_LEATHER_HELMET("reinforced_leather_helmet"), - GOLD_SABATONS("gold_sabatons"), - GOLD_GUARD("gold_guard"), - GOLD_GREAVES("gold_greaves"), - GOLD_CROWN("gold_crown"), - RECURVED_BOW("recurved_bow"), - RECURVED_CROSSBOW("recurved_crossbow"), - UNLIT_CAMPFIRE("unlit_campfire"), - FLINT_SICKLE("flint_sickle"), - STONE_SICKLE("stone_sickle"), - IRON_SICKLE("iron_sickle"), - DIAMOND_SICKLE("diamond_sickle"), - GRAPPLING_HOOK("grappling_hook"), - WATER_BOTTLES("clean_water_furnace", "clean_water_smoker", "clean_water_campfire"), - COFFEE_BEAN("coffee_bean"), - COLD_MILK("cold_milk"), - HOT_MILK("hot_milk"), - COFFEE("coffee"), - BEEKEEPER_SUIT("beekeeper_helmet", "beekeeper_chestplate", "beekeeper_leggings", "beekeeper_boots"), - SNOW_BOOTS("snow_boots"), - RAIN_BOOTS("rain_boots"), - - // VANILLA ITEMS - ENCHANTED_GOLDEN_APPLE("enchanted_golden_apple"), - SADDLE("saddle"), - NAMETAG("nametag"), - STRING("string1", "string2"), - IRON_HORSE_ARMOR("iron_horse_armor"), - GOLD_HORSE_ARMOR("gold_horse_armor"), - DIAMOND_HORSE_ARMOR("diamond_horse_armor"), - LEATHER_HORSE_ARMOR("leather_horse_armor"), - TORCH("torch1", "torch2"), - FLINT("flint"), - FERMENTED_SPIDER_EYE("fermented_spider_eye"), - POISONOUS_POTATO("poisonous_potato"), - GLASS_BOTTLE("glass_bottle"), - BOWL("bowl"), - FISHING_ROD("fishing_rod"), - IRON_INGOT("iron_ingot"), - IRON_NUGGET("iron_nugget"), - GOLD_INGOT("gold_ingot"), - GOLD_NUGGET("gold_nugget"), - BREAD("bread"), - COOKIE("cookie"), - SLIMEBALL("slimeball"), - COBWEB("cobweb"), - STICK("stick"), - IRON_BOOTS("iron_boots"), - IRON_LEGGINGS("iron_leggings"), - IRON_CHESTPLATE("iron_chestplate"), - IRON_HELMET("iron_helmet"), - DIAMOND_BOOTS("diamond_boots"), - DIAMOND_LEGGINGS("diamond_leggings"), - DIAMOND_CHESTPLATE("diamond_chestplate"), - DIAMOND_HELMET("diamond_helmet"), - COMPASS("compass"), - - // VANILLA BLOCKS - CLAY_BRICK("clay_brick"), - QUARTZ("quartz"), - FURNACE("furnace"), - CHEST("chest"), - CLAY("clay"), - DIORITE("diorite"), - ANDESITE("andesite"), - GRANITE("granite"), - GRAVEL("gravel"), - ICE("ice1", "ice2"), - PACKED_ICE("packed_ice"), - - // SMELTING RECIPES - FURNACE_IRON_INGOT("furnace_iron_ingot"), - FURNACE_GOLD_INGOT("furnace_gold_ingot"), - BLAST_IRON_INGOT("blast_iron_ingot"), - BLAST_GOLD_INGOT("blast_gold_ingot"); - - private final Collection keys; - private static final Collection allKeys; - - static { - allKeys = new ArrayList<>(); - for (Recipes recipes : values()) { - allKeys.addAll(recipes.keys); - } - } - - Recipes(String... keys) { - ArrayList list = new ArrayList<>(); - for (String key : keys) { - assert false; - list.add(Utils.getNamespacedKey(key)); - } - this.keys = list; - } - - /** - * Get the {@link NamespacedKey}s for this recipe - * - * @return NamespacedKeys for this recipe - */ - public Collection getKeys() { - return this.keys; - } - - private static Collection getAllKeys() { - return allKeys; - } - } - - private void removeRecipes() { - if (config.SURVIVAL_ENABLED) { - removeRecipeByKey("campfire"); - removeRecipeByKey("chest"); - if (config.SURVIVAL_TORCH) { - removeRecipeByKey("torch"); - } - if (config.RECIPES_FURNACE) { - removeRecipeByKey("furnace"); - } - if (config.RECIPES_WORKBENCH) { - removeRecipeByKey("crafting_table"); - } - } - if (config.SURVIVAL_REMOVE_WOOD_TOOLS) { - removeRecipeByKey("wooden_sword"); - removeRecipeByKey("wooden_hoe"); - removeRecipeByKey("wooden_shovel"); - removeRecipeByKey("wooden_pickaxe"); - removeRecipeByKey("wooden_axe"); - } - if (config.MECHANICS_REDUCED_IRON_NUGGET) { - removeRecipeByKey("iron_ingot"); - removeRecipeByKey("iron_ingot_from_nuggets"); - removeRecipeByKey("iron_nugget"); - removeRecipeByKey("iron_nugget_from_smelting"); - } - if (config.MECHANICS_REDUCED_GOLD_NUGGET) { - removeRecipeByKey("gold_ingot"); - removeRecipeByKey("gold_ingot_from_nuggets"); - removeRecipeByKey("gold_nugget"); - removeRecipeByKey("gold_nugget_from_smelting"); - - } - if (config.MECHANICS_SLOW_ARMOR) { - removeRecipeByKey("diamond_helmet"); - removeRecipeByKey("diamond_chestplate"); - removeRecipeByKey("diamond_leggings"); - removeRecipeByKey("diamond_boots"); - removeRecipeByKey("iron_helmet"); - removeRecipeByKey("iron_chestplate"); - removeRecipeByKey("iron_leggings"); - removeRecipeByKey("iron_boots"); - } - if (config.MECHANICS_SNOWBALL_REVAMP) { - removeRecipeByKey("snow"); - removeRecipeByKey("snow_block"); - } - if (config.MECHANICS_FARMING_PRODUCTS_COOKIE) { - removeRecipeByKey("cookie"); - } - if (config.MECHANICS_FARMING_PRODUCTS_BREAD) { - removeRecipeByKey("bread"); - } - if (config.LEGENDARY_GOLDARMORBUFF) { - removeRecipeByKey("golden_helmet"); - removeRecipeByKey("golden_chestplate"); - removeRecipeByKey("golden_boots"); - removeRecipeByKey("golden_leggings"); - } - if (config.LEGENDARY_BLAZESWORD) { - removeRecipeByKey("golden_sword"); - } - if (config.LEGENDARY_GIANTBLADE) { - removeRecipeByKey("golden_hoe"); - } - if (config.LEGENDARY_QUARTZPICKAXE) { - removeRecipeByKey("golden_pickaxe"); - } - if (config.LEGENDARY_OBSIDIAN_MACE) { - removeRecipeByKey("golden_shovel"); - } - if (config.LEGENDARY_VALKYRIE) { - removeRecipeByKey("golden_axe"); - } - if (config.RECIPES_GRANITE) { - removeRecipeByKey("granite"); - } - if (config.RECIPES_ANDESITE) { - removeRecipeByKey("andesite"); - } - if (config.RECIPES_DIORITE) { - removeRecipeByKey("diorite"); - } - if (config.RECIPES_LEATHER_BARD) { - removeRecipeByKey("leather_horse_armor"); - } - if (config.RECIPES_FISHING_ROD) { - removeRecipeByKey("fishing_rod"); - } - if (config.MECHANICS_COMPASS_WAYPOINT) { - removeRecipeByKey("compass"); - } - if (config.RECIPES_PACKED_ICE) { - removeRecipeByKey("packed_ice"); - } - } - - /** - * Unlock all custom recipes for a player - * - * @param player Player to unlock recipes for - */ - public void unlockAllRecipes(Player player) { - player.discoverRecipes(Recipes.getAllKeys()); - } - - /** - * Remove a vanilla Minecraft recipe from the server - * - * @param recipeKey Recipe to remove - */ - @SuppressWarnings("WeakerAccess") - public void removeRecipeByKey(String recipeKey) { - Bukkit.removeRecipe(NamespacedKey.minecraft(recipeKey)); - } - - private NamespacedKey key(String key) { - return new NamespacedKey(plugin, key); - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/ScoreBoardManager.java b/src/main/java/tk/shanebee/survival/managers/ScoreBoardManager.java deleted file mode 100644 index ffd64e2..0000000 --- a/src/main/java/tk/shanebee/survival/managers/ScoreBoardManager.java +++ /dev/null @@ -1,47 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.entity.Player; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.Board; -import tk.shanebee.survival.tasks.Healthboard; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class ScoreBoardManager { - - private final Survival plugin; - private final Map playerBoards = new HashMap<>(); - - public ScoreBoardManager(Survival plugin) { - this.plugin = plugin; - } - - /** Sets up a scoreboard for a player - *

- * This is generally used internally - *

- * @param player Player to setup a scoreboard for - */ - public void setupScoreboard(Player player) { - playerBoards.put(player.getUniqueId(), new Healthboard(plugin, player)); - } - - public void resetStatusScoreboard(boolean enabled) { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (enabled) - setupScoreboard(player); - else - Board.removeBoard(player); - } - } - - public void unloadScoreboard(Player player) { - if (playerBoards.containsKey(player.getUniqueId())) { - playerBoards.get(player.getUniqueId()).cancel(); - playerBoards.remove(player.getUniqueId()); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/managers/StatusManager.java b/src/main/java/tk/shanebee/survival/managers/StatusManager.java deleted file mode 100644 index 5bba9d9..0000000 --- a/src/main/java/tk/shanebee/survival/managers/StatusManager.java +++ /dev/null @@ -1,152 +0,0 @@ -package tk.shanebee.survival.managers; - -import org.bukkit.entity.Player; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.Nutrient; -import tk.shanebee.survival.data.PlayerData; - -/** - * Manage a player's different status levels - * @deprecated Use {@link PlayerData} - */ -@SuppressWarnings({"unused", "WeakerAccess"}) -@Deprecated -public class StatusManager { - - private static PlayerManager playerManager = Survival.getInstance().getPlayerManager(); - - /** - * Enums for Nutrient types - */ - public enum Nutrients { - CARBS("Carbs"), - PROTEIN("Protein"), - SALTS("Salts"); - - private String name; - - Nutrients(String nutrient){ - name = nutrient; - } - - public String getName() { - return name; - } - - } - - /** Set the thirst level of a player - * @param player The player to set thirst for - * @param level The level of thirst to set (Max = 40) - */ - public static void setThirst(Player player, int level) { - PlayerData pd = playerManager.getPlayerData(player); - pd.setThirst(level); - } - - /** Get the thirst level of a player - * @param player The player to get a thirst level from - * @return The thirst level of this player - */ - public static int getThirst(Player player) { - PlayerData pd = playerManager.getPlayerData(player); - return pd.getThirst(); - } - - /** Add to the thirst level of a player - * @param player The player to add thirst to - * @param level The level of thirst to add - */ - public static void addThirst(Player player, int level) { - setThirst(player, getThirst(player) + level); - } - - /** Remove from the thirst level of a player - * @param player The player to remove thirst from - * @param level The level of thirst to remove - */ - public static void removeThirst(Player player, int level) { - setThirst(player, getThirst(player) - level); - } - - /** Set the nutrient levels of a player - * @param player The player to set nutrients for - * @param nutrient The nutrient to set - * @param level The level to set - */ - public static void setNutrients(Player player, Nutrients nutrient, int level) { - PlayerData pd = playerManager.getPlayerData(player); - switch (nutrient) { - case SALTS: - pd.setNutrient(Nutrient.SALTS, level); - break; - case CARBS: - pd.setNutrient(Nutrient.CARBS, level); - break; - case PROTEIN: - pd.setNutrient(Nutrient.PROTEIN, level); - } - } - - /** Get the nutrient levels of a player - * @param player The player to get nutrient levels for - * @param nutrient The nutrient to check - * @return The level of this nutrient - */ - public static int getNutrients(Player player, Nutrients nutrient) { - PlayerData pd = playerManager.getPlayerData(player); - switch (nutrient) { - case SALTS: - return pd.getNutrient(Nutrient.SALTS); - case CARBS: - return pd.getNutrient(Nutrient.CARBS); - case PROTEIN: - return pd.getNutrient(Nutrient.PROTEIN); - default: - return 0; - } - } - - /** Add to the nutrient levels of a player - * @param player The player to add nutrients for - * @param nutrient The nutrient to add to - * @param level The level to add - */ - public static void addNutrients(Player player, Nutrients nutrient, int level) { - setNutrients(player, nutrient, getNutrients(player, nutrient) + level); - } - - /** Remove from the nutrient levels of a player - * @param player The player to remove nutrients for - * @param nutrient The nutrient to remove from - * @param level The level to remove - */ - public static void removeNutrients(Player player, Nutrients nutrient, int level) { - setNutrients(player, nutrient, getNutrients(player, nutrient) - level); - } - - /** Set the hunger level of a player - *

- * NOTE: This level is a mixture of the player's food/saturation levels - *

- * @param player The player to set hunger level for - * @param level The level to set for the player - */ - public static void setHunger(Player player, int level) { - level = Math.min(level, 40); - player.setFoodLevel(Math.min(level, 20)); - player.setSaturation(level >= 21 ? level - 20 : 0); - } - - /** Get the hunger level of a player - *

- * NOTE: This level is a mixture of the player's food/saturation levels - *

- * @param player The player to get hunger level for - * @return The level of player's hunger - */ - public static int getHunger(Player player) { - return Math.round(player.getFoodLevel() + player.getSaturation()); - } - -} diff --git a/src/main/java/tk/shanebee/survival/metrics/Metrics.java b/src/main/java/tk/shanebee/survival/metrics/Metrics.java deleted file mode 100644 index 354eb6b..0000000 --- a/src/main/java/tk/shanebee/survival/metrics/Metrics.java +++ /dev/null @@ -1,718 +0,0 @@ -package tk.shanebee.survival.metrics; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; - -import javax.net.ssl.HttpsURLConnection; -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - */ -@SuppressWarnings({"WeakerAccess", "unused"}) -public class Metrics { - - static { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Is bStats enabled on this server? - private boolean enabled; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final Plugin plugin; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public Metrics(Plugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - enabled = config.getBoolean("enabled", true); - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - - if (enabled) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.addProperty("pluginName", pluginName); // Append the name of the plugin - data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - JsonArray customCharts = new JsonArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JsonObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.add("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("onlineMode", onlineMode); - data.addProperty("bukkitVersion", bukkitVersion); - data.addProperty("bukkitName", bukkitName); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); - if (plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { // old bstats version compatibility - try { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); - if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); - jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); - pluginData.add(object); - } - } catch (ClassNotFoundException e) { - // minecraft version 1.14+ - if (logFailedRequests) { - this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); - } - continue; // continue looping since we cannot do any other thing. - } - } - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } - } - } catch (NoSuchFieldException ignored) { } - } - - data.add("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { - @Override - public void run() { - try { - // Send the data - sendData(plugin, data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data.toString()); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - InputStream inputStream = connection.getInputStream(); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - - StringBuilder builder = new StringBuilder(); - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - bufferedReader.close(); - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); - } - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JsonObject getRequestJsonObject() { - JsonObject chart = new JsonObject(); - chart.addProperty("chartId", chartId); - try { - JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.add("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JsonObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObject value = new JsonObject(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.addProperty(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - values.add(entryValues.getKey(), value); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JsonArray categoryValues = new JsonArray(); - categoryValues.add(entry.getValue()); - values.add(entry.getKey(), categoryValues); - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JsonArray categoryValues = new JsonArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(categoryValue); - } - values.add(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/Healthboard.java b/src/main/java/tk/shanebee/survival/tasks/Healthboard.java deleted file mode 100644 index 00048a3..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/Healthboard.java +++ /dev/null @@ -1,122 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.data.Board; -import tk.shanebee.survival.data.Info; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.util.Utils; - -public class Healthboard extends BukkitRunnable { - - private final Config config; - private final PlayerManager pm; - private final Player player; - private final PlayerData playerData; - private final Board board; - - // Board stuff - private boolean hunger; - private boolean thirst; - private boolean energy; - private boolean nutrients; - - public Healthboard(Survival plugin, Player player) { - this.config = plugin.getSurvivalConfig(); - this.pm = plugin.getPlayerManager(); - this.player = player; - this.playerData = plugin.getPlayerManager().getPlayerData(player); - this.board = Board.getBoard(player); - this.hunger = playerData.isInfoDisplayed(Info.HUNGER); - this.thirst = playerData.isInfoDisplayed(Info.THIRST); - this.energy = playerData.isInfoDisplayed(Info.ENERGY); - this.nutrients = playerData.isInfoDisplayed(Info.NUTRIENTS); - - this.board.setTitle(Utils.getColoredString(plugin.getLang().healthboard_title)); - - this.runTaskTimer(plugin, -1, 10); - } - - @Override - public void run() { - if (!player.isOnline()) { - this.cancel(); - return; - } - - GameMode mode = player.getGameMode(); - if (mode == GameMode.CREATIVE || mode == GameMode.SPECTATOR) { - // If the player is in creative/spectator and board is on, turn it off - if (board.isOn()) { - board.toggle(false); - } - } else { - // Else if player is in survival/adventure and board is off, turn it on - if (!board.isOn()) { - board.toggle(true); - } - } - - // Refresh board options - this.hunger = playerData.isInfoDisplayed(Info.HUNGER); - this.thirst = playerData.isInfoDisplayed(Info.THIRST); - this.energy = playerData.isInfoDisplayed(Info.ENERGY); - this.nutrients = playerData.isInfoDisplayed(Info.NUTRIENTS); - - // If all options on the board are disabled, turn board off - if (!hunger && !thirst && !energy && !nutrients) { - if (board.isOn()) { - board.toggle(false); - } - return; - } - - if (hunger) { - board.setLine(11, pm.ShowHunger(player).get(0)); - board.setLine(10, pm.ShowHunger(player).get(1)); - board.setLine(9, pm.ShowHunger(player).get(2)); - } else { - board.deleteLine(11); - board.deleteLine(10); - board.deleteLine(9); - } - - if (config.MECHANICS_THIRST_ENABLED && thirst) { - board.setLine(8, pm.ShowThirst(player).get(0)); - board.setLine(7, pm.ShowThirst(player).get(1)); - board.setLine(6, pm.ShowThirst(player).get(2)); - } else { - board.deleteLine(8); - board.deleteLine(7); - board.deleteLine(6); - } - - if (config.MECHANICS_ENERGY_ENABLED && energy) { - board.setLine(5, pm.showEnergy(player).get(0)); - board.setLine(4, pm.showEnergy(player).get(1)); - } else { - board.deleteLine(5); - board.deleteLine(4); - } - - if (config.MECHANICS_FOOD_DIVERSITY_ENABLED && nutrients) { - board.setLine(3, pm.ShowNutrients(player).get(0)); - board.setLine(2, pm.ShowNutrients(player).get(1)); - board.setLine(1, pm.ShowNutrients(player).get(2)); - } else { - board.deleteLine(3); - board.deleteLine(2); - board.deleteLine(1); - } - } - - @Override - public synchronized void cancel() throws IllegalStateException { - super.cancel(); - Board.removeBoard(player); - } -} diff --git a/src/main/java/tk/shanebee/survival/tasks/NutrientsAlert.java b/src/main/java/tk/shanebee/survival/tasks/NutrientsAlert.java deleted file mode 100644 index 66dadd3..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/NutrientsAlert.java +++ /dev/null @@ -1,47 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.Nutrient; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Lang; - -class NutrientsAlert extends BukkitRunnable { - - private final Lang lang; - private final PlayerManager playerManager; - - NutrientsAlert(Survival plugin) { - this.lang = plugin.getLang(); - final int ALERT_INTERVAL = plugin.getSurvivalConfig().MECHANICS_ALERT_INTERVAL; - this.playerManager = plugin.getPlayerManager(); - this.runTaskTimer(plugin, -1, ALERT_INTERVAL * 20); - } - - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - PlayerData playerData = playerManager.getPlayerData(player); - - if (playerData.getNutrient(Nutrient.CARBS) <= 480) { - player.sendMessage(ChatColor.DARK_GREEN + lang.carbohydrates_lack); - } - - if (playerData.getNutrient(Nutrient.SALTS) <= 180) { - player.sendMessage(ChatColor.BLUE + lang.vitamins_lack); - } - - if (playerData.getNutrient(Nutrient.PROTEIN) <= 120) { - player.sendMessage(ChatColor.DARK_RED + lang.protein_lack); - } - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/NutrientsDrain.java b/src/main/java/tk/shanebee/survival/tasks/NutrientsDrain.java deleted file mode 100644 index b9b230d..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/NutrientsDrain.java +++ /dev/null @@ -1,37 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.Nutrient; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.managers.StatusManager; - -class NutrientsDrain extends BukkitRunnable { - - private final PlayerManager playerManager; - - NutrientsDrain(Survival plugin) { - this.playerManager = plugin.getPlayerManager(); - this.runTaskTimer(plugin, -1, 1); - } - - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - if (player.getExhaustion() >= 4) { - PlayerData playerData = playerManager.getPlayerData(player); - - playerData.increaseNutrient(Nutrient.CARBS, -8); - playerData.increaseNutrient(Nutrient.PROTEIN, -2); - playerData.increaseNutrient(Nutrient.SALTS, -3); - } - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/NutrientsEffect.java b/src/main/java/tk/shanebee/survival/tasks/NutrientsEffect.java deleted file mode 100644 index c52f18f..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/NutrientsEffect.java +++ /dev/null @@ -1,125 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.data.Nutrient; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; - -class NutrientsEffect extends BukkitRunnable { - - private final Config config; - private final PlayerManager playerManager; - private PotionEffect SALTS_NORMAL = null; - private PotionEffect SALTS_HARD = null; - private PotionEffect PROTEIN_NORMAL = null; - private PotionEffect PROTEIN_HARD = null; - - NutrientsEffect(Survival plugin) { - this.config = plugin.getSurvivalConfig(); - this.playerManager = plugin.getPlayerManager(); - loadEffects(); - this.runTaskTimer(plugin, -1, 320); - } - - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - PlayerData playerData = playerManager.getPlayerData(player); - - if (playerData.getNutrient(Nutrient.CARBS) <= 0) { - switch (player.getWorld().getDifficulty()) { - case EASY: - player.setExhaustion(player.getExhaustion() + Math.max(config.MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_EASY, 0)); - break; - case NORMAL: - player.setExhaustion(player.getExhaustion() + Math.max(config.MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_MEDIUM, 0)); - break; - case HARD: - player.setExhaustion(player.getExhaustion() + Math.max(config.MECHANICS_FOOD_EFFECTS_CARBS_EX_AMP_HARD, 0)); - break; - default: - } - } - - if (playerData.getNutrient(Nutrient.SALTS) <= 0) { - player.setExhaustion(player.getExhaustion() + Math.max(config.MECHANICS_FOOD_EFFECTS_SALTS_EX_AMP, 0)); - switch (player.getWorld().getDifficulty()) { - case NORMAL: - if (SALTS_NORMAL != null) { - player.addPotionEffect(SALTS_NORMAL, true); - } - break; - case HARD: - if (SALTS_HARD != null) { - player.addPotionEffect(SALTS_HARD, true); - } - break; - default: - } - } - - if (playerData.getNutrient(Nutrient.PROTEIN) <= 0) { - player.setExhaustion(player.getExhaustion() + Math.max(config.MECHANICS_FOOD_EFFECTS_PROTEIN_EX_AMP, 0)); - switch (player.getWorld().getDifficulty()) { - case NORMAL: - if (PROTEIN_NORMAL != null) { - player.addPotionEffect(PROTEIN_NORMAL, true); - } - break; - case HARD: - if (PROTEIN_HARD != null) { - player.addPotionEffect(PROTEIN_HARD, true); - } - break; - default: - } - } - } - } - } - - private void loadEffects() { - PotionEffectType s_normal_type = getType(config.MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_EFFECT); - if (s_normal_type != null) { - int s_normal_amp = config.MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_AMP; - int s_normal_dur = config.MECHANICS_FOOD_EFFECTS_SALTS_SE_NORMAL_DURATION; - SALTS_NORMAL = new PotionEffect(s_normal_type, s_normal_dur * 20, s_normal_amp); - } - PotionEffectType s_hard_type = getType(config.MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_EFFECT); - if (s_hard_type != null) { - int s_hard_amp = config.MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_AMP; - int s_hard_dur = config.MECHANICS_FOOD_EFFECTS_SALTS_SE_HARD_DURATION; - SALTS_HARD = new PotionEffect(s_hard_type, s_hard_dur * 20, s_hard_amp); - } - - PotionEffectType p_normal_type = getType(config.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_EFFECT); - if (p_normal_type != null) { - int p_normal_amp = config.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_AMP; - int p_normal_dur = config.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_NORMAL_DURATION; - PROTEIN_NORMAL = new PotionEffect(p_normal_type, p_normal_dur * 20, p_normal_amp); - } - PotionEffectType p_hard_type = getType(config.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_EFFECT); - if (p_hard_type != null) { - int p_hard_amp = config.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_AMP; - int p_hard_dur = config.MECHANICS_FOOD_EFFECTS_PROTEIN_SE_HARD_DURATION; - PROTEIN_HARD = new PotionEffect(p_hard_type, p_hard_dur * 20, p_hard_amp); - } - } - - private PotionEffectType getType(String potionType) { - try { - return PotionEffectType.getByName(potionType); - } catch (IllegalArgumentException ex) { - return null; - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/TaskManager.java b/src/main/java/tk/shanebee/survival/tasks/TaskManager.java deleted file mode 100644 index d80c5d4..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/TaskManager.java +++ /dev/null @@ -1,42 +0,0 @@ -package tk.shanebee.survival.tasks; - -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; - -/** - * Internal task manager - */ -public class TaskManager { - - public TaskManager(Survival plugin) { - final int ALERT_INTERVAL = plugin.getSurvivalConfig().MECHANICS_ALERT_INTERVAL; - Config config = plugin.getSurvivalConfig(); - if (config.MECHANICS_ENERGY_ENABLED) { - new EnergyDrain(plugin); - } - if (config.MECHANICS_THIRST_ENABLED) { - new ThirstDrain(plugin); - if (!config.MECHANICS_STATUS_SCOREBOARD && ALERT_INTERVAL > 0) { - new ThirstAlert(plugin); - } - } - if (config.MECHANICS_FOOD_DIVERSITY_ENABLED) { - new NutrientsDrain(plugin); - new NutrientsEffect(plugin); - if (!config.MECHANICS_STATUS_SCOREBOARD && ALERT_INTERVAL > 0) { - new NutrientsAlert(plugin); - } - } - - if (config.MECHANICS_WEATHER_ENABLED) { - new WeatherTask(plugin); - } - if (config.MECHANICS_THIRST_DRAIN_NETHER > 0) { - new ThirstDrainNether(plugin); - } - if (config.MECHANICS_THIRST_DRAIN_HEAT > 0) { - new ThirstDrainHeat(plugin); - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/ThirstAlert.java b/src/main/java/tk/shanebee/survival/tasks/ThirstAlert.java deleted file mode 100644 index 99aaee7..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/ThirstAlert.java +++ /dev/null @@ -1,40 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.config.Lang; - -class ThirstAlert extends BukkitRunnable { - - private final PlayerManager playerManager; - private final Lang lang; - - ThirstAlert(Survival plugin) { - this.playerManager = plugin.getPlayerManager(); - this.lang = plugin.getLang(); - final int ALERT_INTERVAL = plugin.getSurvivalConfig().MECHANICS_ALERT_INTERVAL; - this.runTaskTimer(plugin, -1, ALERT_INTERVAL * 20); - } - @Override - public void run() { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - PlayerData playerData = playerManager.getPlayerData(player); - int hunger = player.getFoodLevel(); - if (hunger <= 6) { - player.sendMessage(ChatColor.GOLD + lang.starved_eat); - } - if (playerData.getThirst() <= 6) { - player.sendMessage(ChatColor.AQUA + lang.dehydrated_drink); - } - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/ThirstDrain.java b/src/main/java/tk/shanebee/survival/tasks/ThirstDrain.java deleted file mode 100644 index bbe872f..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/ThirstDrain.java +++ /dev/null @@ -1,73 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Config; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.events.ThirstLevelChangeEvent; -import tk.shanebee.survival.managers.PlayerManager; - -import java.util.Random; - -class ThirstDrain extends BukkitRunnable { - - private final PlayerManager playerManager; - private final double drain; - private final double damage; - - ThirstDrain(Survival plugin) { - this.playerManager = plugin.getPlayerManager(); - Config config = plugin.getSurvivalConfig(); - this.drain = config.MECHANICS_THIRST_DRAIN_RATE; - this.damage = config.MECHANICS_THIRST_DAMAGE_RATE; - this.runTaskTimer(plugin, -1, 1); - } - - @Override - public void run() { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) { - // Drain player's thirst when exhaustion is high - if (player.getExhaustion() >= 4) { - PlayerData playerData = playerManager.getPlayerData(player); - - Random rand = new Random(); - int change = rand.nextDouble() <= this.drain ? 1 : 0; - - // Prevent calling thirst event if there is no change - if (change == 0) continue; - - // Call thirst level change event - ThirstLevelChangeEvent event = new ThirstLevelChangeEvent(player, change, playerData.getThirst() - change); - Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled()) { - playerData.increaseThirst(-change); - } - } - // Damage player when thirst is too low - PlayerData playerData = playerManager.getPlayerData(player); - - if (playerData.getThirst() <= 0) { - switch (player.getWorld().getDifficulty()) { - case EASY: - if (player.getHealth() > 10) - player.damage(this.damage); - break; - case NORMAL: - if (player.getHealth() > 1) - player.damage(this.damage); - break; - case HARD: - player.damage(this.damage); - break; - default: - } - } - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/ThirstDrainHeat.java b/src/main/java/tk/shanebee/survival/tasks/ThirstDrainHeat.java deleted file mode 100644 index e243747..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/ThirstDrainHeat.java +++ /dev/null @@ -1,42 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.World.Environment; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.events.ThirstLevelChangeEvent; -import tk.shanebee.survival.managers.PlayerManager; -import tk.shanebee.survival.util.Utils; - -class ThirstDrainHeat extends BukkitRunnable { - - private final PlayerManager playerManager; - - ThirstDrainHeat(Survival plugin) { - this.playerManager = plugin.getPlayerManager(); - this.runTaskTimer(plugin, 0, 20 * plugin.getSurvivalConfig().MECHANICS_THIRST_DRAIN_HEAT); - } - - @Override - public void run() { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - if (player.getGameMode() != GameMode.SURVIVAL && player.getGameMode() != GameMode.ADVENTURE) continue; - if (player.getWorld().getEnvironment() != Environment.NORMAL) continue; - if (player.getLocation().getBlock().getTemperature() < 1.0) continue; - if (!Utils.isAtHighest(player)) continue; - - PlayerData playerData = playerManager.getPlayerData(player); - int change = 1; - // Call thirst level change event - ThirstLevelChangeEvent event = new ThirstLevelChangeEvent(player, change, playerData.getThirst() - change); - Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled()) { - playerData.increaseThirst(-change); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/ThirstDrainNether.java b/src/main/java/tk/shanebee/survival/tasks/ThirstDrainNether.java deleted file mode 100644 index 7218c35..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/ThirstDrainNether.java +++ /dev/null @@ -1,39 +0,0 @@ -package tk.shanebee.survival.tasks; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.World.Environment; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.events.ThirstLevelChangeEvent; -import tk.shanebee.survival.managers.PlayerManager; - -class ThirstDrainNether extends BukkitRunnable { - - private final PlayerManager playerManager; - - ThirstDrainNether(Survival plugin) { - this.playerManager = plugin.getPlayerManager(); - this.runTaskTimer(plugin, 0, 20 * plugin.getSurvivalConfig().MECHANICS_THIRST_DRAIN_NETHER); - } - - @Override - public void run() { - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - if (player.getGameMode() != GameMode.SURVIVAL && player.getGameMode() != GameMode.ADVENTURE) continue; - if (player.getWorld().getEnvironment() != Environment.NETHER) continue; - - PlayerData playerData = playerManager.getPlayerData(player); - int change = 1; - // Call thirst level change event - ThirstLevelChangeEvent event = new ThirstLevelChangeEvent(player, change, playerData.getThirst() - change); - Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled()) { - playerData.increaseThirst(-change); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/tool/BlazeSwordEffects.java b/src/main/java/tk/shanebee/survival/tasks/tool/BlazeSwordEffects.java deleted file mode 100644 index 61fb88e..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/tool/BlazeSwordEffects.java +++ /dev/null @@ -1,42 +0,0 @@ -package tk.shanebee.survival.tasks.tool; - -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -public class BlazeSwordEffects extends BukkitRunnable { - - private final Survival plugin; - private final PotionEffect FLAME; - - public BlazeSwordEffects(Survival plugin) { - this.plugin = plugin; - this.FLAME = new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 20, 0, false); - this.runTaskTimer(plugin, 1, 10); - } - - @Override - public void run() { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (ItemManager.compare(player.getInventory().getItemInMainHand(), Item.BLAZE_SWORD)) { - player.removePotionEffect(PotionEffectType.FIRE_RESISTANCE); - player.addPotionEffect(this.FLAME); - Location particleLoc = player.getLocation(); - particleLoc.setY(particleLoc.getY() + 1); - assert particleLoc.getWorld() != null; - particleLoc.getWorld().spawnParticle(Particle.FLAME, particleLoc, 10, 0.5, 0.5, 0.5); - - player.setFireTicks(20); - if (player.getHealth() > 14) - player.setHealth(14); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/tool/BlazeSwordSound.java b/src/main/java/tk/shanebee/survival/tasks/tool/BlazeSwordSound.java deleted file mode 100644 index 8e0af10..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/tool/BlazeSwordSound.java +++ /dev/null @@ -1,33 +0,0 @@ -package tk.shanebee.survival.tasks.tool; - -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -import java.util.Random; - -public class BlazeSwordSound extends BukkitRunnable { - - private final Survival plugin; - - public BlazeSwordSound(Survival plugin) { - this.plugin = plugin; - this.runTaskTimer(plugin, 1, 50); - } - - @Override - public void run() { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (ItemManager.compare(player.getInventory().getItemInMainHand(), Item.BLAZE_SWORD)) { - Random rand = new Random(); - assert player.getLocation().getWorld() != null; - player.getLocation().getWorld().playSound( - player.getLocation(), Sound.ENTITY_BLAZE_AMBIENT, 1.0F, rand.nextFloat() * 0.4F + 0.8F); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/tool/GiantBlade.java b/src/main/java/tk/shanebee/survival/tasks/tool/GiantBlade.java deleted file mode 100644 index f554abc..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/tool/GiantBlade.java +++ /dev/null @@ -1,89 +0,0 @@ -package tk.shanebee.survival.tasks.tool; - -import com.google.common.collect.ImmutableSet; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.data.PlayerData; -import tk.shanebee.survival.data.Stat; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; -import tk.shanebee.survival.managers.PlayerManager; - -public class GiantBlade extends BukkitRunnable { - - private final Survival plugin; - private final PlayerManager playerManager; - private final ImmutableSet MAIN_SET; - private final ImmutableSet OFF_SET; - private final PotionEffect DAMAGE; - private final PotionEffect SLOW; - private final PotionEffect JUMP; - - public GiantBlade(Survival plugin) { - this.plugin = plugin; - this.playerManager = plugin.getPlayerManager(); - this.MAIN_SET = ImmutableSet.builder() - .add(Material.GOLDEN_HOE).add(Material.GOLDEN_AXE).build(); - this.OFF_SET = ImmutableSet.builder() - .add(Material.WOODEN_AXE).add(Material.WOODEN_SWORD).add(Material.WOODEN_PICKAXE) - .add(Material.WOODEN_SHOVEL).add(Material.WOODEN_HOE).add(Material.STONE_AXE) - .add(Material.STONE_SWORD).add(Material.STONE_PICKAXE).add(Material.STONE_SHOVEL) - .add(Material.STONE_HOE).add(Material.IRON_AXE).add(Material.IRON_SWORD) - .add(Material.IRON_PICKAXE).add(Material.IRON_SHOVEL).add(Material.IRON_HOE) - .add(Material.GOLDEN_AXE).add(Material.GOLDEN_SWORD).add(Material.GOLDEN_PICKAXE) - .add(Material.GOLDEN_SHOVEL).add(Material.GOLDEN_HOE).add(Material.DIAMOND_AXE) - .add(Material.DIAMOND_SWORD).add(Material.DIAMOND_PICKAXE).add(Material.DIAMOND_SHOVEL) - .add(Material.DIAMOND_HOE).add(Material.BOW).build(); - - this.DAMAGE = new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20, 1, false); - this.SLOW = new PotionEffect(PotionEffectType.SLOW, 20, 6, true); - this.JUMP = new PotionEffect(PotionEffectType.JUMP, 20, 199, true); - - this.runTaskTimer(plugin, 1, 10); - } - - @Override - public void run() { //TODO this guy needs some serious work - for (Player player : plugin.getServer().getOnlinePlayers()) { - ItemStack mainItem = player.getInventory().getItemInMainHand(); - ItemStack offItem = player.getInventory().getItemInOffHand(); - Material mainType = mainItem.getType(); - Material offType = offItem.getType(); - - if (ItemManager.compare(mainItem, Item.ENDER_GIANT_BLADE)) { - Location particleLoc = player.getLocation(); - particleLoc.setY(particleLoc.getY() + 1); - assert particleLoc.getWorld() != null; - particleLoc.getWorld().spawnParticle(Particle.CRIT_MAGIC, particleLoc, 10, 0.5, 0.5, 0.5); - } - - if (ItemManager.compare(offItem, Item.ENDER_GIANT_BLADE)) { - player.removePotionEffect(PotionEffectType.DAMAGE_RESISTANCE); - player.addPotionEffect(this.DAMAGE); - Location particleLoc = player.getLocation(); - particleLoc.setY(particleLoc.getY() + 1); - assert particleLoc.getWorld() != null; - particleLoc.getWorld().spawnParticle(Particle.CRIT_MAGIC, particleLoc, 10, 0.5, 0.5, 0.5); - } - - PlayerData playerData = playerManager.getPlayerData(player); - if ((MAIN_SET.contains(mainType) && OFF_SET.contains(offType)) || (MAIN_SET.contains(offType) && OFF_SET.contains(mainType))) { - player.removePotionEffect(PotionEffectType.SLOW); - player.addPotionEffect(this.SLOW); - player.removePotionEffect(PotionEffectType.JUMP); - player.addPotionEffect(this.JUMP); - playerData.setStat(Stat.DUAL_WIELD, 1); - } else { - playerData.setStat(Stat.DUAL_WIELD, 0); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/tool/ObsidianMace.java b/src/main/java/tk/shanebee/survival/tasks/tool/ObsidianMace.java deleted file mode 100644 index 9bc9bb9..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/tool/ObsidianMace.java +++ /dev/null @@ -1,37 +0,0 @@ -package tk.shanebee.survival.tasks.tool; - -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -public class ObsidianMace extends BukkitRunnable { - - private final Survival plugin; - - public ObsidianMace(Survival plugin) { - this.plugin = plugin; - this.runTaskTimer(plugin, 1, 10); - } - - @Override - public void run() { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (ItemManager.compare(player.getInventory().getItemInMainHand(), Item.OBSIDIAN_MACE)) { - player.removePotionEffect(PotionEffectType.SLOW); - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 100, 1, false)); - Location particleLoc = player.getLocation(); - particleLoc.setY(particleLoc.getY() + 1); - assert particleLoc.getWorld() != null; - particleLoc.getWorld().spawnParticle(Particle.CRIT, particleLoc, 10, 0.5, 0.5, 0.5); - particleLoc.getWorld().spawnParticle(Particle.PORTAL, particleLoc, 20, 0.5, 0.5, 0.5); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/tool/QuartzPickaxe.java b/src/main/java/tk/shanebee/survival/tasks/tool/QuartzPickaxe.java deleted file mode 100644 index 87cb99d..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/tool/QuartzPickaxe.java +++ /dev/null @@ -1,30 +0,0 @@ -package tk.shanebee.survival.tasks.tool; - -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -public class QuartzPickaxe extends BukkitRunnable { - - private final Survival plugin; - - public QuartzPickaxe(Survival plugin) { - this.plugin = plugin; - this.runTaskTimer(plugin, 1, 10); - } - - @Override - public void run() { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (ItemManager.compare(player.getInventory().getItemInMainHand(), Item.QUARTZ_PICKAXE)) { - player.removePotionEffect(PotionEffectType.FAST_DIGGING); - player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 20, 9, false)); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/tasks/tool/Valkyrie.java b/src/main/java/tk/shanebee/survival/tasks/tool/Valkyrie.java deleted file mode 100644 index 1ca34d1..0000000 --- a/src/main/java/tk/shanebee/survival/tasks/tool/Valkyrie.java +++ /dev/null @@ -1,32 +0,0 @@ -package tk.shanebee.survival.tasks.tool; - -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -public class Valkyrie extends BukkitRunnable { - - private final Survival plugin; - - public Valkyrie(Survival plugin) { - this.plugin = plugin; - this.runTaskTimer(plugin, 1, 10); - } - - @Override - public void run() { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (ItemManager.compare(player.getInventory().getItemInMainHand(), Item.VALKYRIES_AXE)) { - Location particleLoc = player.getLocation(); - particleLoc.setY(particleLoc.getY() + 1); - assert particleLoc.getWorld() != null; - particleLoc.getWorld().spawnParticle(Particle.CRIT_MAGIC, particleLoc, 10, 0.5, 0.5, 0.5); - } - } - } - -} diff --git a/src/main/java/tk/shanebee/survival/util/Utils.java b/src/main/java/tk/shanebee/survival/util/Utils.java deleted file mode 100644 index 0589310..0000000 --- a/src/main/java/tk/shanebee/survival/util/Utils.java +++ /dev/null @@ -1,880 +0,0 @@ -package tk.shanebee.survival.util; - -import com.google.common.collect.ImmutableSet; -import org.bukkit.*; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.metadata.Metadatable; -import tk.shanebee.survival.Survival; -import tk.shanebee.survival.config.Lang; -import tk.shanebee.survival.managers.ItemManager; -import tk.shanebee.survival.item.Item; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@SuppressWarnings({"WeakerAccess", "unused"}) -public class Utils { - - private static final Pattern HEX_PATTERN = Pattern.compile("<#([A-Fa-f0-9]){6}>"); - private static final ImmutableSet CONCRETE_BLOCKS; - private static final ImmutableSet CONCRETE_POWDER; - private final static ImmutableSet GLAZED_TERRACOTTA; - private final static ImmutableSet TERRACOTTA; - private final static ImmutableSet NATURAL_ORE_BLOCK; - private final static ImmutableSet ORE_BLOCK; - private final static ImmutableSet COOKING_BLOCK; - private final static ImmutableSet UTILITY_BLOCK; - private final static ImmutableSet STORAGE_BLOCK; - private final static ImmutableSet STONE_TYPE_BLOCK; - private final static ImmutableSet FARMABLE; - private final static ImmutableSet SHOVEL; - private final static ImmutableSet REQUIRES_SHOVEL; - private final static ImmutableSet PICKAXE; - private final static ImmutableSet REQUIRES_PICKAXE; - private final static ImmutableSet AXE; - private final static ImmutableSet REQUIRES_AXE; - private final static ImmutableSet REQUIRES_SHEARS; - private final static ImmutableSet REQUIRES_HAMMER; - - static { - CONCRETE_BLOCKS = ImmutableSet.builder() - .add(Material.CYAN_CONCRETE) - .add(Material.BLACK_CONCRETE) - .add(Material.BLUE_CONCRETE) - .add(Material.BROWN_CONCRETE) - .add(Material.GRAY_CONCRETE) - .add(Material.GREEN_CONCRETE) - .add(Material.LIGHT_BLUE_CONCRETE) - .add(Material.LIGHT_GRAY_CONCRETE) - .add(Material.LIME_CONCRETE) - .add(Material.MAGENTA_CONCRETE) - .add(Material.ORANGE_CONCRETE) - .add(Material.PINK_CONCRETE) - .add(Material.PURPLE_CONCRETE) - .add(Material.RED_CONCRETE) - .add(Material.WHITE_CONCRETE) - .add(Material.YELLOW_CONCRETE) - .build(); - - CONCRETE_POWDER = ImmutableSet.builder() - .add(Material.BLACK_CONCRETE_POWDER) - .add(Material.BLUE_CONCRETE_POWDER) - .add(Material.BROWN_CONCRETE_POWDER) - .add(Material.CYAN_CONCRETE_POWDER) - .add(Material.GRAY_CONCRETE_POWDER) - .add(Material.GREEN_CONCRETE_POWDER) - .add(Material.LIME_CONCRETE_POWDER) - .add(Material.MAGENTA_CONCRETE_POWDER) - .add(Material.ORANGE_CONCRETE_POWDER) - .add(Material.PINK_CONCRETE_POWDER) - .add(Material.PURPLE_CONCRETE_POWDER) - .add(Material.RED_CONCRETE_POWDER) - .add(Material.WHITE_CONCRETE_POWDER) - .add(Material.YELLOW_CONCRETE_POWDER) - .add(Material.LIGHT_BLUE_CONCRETE_POWDER) - .add(Material.LIGHT_GRAY_CONCRETE_POWDER) - .build(); - - GLAZED_TERRACOTTA = ImmutableSet.builder() - .add(Material.BLACK_GLAZED_TERRACOTTA) - .add(Material.BLUE_GLAZED_TERRACOTTA) - .add(Material.BROWN_GLAZED_TERRACOTTA) - .add(Material.CYAN_GLAZED_TERRACOTTA) - .add(Material.GRAY_GLAZED_TERRACOTTA) - .add(Material.GREEN_GLAZED_TERRACOTTA) - .add(Material.LIGHT_BLUE_GLAZED_TERRACOTTA) - .add(Material.LIME_GLAZED_TERRACOTTA) - .add(Material.MAGENTA_GLAZED_TERRACOTTA) - .add(Material.ORANGE_GLAZED_TERRACOTTA) - .add(Material.PINK_GLAZED_TERRACOTTA) - .add(Material.PURPLE_GLAZED_TERRACOTTA) - .add(Material.RED_GLAZED_TERRACOTTA) - .add(Material.LIGHT_GRAY_GLAZED_TERRACOTTA) - .add(Material.WHITE_GLAZED_TERRACOTTA) - .add(Material.YELLOW_GLAZED_TERRACOTTA) - .build(); - - TERRACOTTA = ImmutableSet.builder() - .add(Material.BLACK_TERRACOTTA) - .add(Material.BLUE_TERRACOTTA) - .add(Material.BROWN_TERRACOTTA) - .add(Material.CYAN_TERRACOTTA) - .add(Material.GRAY_TERRACOTTA) - .add(Material.GREEN_TERRACOTTA) - .add(Material.LIGHT_BLUE_TERRACOTTA) - .add(Material.LIME_TERRACOTTA) - .add(Material.MAGENTA_TERRACOTTA) - .add(Material.ORANGE_TERRACOTTA) - .add(Material.PINK_TERRACOTTA) - .add(Material.PURPLE_TERRACOTTA) - .add(Material.RED_TERRACOTTA) - .add(Material.LIGHT_GRAY_TERRACOTTA) - .add(Material.WHITE_TERRACOTTA) - .add(Material.YELLOW_TERRACOTTA) - .build(); - - NATURAL_ORE_BLOCK = ImmutableSet.builder() - .add(Material.COAL_ORE) - .add(Material.DIAMOND_ORE) - .add(Material.EMERALD_ORE) - .add(Material.GOLD_ORE) - .add(Material.IRON_ORE) - .add(Material.LAPIS_ORE) - .add(Material.NETHER_QUARTZ_ORE) - .add(Material.REDSTONE_ORE) - .add(Material.NETHER_GOLD_ORE) - .add(Material.ANCIENT_DEBRIS) - .add(Material.GILDED_BLACKSTONE) - .build(); - - ORE_BLOCK = ImmutableSet.builder() - .add(Material.COAL_BLOCK) - .add(Material.DIAMOND_BLOCK) - .add(Material.EMERALD_BLOCK) - .add(Material.GOLD_BLOCK) - .add(Material.IRON_BLOCK) - .add(Material.LAPIS_BLOCK) - .add(Material.QUARTZ_BLOCK) - .add(Material.REDSTONE_BLOCK) - .add(Material.NETHERITE_BLOCK) - .build(); - - COOKING_BLOCK = ImmutableSet.builder() - .add(Material.FURNACE) - .add(Material.BLAST_FURNACE) - .add(Material.SMOKER) - .build(); - - UTILITY_BLOCK = ImmutableSet.builder() - .add(Material.CARTOGRAPHY_TABLE) - .add(Material.FLETCHING_TABLE) - .add(Material.LECTERN) - .add(Material.LOOM) - .add(Material.STONECUTTER) - .add(Material.GRINDSTONE) - .add(Material.SMITHING_TABLE) - .add(Material.ANVIL) - .add(Material.ENCHANTING_TABLE) - .add(Material.JUKEBOX) - .add(Material.NOTE_BLOCK) - .add(Material.BREWING_STAND) - .add(Material.CAULDRON) - .add(Material.COMPOSTER) - .add(Material.RESPAWN_ANCHOR) - .add(Material.LODESTONE) - .build(); - - STORAGE_BLOCK = ImmutableSet.builder() - .add(Material.CHEST) - .add(Material.ENDER_CHEST) - .add(Material.TRAPPED_CHEST) - .add(Material.BARREL) - .build(); - - STONE_TYPE_BLOCK = ImmutableSet.builder() - .add(Material.STONE) - .add(Material.COBBLESTONE) - .add(Material.MOSSY_COBBLESTONE) - .add(Material.INFESTED_COBBLESTONE) - .add(Material.ANDESITE) - .add(Material.POLISHED_ANDESITE) - .add(Material.DIORITE) - .add(Material.POLISHED_DIORITE) - .add(Material.GRANITE) - .add(Material.POLISHED_GRANITE) - .add(Material.BRICKS) - .add(Material.NETHER_BRICKS) - .add(Material.SANDSTONE) - .add(Material.CHISELED_SANDSTONE) - .add(Material.SMOOTH_SANDSTONE) - .add(Material.CUT_SANDSTONE) - .add(Material.RED_SANDSTONE) - .add(Material.CHISELED_RED_SANDSTONE) - .add(Material.CUT_RED_SANDSTONE) - .add(Material.SMOOTH_RED_SANDSTONE) - .add(Material.PRISMARINE) - .add(Material.PRISMARINE_BRICKS) - .add(Material.DARK_PRISMARINE) - .add(Material.NETHERRACK) - .add(Material.END_STONE) - .add(Material.END_STONE_BRICKS) - .add(Material.PURPUR_BLOCK) - .add(Material.PURPUR_PILLAR) - // Nether update blocks - .add(Material.BASALT) - .add(Material.POLISHED_BASALT) - .add(Material.BLACKSTONE) - .add(Material.POLISHED_BLACKSTONE) - .add(Material.CHISELED_POLISHED_BLACKSTONE) - .add(Material.CHISELED_NETHER_BRICKS) - .add(Material.CRACKED_NETHER_BRICKS) - .add(Material.QUARTZ_BRICKS) - .build(); - - FARMABLE = ImmutableSet.builder() - .add(Material.MELON) - .add(Material.MELON_STEM) - .add(Material.PUMPKIN) - .add(Material.PUMPKIN_STEM) - .add(Material.CHORUS_FLOWER) - .add(Material.CHORUS_PLANT) - .add(Material.CARROTS) - .add(Material.POTATOES) - .add(Material.BEETROOTS) - .add(Material.WHEAT) - .add(Material.SWEET_BERRY_BUSH) - .add(Material.COCOA) - .build(); - - SHOVEL = ImmutableSet.builder() - .add(Material.STONE_SHOVEL) - .add(Material.IRON_SHOVEL) - .add(Material.DIAMOND_SHOVEL) - .add(Material.GOLDEN_SHOVEL) - .add(Material.WOODEN_SHOVEL) - .add(Material.NETHERITE_SHOVEL) - .build(); - - REQUIRES_SHOVEL = ImmutableSet.builder() - .add(Material.GRASS_BLOCK) - .add(Material.DIRT) - .add(Material.PODZOL) - .add(Material.COARSE_DIRT) - .add(Material.GRASS_PATH) - .add(Material.FARMLAND) - .add(Material.SOUL_SAND) - .add(Material.SAND) - .add(Material.RED_SAND) - .add(Material.CLAY) - .add(Material.MYCELIUM) - .add(Material.SNOW) - .add(Material.SNOW_BLOCK) - .add(Material.SOUL_SOIL) - .build(); - - PICKAXE = ImmutableSet.builder() - .add(Material.GOLDEN_PICKAXE) - .add(Material.WOODEN_PICKAXE) - .add(Material.DIAMOND_PICKAXE) - .add(Material.IRON_PICKAXE) - .add(Material.STONE_PICKAXE) - .add(Material.NETHERITE_PICKAXE) - .build(); - - REQUIRES_PICKAXE = ImmutableSet.builder() - .add(Material.NETHER_BRICK_FENCE) - .add(Material.NETHER_BRICKS) - .add(Material.RED_NETHER_BRICKS) - .add(Material.SPAWNER) - .add(Material.SEA_LANTERN) - .add(Material.GLOWSTONE) - .add(Material.END_ROD) - .add(Material.DISPENSER) - .add(Material.DROPPER) - .add(Material.OBSERVER) - .add(Material.PISTON) - .add(Material.PISTON_HEAD) - .add(Material.STICKY_PISTON) - .add(Material.MOVING_PISTON) - .add(Material.ENCHANTING_TABLE) - .add(Material.ANVIL) - .add(Material.GRINDSTONE) - .add(Material.STONECUTTER) - .add(Material.ENDER_CHEST) - .add(Material.HOPPER) - .add(Material.CAULDRON) - .add(Material.BREWING_STAND) - .add(Material.STONE_PRESSURE_PLATE) - .add(Material.HEAVY_WEIGHTED_PRESSURE_PLATE) - .add(Material.LIGHT_WEIGHTED_PRESSURE_PLATE) - .add(Material.BEACON) - .add(Material.OBSIDIAN) - .add(Material.IRON_TRAPDOOR) - .build(); - - AXE = ImmutableSet.builder() - .add(Material.WOODEN_AXE) - .add(Material.STONE_AXE) - .add(Material.GOLDEN_AXE) - .add(Material.IRON_AXE) - .add(Material.DIAMOND_AXE) - .add(Material.NETHERITE_AXE) - .build(); - - REQUIRES_AXE = ImmutableSet.builder() - .add(Material.CHEST) - .add(Material.TRAPPED_CHEST) - .add(Material.BARREL) - .add(Material.CRAFTING_TABLE) - .add(Material.CARTOGRAPHY_TABLE) - .add(Material.FLETCHING_TABLE) - .add(Material.SMITHING_TABLE) - .add(Material.LOOM) - .add(Material.LECTERN) - .add(Material.CAMPFIRE) - .add(Material.COMPOSTER) - .add(Material.BOOKSHELF) - .add(Material.LADDER) - .add(Material.JUKEBOX) - .add(Material.NOTE_BLOCK) - .add(Material.DAYLIGHT_DETECTOR) - .add(Material.SCAFFOLDING) - .build(); - - REQUIRES_SHEARS = ImmutableSet.builder() - .add(Material.COBWEB) - .add(Material.TRIPWIRE) - .add(Material.TNT) - .add(Material.MUSHROOM_STEM) - .build(); - - REQUIRES_HAMMER = ImmutableSet.builder() - .add(Material.BOOKSHELF) - .add(Material.LADDER) - .add(Material.SEA_LANTERN) - .add(Material.GLOWSTONE) - .add(Material.END_ROD) - .add(Material.DISPENSER) - .add(Material.DROPPER) - .add(Material.HOPPER) - .add(Material.STONE_PRESSURE_PLATE) - .add(Material.LIGHT_WEIGHTED_PRESSURE_PLATE) - .add(Material.HEAVY_WEIGHTED_PRESSURE_PLATE) - .add(Material.DAYLIGHT_DETECTOR) - .add(Material.PISTON) - .add(Material.STICKY_PISTON) - .add(Material.REDSTONE_LAMP) - .add(Material.REPEATER) - .add(Material.COMPARATOR) - .add(Material.TRIPWIRE_HOOK) - .add(Material.BEACON) - .add(Material.IRON_BARS) - .add(Material.SCAFFOLDING) - .build(); - } - - /** Check if a material is concrete - * @param material Material to check - * @return True if material is concrete - */ - public static boolean isConcrete(Material material) { - return CONCRETE_BLOCKS.contains(material); - } - - /** Check if a material is concrete powder - * @param material Material to check - * @return True if material is concrete powder - */ - public static boolean isConcretePowder(Material material) { - return CONCRETE_POWDER.contains(material); - } - - /** Check if a material is glazed terracotta - * @param material Material to check - * @return True if material is glazed terracotta - */ - public static boolean isGlazedTerracotta(Material material) { - return GLAZED_TERRACOTTA.contains(material); - } - - /** Check if a material is terracotta - * @param material Material to check - * @return True if material is terracotta - */ - public static boolean isTerracotta(Material material) { - return TERRACOTTA.contains(material); - } - - /** Check if a material is a natural ore block - *

ie: coal ore, diamond ore, iron ore

- * @param material Material to check - * @return True if material is natural ore block - */ - public static boolean isNaturalOreBlock(Material material) { - return NATURAL_ORE_BLOCK.contains(material); - } - - /** Check if a material is an ore block - *

ie: coal block, diamond block, iron block

- * @param material Material to check - * @return True if material is ore block - */ - public static boolean isOreBlock(Material material) { - return ORE_BLOCK.contains(material); - } - - /** Check if a material is a cooking block - *

ie: furnace, blast furnace, smoker

- * @param material Material to check - * @return True if material is cooking block - */ - public static boolean isCookingBlock(Material material) { - return COOKING_BLOCK.contains(material); - } - - /** Check if a material is a utility block - *

ie: cartography table, grindstone, anvil

- * @param material Material to check - * @return True if material is utility block - */ - public static boolean isUtilityBlock(Material material) { - return UTILITY_BLOCK.contains(material); - } - - /** Check if a material is a shulker box - * @param material Material to check - * @return True if material is shulker box - */ - public static boolean isShulkerBox(Material material) { - return Tag.SHULKER_BOXES.isTagged(material); - } - - /** Check if a material is a storage block - *

ie: chest, ender chest, barrel

- * @param material Material to check - * @return True if material is storage block - */ - public static boolean isStorageBlock(Material material) { - return STORAGE_BLOCK.contains(material); - } - - /** Check if a material is stone block type - * @param material Material to check - * @return True if material is stone block type - */ - public static boolean isStoneTypeBlock(Material material) { - if (STONE_TYPE_BLOCK.contains(material)) return true; - if (isNonWoodSlab(material)) return true; - if (isNonWoodStairs(material)) return true; - return Tag.STONE_BRICKS.isTagged(material) || Tag.WALLS.isTagged(material); - } - - /** Check if a material is a non wood door - * @param material Material to check - * @return True if material is non wood door - */ - public static boolean isNonWoodDoor(Material material) { - return (Tag.DOORS.isTagged(material) && !Tag.WOODEN_DOORS.isTagged(material)); - } - - /** Check if a material is a non wood slab - * @param material Material to check - * @return True if material is non wood slab - */ - public static boolean isNonWoodSlab(Material material) { - return (Tag.SLABS.isTagged(material) && !Tag.WOODEN_SLABS.isTagged(material)); - } - - /** Check if a material is a non wood stair - * @param material Material to check - * @return True if material is non wood stair - */ - public static boolean isNonWoodStairs(Material material) { - return (Tag.STAIRS.isTagged(material) && !Tag.WOODEN_STAIRS.isTagged(material)); - } - - /** Check if a material is a wood gate - * @param material Material to check - * @return True if material is wood gate - */ - public static boolean isWoodGate(Material material) { - return Tag.FENCE_GATES.isTagged(material); - } - - /** Check if a material is a farmable block - *

ie: melon, potatoes, wheat

- * @param material Material to check - * @return True if material is farmable block - */ - public static boolean isFarmable(Material material) { - return FARMABLE.contains(material); - } - - /** Check if a material is a shove - * @param material Material to check - * @return True if material is shovel - */ - public static boolean isShovel(Material material) { - return SHOVEL.contains(material); - } - - /** Check if a material requires a shovel to dig it - * @param material Material to check - * @return True if material requires a shovel - */ - public static boolean requiresShovel(Material material) { - return REQUIRES_SHOVEL.contains(material) || isConcretePowder(material); - } - - /** Check if a material is a pickaxe - * @param material Material to check - * @return True if material is pickaxe - */ - public static boolean isPickaxe(Material material) { - return PICKAXE.contains(material); - } - - /** Check if a material requires a pickaxe to mine it - *

ie: ores, non-wood doors/slabs/stairs, concrete

- * @param material Material to check - * @return True if material requires pickaxe - */ - public static boolean requiresPickaxe(Material material) { - if (REQUIRES_PICKAXE.contains(material)) return true; - if (Utils.isStoneTypeBlock(material)) return true; - if (Utils.isOreBlock(material)) return true; - if (Utils.isNaturalOreBlock(material)) return true; - if (Utils.isNonWoodDoor(material)) return true; - if (Utils.isTerracotta(material)) return true; - if (Utils.isGlazedTerracotta(material)) return true; - if (Utils.isConcrete(material)) return true; - if (Utils.isCookingBlock(material)) return true; - if (Tag.WALLS.isTagged(material)) return true; - if (Tag.ICE.isTagged(material)) return true; - if (Tag.CORAL_BLOCKS.isTagged(material)) return true; - return Tag.RAILS.isTagged(material); - } - - /** Check if a material is an axe - * @param material Material to check - * @return True if material is axe - */ - public static boolean isAxe(Material material) { - return AXE.contains(material); - } - - /** Check if a material requires an axe to break - * @param material Material to check - * @return True if material requires axe - */ - public static boolean requiresAxe(Material material) { - if (REQUIRES_AXE.contains(material)) return true; - if (Tag.WOODEN_DOORS.isTagged(material)) return true; - if (Tag.WOODEN_TRAPDOORS.isTagged(material)) return true; - if (Tag.PLANKS.isTagged(material)) return true; - if (Tag.LOGS.isTagged(material)) return true; - if (Tag.WOODEN_STAIRS.isTagged(material)) return true; - if (Tag.WOODEN_SLABS.isTagged(material)) return true; - if (Tag.WOODEN_FENCES.isTagged(material)) return true; - if (Tag.WOODEN_PRESSURE_PLATES.isTagged(material)) return true; - if (Tag.BANNERS.isTagged(material)) return true; - if (Tag.SIGNS.isTagged(material)) return true; - return Utils.isWoodGate(material); - } - - /** Check if a material requires shears to break - *

ie: cobweb, tripwire, tnt

- * @param material Material to check - * @return True if material requires shears - */ - public static boolean requiresShears(Material material) { - return REQUIRES_SHEARS.contains(material); - } - - /** Check if a material requires a hammer (in offhand) to place - * @param material Material to check - * @return True if material requires hammer - */ - public static boolean requiresHammer(Material material) { - if (REQUIRES_HAMMER.contains(material)) return true; - return Tag.DOORS.isTagged(material) - - || isWoodGate(material) - || isTerracotta(material) - || isGlazedTerracotta(material) - || isConcrete(material) - || isStoneTypeBlock(material) - || isCookingBlock(material) - || isStorageBlock(material) - || isUtilityBlock(material) - || isShulkerBox(material) - || isOreBlock(material) - - || Tag.BEDS.isTagged(material) - || Tag.LOGS.isTagged(material) - || Tag.STAIRS.isTagged(material) - || Tag.SLABS.isTagged(material) - || Tag.PLANKS.isTagged(material) - || Tag.WOODEN_PRESSURE_PLATES.isTagged(material) - || Tag.WOODEN_FENCES.isTagged(material) - || Tag.RAILS.isTagged(material) - || Tag.BANNERS.isTagged(material) - || Tag.FENCES.isTagged(material) - || Tag.SIGNS.isTagged(material); - } - - /** Get the drops for a certain material - * @param material Material that will be broken - * @param grown If the block is grown - * @return List of materials this material will drop - */ - public static List getDrops(Material material, Boolean grown) { - List mat = new ArrayList<>(); - switch (material) { - case PUMPKIN: - mat.add(Material.PUMPKIN); - break; - case MELON_STEM: - mat.add(Material.MELON_SEEDS); - break; - case MELON: - mat.add(Material.MELON_SLICE); - break; - case PUMPKIN_STEM: - mat.add(Material.PUMPKIN_SEEDS); - break; - case CHORUS_FLOWER: - mat.add(Material.CHORUS_FLOWER); - break; - case CARROTS: - mat.add(Material.CARROT); - break; - case POTATOES: - mat.add(Material.POTATO); - break; - case BEETROOTS: - if (grown) { - mat.add(Material.BEETROOT); - } - mat.add(Material.BEETROOT_SEEDS); - break; - case WHEAT: - if (grown) { - mat.add(Material.WHEAT); - } - mat.add(Material.WHEAT_SEEDS); - break; - case SWEET_BERRY_BUSH: - mat.add(Material.SWEET_BERRIES); - break; - case COCOA: - mat.add(Material.COCOA_BEANS); - break; - default: - mat.add(Material.AIR); - } - return mat; - } - - /** Send a colored string to a Player - *

- * Does not require ChatColor methods - *

- * @param player The player to send a colored string to - * @param msg The string to send including color codes - */ - public static void sendColoredMsg(CommandSender player, String msg) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); - } - - /** Send a colored console message - *

This will NOT include plugin prefix

- * @param msg Message to send - */ - public static void sendColoredConsoleMsg(String msg) { - Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); - } - - /** Log a message to console - *

This will include plugin prefix

- * @param msg Message to log to console - */ - public static void log(String msg) { - Lang lang = Survival.getInstance().getLang(); - String prefix = "&7[&bSurvival&3Plus&7] "; - if (lang != null) { - prefix = lang.prefix; - } - sendColoredConsoleMsg(prefix + msg); - } - - /** Log a formatted message to console - *

Formatted in the same style as {@link String#format(String, Object...)} - *
This will include plugin prefix

- * @param format Message format - * @param objects Objects in format - */ - public static void log(String format, Object... objects) { - log(String.format(format, objects)); - } - - /** Gets a colored string - * @param string The string including color codes/HEX color codes - * @return Returns a formatted string - */ - public static String getColoredString(String string) { - if (isRunningMinecraft(1, 16)) { - Matcher matcher = HEX_PATTERN.matcher(string); - while (matcher.find()) { - final net.md_5.bungee.api.ChatColor hexColor = net.md_5.bungee.api.ChatColor.of(matcher.group().substring(1, matcher.group().length() - 1)); - final String before = string.substring(0, matcher.start()); - final String after = string.substring(matcher.end()); - string = before + hexColor + after; - matcher = HEX_PATTERN.matcher(string); - } - } - return net.md_5.bungee.api.ChatColor.translateAlternateColorCodes('&', string); - } - - /** Spawn a particle at a location for all players - * @param location The location to spawn a particle at - * @param particle The particle to spawn - * @param amount The amount of particles - * @param offsetX Offset by x - * @param offsetY Offset by y - * @param offsetZ Offset by z - */ - public static void spawnParticle(Location location, Particle particle, int amount, double offsetX, double offsetY, double offsetZ) { - assert location.getWorld() != null; - location.getWorld().spawnParticle(particle, location, amount, offsetX, offsetY, offsetZ); - } - - /** Spawn a particle at a location for a player - * @param location The location to spawn a particle at - * @param particle The particle to spawn - * @param amount The amount of particles - * @param offsetX Offset by x - * @param offsetY Offset by y - * @param offsetZ Offset by z - * @param player The player to spawn a particle for - */ - public static void spawnParticle(Location location, Particle particle, int amount, double offsetX, double offsetY, double offsetZ, Player player) { - player.spawnParticle(particle, location, amount, offsetX, offsetY, offsetZ); - } - - /** Set the durability of an ItemStack - * @param item The ItemStack to set - * @param durability The durability to set - */ - public static void setDurability(ItemStack item, int durability) { - ItemMeta meta = item.getItemMeta(); - assert meta != null; - ((Damageable) meta).setDamage(durability); - item.setItemMeta(meta); - } - - /** Check the durability of an ItemStack - * @param item The ItemStack to check - * @return The durability of the ItemStack - */ - public static int getDurability(ItemStack item) { - assert item.getItemMeta() != null; - return ((Damageable) item.getItemMeta()).getDamage(); - } - - public static List getItemStackDura(Item item, int maxDurability) { - List itemStacks = new ArrayList<>(); - for (int i = 0; i < maxDurability; i++) { - ItemStack stack = ItemManager.get(item); - ItemMeta meta = stack.getItemMeta(); - assert meta != null; - ((Damageable) meta).setDamage(i); - stack.setItemMeta(meta); - itemStacks.add(stack); - } - return itemStacks; - } - - /** Gets the minutes a player has played on the server - * @param player The player to check - * @return The number of minutes they have played on the server - */ - @SuppressWarnings("IntegerDivisionInFloatingPointContext") - public static int getMinutesPlayed(Player player) { - int played = player.getStatistic(Statistic.PLAY_ONE_MINUTE); - return Math.round(played / 1200); - } - - /** Check if server is running a minimum Minecraft version - * @param major Major version to check (Most likely just going to be 1) - * @param minor Minor version to check - * @return True if running this version or higher - */ - public static boolean isRunningMinecraft(int major, int minor) { - return isRunningMinecraft(major, minor, 0); - } - - /** Check if server is running a minimum Minecraft version - * @param major Major version to check (Most likely just going to be 1) - * @param minor Minor version to check - * @param revision Revision to check - * @return True if running this version or higher - */ - public static boolean isRunningMinecraft(int major, int minor, int revision) { - String[] version = Bukkit.getServer().getBukkitVersion().split("-")[0].split("\\."); - int maj = Integer.parseInt(version[0]); - int min = Integer.parseInt(version[1]); - int rev; - try { - rev = Integer.parseInt(version[2]); - } catch (Exception ignore) { - rev = 0; - } - return maj > major || min > minor || (min == minor && rev >= revision); - } - - public static boolean isRunningSpigot() { - return classExists("org.spigotmc.CustomTimingsHandler"); - } - - /** Check if a class exists - * @param className The {@link Class#getCanonicalName() canonical name} of the class - * @return True if the class exists - */ - public static boolean classExists(final String className) { - try { - Class.forName(className); - return true; - } catch (ClassNotFoundException ex) { - return false; - } - } - - /** Check if a method exists - * @param c Class the method belongs to - * @param methodName Name of method - * @param parameterTypes Parameter types for this method - * @return True if the method exists - */ - public static boolean methodExists(final Class c, final String methodName, final Class... parameterTypes) { - try { - c.getDeclaredMethod(methodName, parameterTypes); - return true; - } catch (NoSuchMethodException ex) { - return false; - } - } - - /** Check if this entity is a Citizens NPC - * @param entity Entity to check - * @return True if entity is an NPC - */ - public static boolean isCitizensNPC(Metadatable entity) { - return entity.hasMetadata("NPC"); - } - - /** Get a {@link NamespacedKey} linked to this plugin - * @param key Key to create - * @return New NamespacedKey linked to this plugin - */ - public static NamespacedKey getNamespacedKey(String key) { - return new NamespacedKey(Survival.getInstance(), key); - } - - /** Check if the player is at the highest block (exposed to sun) - * @param player Player to check - * @return True if player is exposed to sun - */ - public static boolean isAtHighest(Player player) { - Location location = player.getLocation(); - World world = player.getWorld(); - return location.getY() > world.getHighestBlockAt(location).getY(); - } - -} diff --git a/src/main/java/tk/shanebee/survival/util/Validate.java b/src/main/java/tk/shanebee/survival/util/Validate.java deleted file mode 100644 index 7487b35..0000000 --- a/src/main/java/tk/shanebee/survival/util/Validate.java +++ /dev/null @@ -1,16 +0,0 @@ -package tk.shanebee.survival.util; - -public abstract class Validate extends org.apache.commons.lang.Validate { - - /** - * Validate if a value is between a min and max value - * - * @param value Value to validate - * @param min Min value amount - * @param max Max value amount - */ - public static void isBetween(int value, int min, int max) { - isTrue(value >= min && value <= max, "Value must be between " + min + " and " + max); - } - -} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 155d686..85e849a 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,150 +1,153 @@ # Settings # Notes in this config are lost on updates if the config file changes -# If you would like to see the notes, delete this file and it will regenerate with notes -# (Make sure to backup your config file) +# If you would like to see the notes, delete this file, and it will regenerate with notes +# (Make sure to back up your config file) -# Preset language file includes in-game messages, item names, lore, etc. -# Language options are EN (English) or CN (Chinese) +# Preset language file includes in-game messages. +# Language options are EN (English) Language: EN -MultiWorld: +settings: # Enable the SurvivalPlus resource pack for players - EnableResourcePack: true + # You can disable this if you wish to supply it yourself + enable-resource-pack: true # The link to the pack, you can put a custom link here if need be - ResourcePackURL: https://www.dropbox.com/s/fq6or9vvcup7wvd/SP-1.14v6.zip?dl=1 - # Notify players when they log in if they deny the resource pack - NotifyMessage: true + resource-pack-url: https://www.dropbox.com/s/fq6or9vvcup7wvd/SP-1.14v6.zip?dl=1 -# The distance from the player at which other players will see their chat messages -# -1 = disabled -LocalChatDist: -1 - -# Disable player's coords in the Minecraft debug screen -NoPos: true + # The distance from the player at which other players will see their chat messages + # -1 = disabled + local-chat-distance: -1 # When a player joins, they will get a link to a simple starter guide -WelcomeGuide: - Enabled: true +welcome-guide: + enabled: true # Only send to players the first time they log in - NewPlayersOnly: false + new-players-only: false # Delay in seconds until this message appears - Delay: 5 + delay: 5 -Survival: +survival: # When enabled, the basic custom SurvivalPlus items will be included in the game - Enabled: true - - # With this enabled, players will only be able to craft items which they have unlocked recipes for - LimitedCrafting: false + enabled: true # If true, all custom recipes will be unlocked when a player joins - # If false, recipes will be unlocked as a player advances thru the game - Unlock-all-recipes-on-join: false + # If false, recipes will be unlocked as a player advances through the game + unlock-all-recipes-on-join: false # When enabled, all vanilla wooden tool recipes will be removed # This makes gameplay a little more difficult - Remove-Wooden-Tools: true + remove-wooden-tools: true # With these enabled, players will only be able to break most blocks with the correct tools - BreakOnlyWith: - Axe: true - Pickaxe: true - Shovel: true - Shears: true - Sickle: true + break-only-with: + axe: true + pickaxe: true + shovel: true + shears: true + sickle: true # Enable each sickle individually - # (note: if BreakOnlyWith.Sickle = false or Survival.Enabled = false, these will be ignored) - # (note: diamond and iron sickles rely on stone sickles in their recipe, so its best to leave stone enabled if diamond or iron are enabled) - Sickles: - Flint: true - Stone: true - Iron: true - Diamond: false - - # With this enabled, players will need a hammer in their off hand to place most buildable blocks - PlaceOnlyWith: - Hammer: true + # (note: if `break-only-with.sickle` = false or survival.enabled` = false, these will be ignored) + # (note: diamond and iron sickles rely on stone sickles in their recipe, so it's best to leave stone enabled if diamond or iron are enabled) + sickles: + flint: true + stone: true + iron: true + diamond: false + + # With this enabled, players will need a hammer in their off-hand to place most buildable blocks + place-only-with: + hammer: true # The rates at which items will drop (Value between 0.01 -> 1.0) - DropRate: + drop-rate: # Dropped when breaking gravel - Flint: 0.5 + flint: 0.5 # Dropped when breaking leaves - Stick: 0.25 + stick: 0.25 # Enables custom torch recipes - Torch: true + torch: true # Enables updating trade options for merchants (ie: Villagers) with custom items equivalent to the trade option # Ex: An armorer offers diamond chestplate -> diamond chestplate with the slowness attribute # Ex: A toolsmith offers diamond hoe -> diamond sickle - UpdateMerchantTrades: true + update-merchant-trades: true + # Same as above but for loot tables (Such as chests/barrels in villages) + update-loot-tables: true -Mechanics: +mechanics: # This is an experimental feature, I recommend not using it - SharedWorkbench: false - - # When enabled the night will not skip to day when players sleep - Prevent-Night-Skip: false + shared-workbench: false # When enabled, players will slow down when wearing heavy armor such as diamond or gold armor - SlowArmor: true + slow-armor: true + # Enables recipes for reinforced leather armor - ReinforcedLeatherArmor: true + reinforced-leather-armor: true # When enabled, players will only be able to shoot a bow/crossbow from their main hand # They will also need to have arrows in their offhand to shoot a bow/load a crossbow - Bow: true + bow: true + # Enables the recurved bow and crossbow - RecurveBow: true + recurve-bow: true + # Enables grappling hooks - GrapplingHook: true + grappling-hook: true + # Enables the medical kit - MedicalKit: true + # Players will be able to heal themselves and other players + # The items.yml file allows you to modify how many uses it has + # Each use (1 durability) will add 2 health points (1 heart) + medical-kit: true + # Reduced recipes for iron/gold nuggets - ReducedIronNugget: true - ReducedGoldNugget: true + reduced-iron-nugget: true + reduced-gold-nugget: true # Shows the players different status levels in a scoreboard - StatusScoreboard: true + status-scoreboard: true + # Interval for alert messages [in seconds] (Currently used to warn players when thirst/nutrients are low) - AlertInterval: 20 + alert-interval: 20 # Applies hunger to players when eating raw meat - RawMeatHunger: true + raw-meat-hunger: true # Players can empty potions in a workbench - EmptyPotions: true + empty-potions: true # When consuming poisonous potatoes, apply a few extra effects to the player - PoisonousPotato: true + poisonous-potato: true # Eating cookies will boost a player's health - CookieHealthBoost: true + cookie-health-boost: true # Eating beetroots will boost a player's strength - BeetrootStrength: true + beetroot-strength: true # Players will need to eat a different variety of foods to stay nourished - FoodDiversity: + food-diversity: enabled: true # Max level for each nutritional value - max-level: - carbs: 50000 - salts: 50000 - proteins: 50000 + max-level: 1000 # The level the player will start with start-level: proteins: 240 carbs: 960 - salts: 360 + vitamins: 360 # The level the player will get after dying respawn-level: proteins: 120 carbs: 480 - salts: 180 + vitamins: 180 + # The amount of minutes a new player will be immune to food diversity effects + # This gives the player time to understand the game and prepare for food diversity changes + # Default = 40 minutes = 2 Minecraft days + # Set to 0 to disable + immunity-minutes: 40 # Each nutrition section has different effects when player's levels are too low effects: carbs: @@ -153,20 +156,19 @@ Mechanics: easy: 2 normal: 4 hard: 8 - salts: + vitamins: exhaustion-amplifier: 1 # Status effects/amplifiers can differ based on server difficulty level status-effects: normal: # The effect (uses Bukkit PotionEffectTypes) - # You can find these effects here: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/potion/PotionEffectType.html - effect: WEAKNESS + effect: "minecraft:weakness" # The amplifying level (0 = tier 1, 1 = tier 2) amplifier: 0 # The time in seconds this effect will last for duration: 20 hard: - effect: WEAKNESS + effect: "minecraft:weakness" amplifier: 1 duration: 20 proteins: @@ -174,53 +176,55 @@ Mechanics: # Status effects/amplifiers can differ based on server difficulty level status-effects: normal: - effect: WEAKNESS + effect: "minecraft:weakness" amplifier: 0 duration: 20 hard: - effect: WEAKNESS + effect: "minecraft:weakness" amplifier: 1 duration: 20 # When enabled, players will need to drink water to replenish their thirst levels - Thirst: - Enabled: true + thirst: + enabled: true # The level of thirst a player starts out with (max = 40) - Starting-Amount: 30 - # The level of thirst a player gets after respawning after death (max = 40) - Respawn-Amount: 30 - # Enables 3 different levels of water (dirty, clean, purified) - PurifyWater: true - MeltSnow: true - # The rate at which a player's thirst level will drop (value from 0.01 -> 1.0) - DrainRate: 1.0 - # If player is in a HOT biome, drain 1 extra thirst point every X seconds - # This helps speed up thirst draining when a player is in a hot biome like the desert or savannah - # (ex: at a rate of 30, thirst drops 2 points a minute, which means the player would lose all thirst in 20 minutes) - # If set to 0, this will be disabled - HeatDrain: 30 - # If player is in the nether, drain 1 extra thirst point every X seconds - # This helps speed up thirst draining when a player is in the nether - # (ex: at a rate of 30, thirst drops 2 points a minute, which means the player would lose all thirst in 20 minutes) - # If set to 0, this will be disabled - NetherDrain: 30 - # The amount of damage a player takes when their thirst level is empty - DamageRate: 1.0 + starting-amount: 30.0 + # The level of thirst a player gets after respawning (max = 40) + respawn-amount: 30.0 + # The amount of minutes a new player will be immune to thirst effects + # This gives the player time to understand the game and prepare for thirst changes + # During this time the player can drink and do any water related tasks, but their thirst won't drop + # Default = 40 minutes = 2 Minecraft days + # Set to 0 to disable + immunity-minutes: 40 + # Enables 5 different levels of water (dirty, salty, murky, clean, purified) + purify-water: true + # Unused (maybe for the future?!?!) + melt-snow: true + # The amount of thirst to drop when doing exhaustive tasks such as running, mining, etc. + # (When exhaustion reaches 4 and resets, this amount will be removed from the player's thirst) + drain-rate: 0.5 + # The amount of thirst that will drop every 5 seconds in the heat + # Player needs to be in a hot biome where the temp exceeds 1.5 (eg: desert, savanna, badlands) and exposed to direct sunlight + # Default = 0.083 (This would take one 20-minute daylight cycle to drain thirst) + heat-drain-rate: 0.083 + # The amount of thirst that will drop every 5 seconds in the nether + # Default = 0.17 (This would take 10 minutes to drain thirst) + nether-drain-rate: 0.17 + # The amount of damage a player will take every 5 seconds when their thirst level is empty + # Easy mode = Will only damage if player's health > 10 (5 hearts) + # Normal mode = Will only damage if player's health > 1 (0.5 hearts) + # Hard mode = Will damage player no matter what (could kill) + damage-rate: 1.0 # The level of thirst that will be replenished when a player consumes this item - Replenish-Level: + # Custom items' replenish thirst levels are handled in the items.yml file + replenish-level: + apple: 1 beetroot-soup: 6 melon-slice: 6 mushroom-stew: 12 - water-bowl: 10 - coffee: 23 - cold-milk: 15 - hot-milk: 10 milk-bucket: 30 honey-bottle: 16 - # Only used if PurifyWater is enabled - dirty-water: 13 - clean-water: 18 - purified-water: 23 # This can be used for any other water bottle (such as custom ones or just vanilla water bottles) # If you do not want players to get thirst from other water bottles leave this at 0 other-water: 0 @@ -228,13 +232,18 @@ Mechanics: water: 18 # Players will have an energy level out of 20, as it drops, players will get weak and suffer some bad effects - Energy: + energy: # With this enabled, players will need to sleep often or risk losing energy enabled: true # The amount of energy a player will start with (out of 20.0) start-level: 20.0 # The amount of energy a player will get after they respawn (out of 20.0) respawn-level: 20.0 + # The amount of minutes a new player will be immune to energy effects + # This gives the player time to understand the game and prepare for energy changes + # Default = 40 minutes = 2 Minecraft days + # Set to 0 to disable + immunity-minutes: 40 # Warn the player via message when energy starts dropping below 10 warning: true # The amount of energy a player loses every 5 seconds of gameplay @@ -244,14 +253,15 @@ Mechanics: # Default (0.015) equivalent to 3.6 levels in 1 MC day (20 minutes) # Setting to 0 will disable this cold-drain-rate: 0.015 + # Players doing exhaustive tasks (such as mining, running, jumping) will lose energy quicker + # Amount to drop per exhaustion reset (set to 0 to disable) + exhaustion: 0.15 # Every 5 seconds a player spends in bed, the level of energy to increase - sleeping-refresh-rate: 0.83 # Default (0.83) equivalent to 10 levels in 1 minute + # Default (0.83) equivalent to 10 levels in 1 minute + sleeping-refresh-rate: 0.83 # Every 5 seconds a player spends sitting in a chair, the level of energy to increase # (Will only work if chairs are enabled) chair-refresh-rate: 0.25 # Default (0.41) equivalent to 3 levels in 1 minute - # Players doing exhaustive tasks (such as mining, running, jumping) will lose energy quicker - # Amount to drop per exhaustion reset (when the player's hunger bar drops) (set to 0 to disable) - exhaustion: 0.15 # Enables coffee recipes and effects (Drink coffee to regain energy) coffee: true # Player will get a few minutes of absorption when their energy is high @@ -259,79 +269,49 @@ Mechanics: # Player will get a few minutes of haste when their energy is high haste: true - Hunger: + hunger: # The level of hunger a player starts out with (max = 40)(this is a mixture of hunger and saturation) - Starting-Amount: 30 - # The level of hunger a player will receive after respawning after death (max = 40) - Respawn-Amount: 30 + starting-amount: 30 + # The level of hunger a player will receive after respawning post-death (max = 40) + respawn-amount: 30 # Players can set a waypoint to a location using a compass - CompassWaypoint: + compass-waypoint: enabled: true # Whether a player is able to set a point for each world per-world: true + # Players can eat a tropical fish to teleport to their waypoint - # (Clownfish was the old type that's why this is still here) - Clownfish: true + tropical-fish: true # Enables fermented skin recipes - FermentedSkin: true + fermented-skin: true # Enables living slime - LivingSlime: true + living-slime: true # When a player throws a snowball it will place a snow layer on the ground - SnowballRevamp: true + snowball-revamp: true - # Currently disabled, do not use!!! - SnowGenerationRevamp: false - - FarmingProducts: - Bread: true - Cookie: true + # Creates harder to craft recipes for these items + farming-products: + bread: true + cookie: true # Enables chairs and the blocks that can be used for chairs - Chairs: - Enabled: true - MaxChairWidth: 2 - # These must be Bukkit material Enums - # https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html - AllowedBlocks: - - OAK_STAIRS - - SPRUCE_STAIRS - - JUNGLE_STAIRS - - BIRCH_STAIRS - - ACACIA_STAIRS - - DARK_OAK_STAIRS - - SANDSTONE_STAIRS - - COBBLESTONE_STAIRS - - BRICK_STAIRS - - STONE_BRICK_STAIRS - - NETHER_BRICK_STAIRS - - QUARTZ_STAIRS - - RED_SANDSTONE_STAIRS - - PURPUR_STAIRS - - PRISMARINE_STAIRS - - PRISMARINE_BRICK_STAIRS - - DARK_PRISMARINE_STAIRS - - # EXPERIMENTAL FEATURE - # DO NOT USE - BurnoutTorches: - Enabled: false - # Time (in seconds) before torch will burn out - BurnoutTime: 60 - # If burnout torches can be re-lit - Relightable: true - # If non persistent torches will drop a torch when broken, if disabled will drop a stick - DropTorch: true - # If persistent torches are enabled - PersistentTorches: true + chairs: + enabled: true + max-chair-width: 2 + # Blocks that can be used as chairs + # Has to be a stair block + # Accepts Minecraft namespaced keys and tags + allowed-blocks: + - '#minecraft:stairs' # WEATHER MECHANICS # These mechanics change how weather affects the player - Weather: - Enabled: false + weather: + enabled: false # Speed modifiers adjust player's speed based on weather speed: # This is the base speed (vanilla speed = 0.10) when a player is in normal conditions @@ -346,20 +326,21 @@ Mechanics: snowstorm: 0.05 # Mechanics that flow around items -Item-Mechanics: +item-mechanics: firestriker: # The amount of ticks it takes to cook/smelt an item with the FireStriker (default 100 ticks = 5 seconds) cook-time: 100 # Mechanics that flow around entities -Entity-Mechanics: - # When a player opens a chest in the nether, and it contains gold items, zombie pigmen will attack the player - pigmen-chests: - enabled: false - # Max radius to check for zombie pigmen around chests +entity-mechanics: + # When a player opens a chest in the nether, and it contains gold items, zombified piglins will attack the player + zombified-piglin-chests: + enabled: true + # Max radius to check for zombified piglin around chests distance: 24 - # Speeds up the pigmen when they are triggered (1.0 = no increase in speed) - speed-modifier: 1.3 + # Speeds up the zombified piglin when they are triggered + # 0.0 = no increase in speed, 0.25 = 25% faster + speed-modifier: 0.25 # When a player has a beekeeper suit on they will not take damage from bee stings beekeeper-suit: enabled: true @@ -382,46 +363,61 @@ Entity-Mechanics: # If 'always-baby = false' this time will only be applied to baby chickens # Vanilla default = 24,000 ticks = 20 minutes baby-ticks: 48000 + # Mechanics for piglin bartering piglin-barter: # When enabled, if a piglin drops a water bottle they'll drop purified/clean water instead # Thirst needs to be enabled for this to work drop-purified-water: true # When enabled, piglins have a chance of randomly dropping custom SurvivalPlus items alternate-bartering: true + # Mobs that should avoid the player + # Will support minecraft tags, ex: `"#minecraft:some_entity_tag"` + # Mobs will run away from players at a speed of 1.6x their normal speed + # For new players (played less than 2 MC days) the multiplier is reduced to 1.25x + # To disable, clear the list and put "empty" in the list + mobs-avoid-players: + - "minecraft:sheep" + - "minecraft:cow" + - "minecraft:chicken" + - "minecraft:pig" + # Make wolves attack players without provocation + # Holding wolf food in hand will stop them + # Options are "always", "night" or "disabled" + angry-wolves: night # Enables custom recipes (Overrides vanilla recipes) # Disable these if you prefer to just use the vanilla recipes -Recipes: - Saddle: true - Nametag: true - PackedIce: true - LeatherBard: true - IronBard: true - GoldBard: true - DiamondBard: true - ClayBrick: true - QuartzBlock: true - WoolString: true - WebString: true - Ice: true - Clay: true - Diorite: false - Granite: false - Andesite: false - Gravel: true - Slimeball: true - Cobweb: true - SaplingToSticks: true - FishingRod: true - Furnace: true - Workbench: true +recipes: + saddle: true + nametag: true + packed-ice: true + leather-bard: true + iron-bard: true + gold-bard: true + diamond-bard: true + clay-brick: true + quartz-block: true + wool-string: true + web-string: true + ice: true + clay: true + diorite: false + granite: false + andesite: false + gravel: true + slimeball: true + cobweb: true + sapling-to-sticks: true + fishing-rod: true + furnace: true + workbench: true # Enables legendary items -LegendaryItems: - ValkyrieAxe: true - QuartzPickaxe: true - ObsidianMace: true - GiantBlade: true - BlazeSword: true - NotchApple: true - GoldArmorBuff: true +legendary-items: + valkyrie-axe: true + quartz-pickaxe: true + obsidian-mace: true + giant-blade: true + blaze-sword: true + notch-apple: true + gold-armor-buff: true diff --git a/src/main/resources/data.yml b/src/main/resources/data.yml deleted file mode 100644 index ea4434c..0000000 --- a/src/main/resources/data.yml +++ /dev/null @@ -1,2 +0,0 @@ -# SurvivalPlus Data Files -# DO NOT TOUCH \ No newline at end of file diff --git a/src/main/resources/datapack/data/survival_plus/damage_type/ender_power.json b/src/main/resources/datapack/data/survival_plus/damage_type/ender_power.json new file mode 100644 index 0000000..66d4d80 --- /dev/null +++ b/src/main/resources/datapack/data/survival_plus/damage_type/ender_power.json @@ -0,0 +1,5 @@ +{ + "exhaustion": 0.1, + "message_id": "ender_power", + "scaling": "when_caused_by_living_non_player" +} diff --git a/src/main/resources/datapack/data/survival_plus/enchantment/blazing.json b/src/main/resources/datapack/data/survival_plus/enchantment/blazing.json new file mode 100644 index 0000000..17c5643 --- /dev/null +++ b/src/main/resources/datapack/data/survival_plus/enchantment/blazing.json @@ -0,0 +1,159 @@ +{ + "description": { + "text": "Blazing", + "color": "#e27c20" + }, + "supported_items": "#minecraft:enchantable/sharp_weapon", + "weight": 1, + "max_level": 1, + "min_cost": { + "base": 10, + "per_level_above_first": 10 + }, + "max_cost": { + "base": 25, + "per_level_above_first": 10 + }, + "anvil_cost": 4, + "slots": [ + "hand" + ], + "effects": { + "minecraft:damage_immunity": [ + { + "requirements": { + "condition": "minecraft:damage_source_properties", + "predicate": { + "tags": [ + { + "id": "minecraft:is_fire", + "expected": true + } + ] + } + }, + "effect": {} + } + ], + "minecraft:tick": [ + { + "requirements": { + "condition": "minecraft:entity_properties", + "entity": "this", + "predicate": { + "periodic_tick": 1 + } + }, + "effect": { + "type": "minecraft:spawn_particles", + "particle": { + "type": "minecraft:flame" + }, + "horizontal_position": { + "type": "entity_position", + "offset": 0, + "scale": 1 + }, + "vertical_position": { + "type": "entity_position", + "offset": 0.9, + "scale": 1 + }, + "horizontal_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "vertical_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "speed": 0.075 + } + }, + { + "requirements": { + "condition": "minecraft:entity_properties", + "entity": "this", + "predicate": { + "periodic_tick": 50 + } + }, + "effect": { + "type": "minecraft:play_sound", + "sound": "minecraft:entity.blaze.ambient", + "volume": 3, + "pitch": { + "type": "minecraft:uniform", + "min_inclusive": 0.8, + "max_exclusive": 1.2 + } + } + } + ], + "minecraft:hit_block": [ + { + "requirements": { + "condition": "minecraft:entity_properties", + "entity": "this", + "predicate": { + "flags": { + "is_sneaking": true + } + } + }, + "effect": { + "type": "minecraft:all_of", + "effects": [ + { + "type": "minecraft:replace_disk", + "block_state": { + "type": "minecraft:simple_state_provider", + "state": { + "Name": "minecraft:fire" + } + }, + "predicate": { + "type": "minecraft:all_of", + "predicates": [ + { + "type": "minecraft:has_sturdy_face", + "direction": "up", + "offset": [ + 0, + -1, + 0 + ] + }, + { + "type": "minecraft:matching_block_tag", + "tag": "minecraft:replaceable" + } + ] + }, + "trigger_game_event": "minecraft:block_place", + "radius": 4, + "height": 2, + "offset": [ + 0, + 1, + 0 + ] + }, + { + "type": "minecraft:change_item_damage", + "amount": 5 + } + ] + } + } + ] + } +} diff --git a/src/main/resources/datapack/data/survival_plus/enchantment/building_reach.json b/src/main/resources/datapack/data/survival_plus/enchantment/building_reach.json new file mode 100644 index 0000000..ed4098f --- /dev/null +++ b/src/main/resources/datapack/data/survival_plus/enchantment/building_reach.json @@ -0,0 +1,35 @@ +{ + "description": { + "text": "Building Reach", + "color": "#23F2AA" + }, + "supported_items": "minecraft:stick", + "weight": 1, + "max_level": 3, + "min_cost": { + "base": 15, + "per_level_above_first": 7 + }, + "max_cost": { + "base": 30, + "per_level_above_first": 10 + }, + "anvil_cost": 4, + "slots": [ + "offhand" + ], + "effects": { + "attributes": [ + { + "attribute": "minecraft:block_interaction_range", + "amount": { + "type": "linear", + "base": 3, + "per_level_above_first": 2 + }, + "operation": "add_value", + "id": "survival_plus:hammer_reach" + } + ] + } +} diff --git a/src/main/resources/datapack/data/survival_plus/enchantment/ender_power.json b/src/main/resources/datapack/data/survival_plus/enchantment/ender_power.json new file mode 100644 index 0000000..012a0be --- /dev/null +++ b/src/main/resources/datapack/data/survival_plus/enchantment/ender_power.json @@ -0,0 +1,120 @@ +{ + "description": { + "text": "Ender Power", + "color": "#973DF1" + }, + "supported_items": "#minecraft:swords", + "weight": 1, + "max_level": 5, + "min_cost": { + "base": 10, + "per_level_above_first": 10 + }, + "max_cost": { + "base": 25, + "per_level_above_first": 10 + }, + "anvil_cost": 4, + "slots": [ + "hand" + ], + "effects": { + "minecraft:tick": [ + { + "requirements": { + "condition": "minecraft:entity_properties", + "entity": "this", + "predicate": { + "periodic_tick": 1 + } + }, + "effect": { + "type": "minecraft:spawn_particles", + "particle": { + "type": "minecraft:crit" + }, + "horizontal_position": { + "type": "entity_position", + "offset": 0, + "scale": 1 + }, + "vertical_position": { + "type": "entity_position", + "offset": 0.9, + "scale": 1 + }, + "horizontal_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "vertical_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "speed": 0.5 + } + } + ], + "minecraft:item_damage": [ + { + "effect": { + "type": "minecraft:remove_binomial", + "chance": { + "type": "minecraft:fraction", + "denominator": { + "type": "minecraft:linear", + "base": 10.0, + "per_level_above_first": 5.0 + }, + "numerator": { + "type": "minecraft:linear", + "base": 2.0, + "per_level_above_first": 2.0 + } + } + }, + "requirements": { + "condition": "minecraft:match_tool", + "predicate": { + "items": "#minecraft:enchantable/armor" + } + } + }, + { + "effect": { + "type": "minecraft:remove_binomial", + "chance": { + "type": "minecraft:fraction", + "denominator": { + "type": "minecraft:linear", + "base": 2.0, + "per_level_above_first": 1.0 + }, + "numerator": { + "type": "minecraft:linear", + "base": 1.0, + "per_level_above_first": 1.0 + } + } + }, + "requirements": { + "condition": "minecraft:inverted", + "term": { + "condition": "minecraft:match_tool", + "predicate": { + "items": "#minecraft:enchantable/armor" + } + } + } + } + ] + } +} diff --git a/src/main/resources/datapack/data/survival_plus/enchantment/obsidian_power.json b/src/main/resources/datapack/data/survival_plus/enchantment/obsidian_power.json new file mode 100644 index 0000000..d33570d --- /dev/null +++ b/src/main/resources/datapack/data/survival_plus/enchantment/obsidian_power.json @@ -0,0 +1,169 @@ +{ + "description": { + "text": "Obsidian Power", + "color": "#973DF1" + }, + "supported_items": "#minecraft:enchantable/mace", + "weight": 1, + "max_level": 1, + "min_cost": { + "base": 10, + "per_level_above_first": 10 + }, + "max_cost": { + "base": 25, + "per_level_above_first": 10 + }, + "anvil_cost": 4, + "slots": [ + "hand" + ], + "effects": { + "minecraft:tick": [ + { + "requirements": { + "condition": "minecraft:entity_properties", + "entity": "this", + "predicate": { + "periodic_tick": 1 + } + }, + "effect": { + "type": "minecraft:spawn_particles", + "particle": { + "type": "minecraft:crit" + }, + "horizontal_position": { + "type": "entity_position", + "offset": 0, + "scale": 1 + }, + "vertical_position": { + "type": "entity_position", + "offset": 0.9, + "scale": 1 + }, + "horizontal_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "vertical_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "speed": 0.5 + } + }, + { + "requirements": { + "condition": "minecraft:entity_properties", + "entity": "this", + "predicate": { + "periodic_tick": 1 + } + }, + "effect": { + "type": "minecraft:spawn_particles", + "particle": { + "type": "minecraft:portal" + }, + "horizontal_position": { + "type": "entity_position", + "offset": 0, + "scale": 1 + }, + "vertical_position": { + "type": "entity_position", + "offset": 0.9, + "scale": 1 + }, + "horizontal_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "vertical_velocity": { + "base": { + "type": "uniform", + "min_inclusive": -2, + "max_exclusive": 2 + }, + "movement_scale": 1 + }, + "speed": 0.5 + } + } + ], + "minecraft:post_attack": [ + { + "effect": { + "type": "minecraft:apply_mob_effect", + "to_apply": [ + "minecraft:weakness", + "minecraft:slowness" + ], + "min_duration": 90, + "max_duration": 150, + "min_amplifier": 0, + "max_amplifier": 0 + }, + "enchanted": "attacker", + "affected": "victim" + }, + { + "effect": { + "type": "minecraft:apply_mob_effect", + "to_apply": [ + "minecraft:regeneration" + ], + "min_duration": 45, + "max_duration": 55, + "min_amplifier": 0, + "max_amplifier": 0 + }, + "enchanted": "attacker", + "affected": "attacker" + }, + { + "effect": { + "type": "minecraft:spawn_particles", + "particle": { + "type": "minecraft:heart" + }, + "horizontal_position": { + "type": "entity_position", + "offset": 0, + "scale": 1 + }, + "vertical_position": { + "type": "entity_position", + "offset": 2.0, + "scale": 1 + }, + "horizontal_velocity": { + "base": 2, + "movement_scale": 2 + }, + "vertical_velocity": { + "base": 2, + "movement_scale": 2 + }, + "speed": 1 + }, + "enchanted": "attacker", + "affected": "attacker" + } + ] + } +} diff --git a/src/main/resources/datapack/data/survival_plus/enchantment/quartz_mining.json b/src/main/resources/datapack/data/survival_plus/enchantment/quartz_mining.json new file mode 100644 index 0000000..8c2b9e3 --- /dev/null +++ b/src/main/resources/datapack/data/survival_plus/enchantment/quartz_mining.json @@ -0,0 +1,44 @@ +{ + "description": { + "text": "Quartz Mining", + "color": "#E8DFD4" + }, + "supported_items": "#minecraft:pickaxes", + "exclusive_set": "#minecraft:exclusive_set/mining", + "weight": 1, + "max_level": 5, + "min_cost": { + "base": 20, + "per_level_above_first": 10 + }, + "max_cost": { + "base": 45, + "per_level_above_first": 10 + }, + "anvil_cost": 4, + "slots": [ + "mainhand" + ], + "effects": { + "minecraft:attributes": [ + { + "amount": { + "type": "minecraft:linear", + "base": 0.2, + "per_level_above_first": 0.1 + }, + "attribute": "minecraft:mining_efficiency", + "id": "minecraft:enchantment.efficiency", + "operation": "add_multiplied_base" + } + ], + "minecraft:repair_with_xp": [ + { + "effect": { + "type": "minecraft:multiply", + "factor": 2.0 + } + } + ] + } +} diff --git a/src/main/resources/datapack/pack.mcmeta b/src/main/resources/datapack/pack.mcmeta new file mode 100644 index 0000000..8ac3987 --- /dev/null +++ b/src/main/resources/datapack/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 61, + "description": "SurvivalPlus Datapack" + } +} diff --git a/src/main/resources/items.yml b/src/main/resources/items.yml index 9793399..5128d36 100644 --- a/src/main/resources/items.yml +++ b/src/main/resources/items.yml @@ -3,14 +3,16 @@ # This file holds certain properties for custom items # Only change it if you know what you're doing +# This file supports MiniMessage formatting +# See the website for more info: https://docs.advntr.dev/minimessage/format +# +# Using legacy color codes '&' or '§' are not supported and will error + # --ITEMS-- -# model_data is the CustomModalData version of this item which represents the CustomModelData number in the resource pack -# If you are using a custom resource pack, you can change this number to match -# repair_cost_multiplier = the amount that will multiply when repairing in an anvil -# -1 = does not require an anvil, can be repaired in a crafting table -# 0 = requires an anvil, but no multiplier -# >0 = requires an anvil, multiplier applied +# repair_cost = The number of experience levels to add to the base level cost when repairing, combining, +# or renaming this item with an anvil. Must be a non-negative integer, defaults to 0. +# See https://minecraft.wiki/w/Data_component_format#repair_cost for further details. # repair_percent = modifier for repair amount # Value must be between 0.0 and 1.0 (1.0 = full vanilla healing) @@ -26,5 +28,304 @@ # --NUTRITION-- # Nutrition values can be changed. They cannot be removed nor added to -# Deleting a value will reset to it's default value +# Deleting a value will reset to its default value # The values must be >= 0 + +items: + # TOOLS + compass: + name: "Compass" + repair_cost: 0 + repair_percent: 0.85 + lore: + - '<#B1BBBE>Shift-Right-Click:' + - '<#17DA4F> Set waypoint to current location' + - '<#B1BBBE>Left-Click:' + - '<#17DA4F> See coords of waypoint' + firestriker: + name: "Firestriker" + lore: + - "Right-Click to burn things" + - " - You can also light campfires" + - "Sneak-Right-Click to smelt things" + - " - Put a smeltable item into input slot" + - " - Keep it open and watch it cook" + repair_cost: 0 + repair_percent: 0.0 + max_cooks: 10 + grappling_hook: + name: "Grappling Hook" + repair_cost: 0 + repair_percent: 0.85 + hammer: + name: "Hammer" + max_damage: 200 + repair_cost: 0 + repair_percent: 0.85 + lore: + - "<#F39516>Required in your off-hand for building" + hatchet: + name: "Hatchet" + max_damage: 50 + repair_cost: 0 + repair_percent: 0.85 + mattock: + name: "Mattock" + max_damage: 50 + repair_cost: 0 + repair_percent: 0.85 + medic_kit: + name: "Medic Kit" + repair_cost: 0 + repair_percent: 0.0 + # The amount of times the medic kit can heal 1 heart + max_heals: 10 + lore: + - "<#38E29F>Right-Click a player to heal them" + - "<#38AEE2>Sneak-Right-Click to heal yourself" + recurved_bow: + name: "Recurved Bow" + repair_cost: 1 + repair_percent: 0.9 + recurved_crossbow: + name: "Recurved Crossbow" + repair_cost: 2 + repair_percent: 0.9 + shiv: + name: "Shiv" + repair_cost: 0 + repair_percent: 0.85 + + # SICKLES + diamond_sickle: + name: "Diamond Sickle" + repair_cost: 2 + repair_percent: 0.85 + max_damage: 1400 + iron_sickle: + name: "Iron Sickle" + repair_cost: 1 + repair_percent: 0.9 + max_damage: 300 + stone_sickle: + name: "Stone Sickle" + repair_cost: 0 + repair_percent: 1.0 + max_damage: 100 + flint_sickle: + name: "Flint Sickle" + repair_cost: 0 + repair_percent: 1.0 + max_damage: 50 + + # LEGENDARY TOOLS + blaze_sword: + name: "Blaze Sword" + repair_cost: 5 + repair_percent: 0.95 + prevent_dual_wield: true + ender_giant_blade: + name: "Ender Giant Blade" + lore: + - '<#36D19B>Right-Click while sprinting to charge toward enemies' + repair_cost: 5 + repair_percent: 0.95 + max_damage: 2400 + prevent_dual_wield: true + charge_damage: 5 # Amount of damage to inflict on nearby entities when charging + obsidian_mace: + name: "Obsidian Mace" + repair_cost: 5 + repair_percent: 0.95 + prevent_dual_wield: true + quartz_pickaxe: + name: "Quartz Pickaxe" + repair_cost: 5 + repair_percent: 0.95 + max_damage: 2400 + prevent_dual_wield: true + valkyries_axe: + name: "Valkyries Axe" + repair_cost: 5 + repair_percent: 0.95 + prevent_dual_wield: true + + # ARMOR + snow_boots: + name: "Snow Boots" + lore: + - 'Move quicker in snow' + repair_cost: 1 + repair_percent: 0.97 + rain_boots: + name: "Rain Boots" + lore: + - 'Move quicker in rain' + repair_cost: 1 + repair_percent: 0.97 + diamond_helmet: + name: "Diamond Helmet" + repair_cost: 0 + repair_percent: 1.0 + diamond_chestplate: + name: "Diamond Chestplate" + repair_cost: 0 + repair_percent: 1.0 + diamond_leggings: + name: "Diamond Leggings" + repair_cost: 0 + repair_percent: 1.0 + diamond_boots: + name: "Diamond Boots" + repair_cost: 0 + repair_percent: 1.0 + iron_helmet: + name: "Iron Helmet" + repair_cost: 0 + repair_percent: 1.0 + iron_chestplate: + name: "Iron Chestplate" + repair_cost: 0 + repair_percent: 1.0 + iron_leggings: + name: "Iron Leggings" + repair_cost: 0 + repair_percent: 1.0 + iron_boots: + name: "Iron Boots" + repair_cost: 0 + repair_percent: 1.0 + golden_crown: + name: "Golden Crown" + repair_cost: 0 + repair_percent: 1.0 + golden_guard: + name: "Golden Guard" + repair_cost: 0 + repair_percent: 1.0 + golden_greaves: + name: "Golden Greaves" + repair_cost: 0 + repair_percent: 1.0 + golden_sabatons: + name: "Golden Sabatons" + repair_cost: 0 + repair_percent: 1.0 + netherite_helmet: + name: "Netherite Helmet" + repair_cost: 0 + repair_percent: 1.0 + netherite_chestplate: + name: "Netherite Chestplate" + repair_cost: 0 + repair_percent: 1.0 + netherite_leggings: + name: "Netherite Leggings" + repair_cost: 0 + repair_percent: 1.0 + netherite_boots: + name: "Netherite Boots" + repair_cost: 0 + repair_percent: 1.0 + beekeeper_helmet: + name: "Beekeeper Helmet" + lore: + - 'Prevent bee stings' + repair_cost: 0 + repair_percent: 1.0 + color: 16777215 + beekeeper_chestplate: + name: "Beekeeper Chestplate" + lore: + - 'Prevent bee stings' + repair_cost: 0 + repair_percent: 1.0 + color: 16777215 + beekeeper_leggings: + name: "Beekeeper Leggings" + lore: + - 'Prevent bee stings' + repair_cost: 0 + repair_percent: 1.0 + color: 16777215 + beekeeper_boots: + name: "Beekeeper Boots" + lore: + - 'Prevent bee stings' + repair_cost: 0 + repair_percent: 1.0 + color: 16777215 + reinforced_leather_helmet: + name: "Reinforced Leather Helmet" + repair_cost: 0 + repair_percent: 0.85 + reinforced_leather_tunic: + name: "Reinforced Leather Tunic" + repair_cost: 0 + repair_percent: 0.85 + reinforced_leather_trousers: + name: "Reinforced Leather Trousers" + repair_cost: 0 + repair_percent: 0.85 + reinforced_leather_boots: + name: "Reinforced Leather Boots" + repair_cost: 0 + repair_percent: 0.85 + + # BLOCKS + unlit_campfire: + name: "Campfire" + lore: + - "Unlit" + - "Hit with a stick a few times" + - "to light the campfire" + workbench: + name: "Workbench" + + # DRINKS + dirty_water: + name: "Dirty Water" + color: 0xA46F29 + thirst_level: 7 + salty_water: + name: "Salty Water" + color: 0x3DE294 + thirst_level: 3 + murky_water: + name: "Murky Water" + color: 12769874 + thirst_level: 3 + clean_water: + name: "Clean Water" + color: 1213666 + thirst_level: 14 + purified_water: + name: "Purified Water" + thirst_level: 24 + color: 0x00FFFF + coffee: + name: "Coffee" + thirst_level: 23 + cold_milk: + name: "Cold Milk" + color: 16250871 + thirst_level: 15 + hot_milk: + name: "Hot Milk" + color: 16110486 + thirst_level: 10 + water_bowl: + name: "Water Bowl" + thirst_level: 10 + + # FOOD + suspicious_meat: + name: "Suspicious Meat" + + # MISC + breeding_egg: + name: "Breeding Egg" + coffee_bean: + name: "Coffee Bean" + fermented_skin: + name: "Fermented Skin" diff --git a/src/main/resources/lang_CN.yml b/src/main/resources/lang_CN.yml deleted file mode 100644 index fcf85ba..0000000 --- a/src/main/resources/lang_CN.yml +++ /dev/null @@ -1,231 +0,0 @@ -# SurvivalPlus 语言文件 - -#################### -# 语言: Chinese (CN) -# 作者: FattyMieo, ShaneBee -# 译者: BackWheel -# Date: 28/4/2016 (Refreshed 23/2/2020) -#################### -# -# 你可以自定义本文件 -# -#################### - -#################### -# 系统消息 -#################### - -prefix: "&7[&3Survival&bPlus&7] " -no-perm: "&c你没有权限执行这个指令" - -# 玩家加入游戏后会看到以下插件帮助的消息 -# 你可以更改为你想要的帮助链接 -survival-guide-msg: "&6本服修改了大量原版生存机制,为了让你有更加流畅且愉快的游戏体验,请 " -survival-guide-click-msg: "&b点击这里查看游戏指南" -survival-guide-hover-msg: "点击查看帮助" -survival-guide-link: "http://mineplugin.org/SurvivalPlus" - -resource-pack-accepted: "成功加载服务器资源包." -resource-pack-declined: "**资源包被拒绝**" -resource-pack-apply: "请使用指定服务器资源包." -resource-pack-required: "该材质包将用于显示本服的更多物品." - - -task-must-use-shovel: "你需要使用铲子才能挖掘这个方块." -task-must-use-axe: "你需要使用斧头才能砍伐木头." -task-must-use-pick: "你需要使用镐子才能挖掘矿物." -task-must-use-shear: "你需要使用剪刀才能剪掉这个方块." -task-must-use-hammer: "你需要使用锤子才能进行方块放置." -task-must-use-sickle: "你需要使用镰刀才能进行农作物收获." - -no-rename: "你不能修改这个物品的名字或者对物品进行修复 " -period: "." - -charge: "已充能!" -charge-ready: "准备充能!" -charge-unable: "无法充能." - -lack-of-energy: "装备未完成充能,请等待充能完毕再进行使用" - -arrows-off-hand: "&c你必须副手持箭才能使用弓." -arrows-off-hand-crossbow: "&c你必须副手持箭才能使用弩." -bow-main-hand: "&c你必须主手手持弓." -recurved-bow: "&3弓" -recurved-crossbow: "&3弩" -recurved: "&7反曲" - -fishing-off-hand: "&c请勿双持钓竿,你需要单手持钓竿才能使用." -fishing-main-hand: "&c你必须用主手持钓竿才能使用钓竿." -grappling-off-hand: "&c请勿双持抓钩,你需要单手持抓钩才能使用." -grappling-main-hand: "&c你必须主手持抓钩才能使用抓钩." - -compass-pointed: "已设置指南针航点" -compass-coords: "你的坐标:" -compass-lore: - - ' ' - - '&7左键单击:' - - '&2 查看你所在的位置坐标' - - '&7右键单击:' - - '&2 设置指南针航点' - -players-only: "仅适用于玩家." -toggle-chat-local: "&b开启&a本地&b聊天." -toggle-chat-global: "&b开启&2全服&b聊天." -toggle-chat-disabled: "&c本服务器关闭了聊天模式的切换." -invalid-arg: "无效的参数,请检查指令是否输入错误." - -starved-eat: "你饿了,吃点东西吧." -dehydrated-drink: "你就快脱水了,喝点水吧." -healthboard-title: "状态" -hunger: "饥饿值" -thirst: "口渴值" -energy: "&d能量值" -carbohydrates: "碳水化合物" -protein: "蛋白质" -vitamins: "维他命/矿物质" -nutrition-gui: "食物营养参数GUI" -nutrition-gui-next-page: "&b下一页" -nutrition-gui-last-page: "&b最后一页" -carbohydrates-lack: "吃点谷类或糖来补充碳水化合物吧." -vitamins-lack: "吃点蔬菜来补充维他命/矿物质吧." -protein-lack: "吃点肉或喝点牛奶来补充蛋白质吧." - -healing: "&a治疗中 " -healing-self: "&a自我疗愈&r治疗自己中" -keep: "&a, 保持 " -on-hand: "&a 手持." -being-healed: "&a你正在被治疗 " -stay-still: "&a, 请勿移动." -healing-complete: "治疗完成." -healing-interrupted: "治疗中断." - -# 能量等级 -energy-level-10: "&6您开始感到有些疲倦." -energy-level-6-5: "&6您开始感到有点疲惫和虚弱." -energy-level-3-5: "&e您开始感到头晕, 也许是时候入睡了." -energy-level-2: "&c您开始感到头晕目眩, 赶快休息一下." -energy-level-1: "&c由于缺乏睡眠,你快要猝死了." - -locked: "已锁定" -missing-component: "缺少组件" - -#################### -# 物品名称及介绍 -#################### - -in-main-hand: "位于主手时:" -in-off-hand: "位于副手时:" -attack-speed: "攻击速度" -attack-damage: "攻击伤害" -right-click-sprinting: "奔跑时右键:" -right-click-sneaking: "潜行时右键:" -decrease-hunger-value: "&7> 降低饥饿值" - -hatchet: "燧石斧" -mattock: "燧石镐" -firestriker: "简易打火石" -firestriker-damaged: "损坏的打火石" -firestriker-lore: "&7右键可点燃物品||&bshift+右键进入冶炼界面||&7 -放入你想冶炼的物品||&7 -点击冶炼" -shiv: "匕首" -poisoned-enemy: "&2添毒: 给予敌人中毒效果" -poisoned-retain: "&2中毒效果 &7会持续一段时间" -reduce-50: "&7> 伤害-50%" -grappling-hook: "抓钩" - -hammer: "锤子" -workbench: "工作台" - -valkyrie-axe: "瓦基里女武神之斧" -valkyrie-axe-unable-dual: "&c你无法双持瓦基里女武神之斧" -valkyrie-axe-spin: "&a旋风斩: 手持斧头旋转一圈可对周围敌人造成伤害!" -valkyrie-axe-cooldown: "&7> 冷却时间: 1 秒" - -quartz-breaker: "石英破碎机" -haste: "&e急迫" - -obsidian-mace: "黑曜石重锤" -cripple-hit: "&d重击: 给予命中的敌人 &8虚弱效果" -drain-hit: "&a嗜血: 每次攻击会获得&b2 颗心" -exhausted-slow: "&8沉重: &c你会获得缓慢 II效果" -expire-disarm: "&7> 缴械5秒" -knockback-resistance: "&9+50% 击退距离" - -ender-giant-blade: "末影巨刃" -ender-giant-blade-unable-duel: "&c你无法双持末影巨刃" -ender-giant-blade-charge: "&a充能技: 奔跑时右键会冲刺攻击前方敌人" -ender-giant-blade-cooldown: "&7> 冷却时间: 5 秒" -half-shield-resistance: "&a末影护盾: 获得 &4抗性提升 II效果" -reflecting-coming: "&7> 反弹受到的40%的伤害" - -blaze-sword: "火焰神剑" -blaze-sword-fire-resistance: "&6免疫火焰伤害" -blaze-sword-fiery: "&c灼伤: -3 颗心的生命值" -blaze-sword-spread-fire: "&6点火" -blaze-sword-cost: "&7> 消耗1点耐久" - -reinforced-boots: "强化皮革靴子" -reinforced-tunic: "强化皮革外套" -reinforced-pants: "强化皮革裤子" -reinforced-hat: "强化皮革帽子" - -golden-sabatons: "金靴子" -golden-guard: "金胸甲" -golden-greaves: "金护腿" -golden-crown: "金皇冠" - -fermented-skin: "发酵皮革" -medical-kit: "医疗包" -water-bowl: "&b装满水的碗" - -suspicious-meat: "&e可疑肉" - -# 水瓶名称、描述和颜色 -# 查看RGB颜色: -# http://minecraft.tools/en/potion.php -dirty-water: "水瓶" -dirty-water-lore: "&7装满了污水..." -dirty-water-color: 12769874 -clean-water: "&b水瓶" -clean-water-lore: "&7简单加热过滤的水" -clean-water-color: 1213666 -purified-water: "&b水瓶" -purified-water-lore: "&7纯净水" -purified-water-color: 0x00FFFF - -coffee-bean-name: "咖啡豆" -coffee-name: "&3咖啡" -coffee-color: 9461779 -cold-milk-name: "&b牛奶" -cold-milk-color: 16250871 -hot-milk-name: "&c热牛奶" -hot-milk-color: 15456977 -hot-milk-drink: "&c哎哟,那太烫了!" -breeding-egg-name: "繁殖卵" - -flint_sickle: "&8燧石镰刀" -stone_sickle: "&7石镰刀" -iron_sickle: "&3铁镰刀" -diamond_sickle: "&b钻石镰刀" - -campfire-name: "&a篝火" -campfire-lore: "&b未点燃的篝火||&7使用木棍进行添柴||&7从而点燃篝火" - -bee-helmet-name: '&6养蜂人头盔' -bee-chest-name: '&6养蜂人胸甲' -bee-legs-name: '&6养蜂人护腿' -bee-boots-name: '&6养蜂人靴子' -bee-suit-lore: '&b可防止被蜜蜂攻击' -snow-boots-name: '&x&9&E&C&9&C&A雪靴' -snow-boots-lore: '&b在雪中移动更快' -rain-boots-name: '&x&D&6&E&7&0&3雨鞋' -rain-boots-lore: '&b在雨中移动更快' - -#################### -# 指令提醒 -#################### - -# 是玩家名称的变量! -cmd-player-not-online: "&c 并不在线!" -cmd-heal-self: "&a你已恢复健康状态!" -cmd-heal-by: "&a 为你恢复了健康!" -cmd-heal-other: "&a你为 恢复了健康!" diff --git a/src/main/resources/lang_EN.yml b/src/main/resources/lang_EN.yml index a6ee1c0..59c2d97 100644 --- a/src/main/resources/lang_EN.yml +++ b/src/main/resources/lang_EN.yml @@ -1,230 +1,129 @@ # SurvivalPlus Language File -#################### -# Language: English (EN) -# Authors: FattyMieo, ShaneBee -# Date: 28/4/2016 (Refreshed 13/3/2019) #################### # # Edit this file to your liking # +# This file supports MiniMessage formatting +# See the website for more info: https://docs.advntr.dev/minimessage/format +# +# Using legacy color codes with '&' or '§' are not supported and will error +# #################### #################### # System Messages #################### -prefix: "&7[&3Survival&bPlus&7] " -no-perm: "&cYou do not have permission to perform this command" +prefix: "[SurvivalPlus] " +no-perm: "You do not have permission to perform this command" # When a player joins, they will see this message which links them to a guide to help get them started # IF you want, you can create your own guide and change the link -survival-guide-msg: "&6Our server changes a bunch of vanilla Minecraft mechanics, &6To see our survival guide " -survival-guide-click-msg: "&bClick Here" -survival-guide-hover-msg: "Click for Guide" -survival-guide-link: "https://bitbucket.org/ShaneBeeStudios/SurvivalPlus/wiki/Getting-Started" - -resource-pack-accepted: "Successfully loaded resource pack." -resource-pack-declined: "**Resource pack declined**" -resource-pack-apply: "Please apply the requested Resource Pack." -resource-pack-required: "The resource pack is required for visual effects." +survival-guide-msg: "<#E2E238>Our server changes a bunch of vanilla Minecraft mechanics, to see our survival guide Click Here" +resource-pack-apply: "Please apply the requested Resource Pack." +resource-pack-fail-download: "Failed to download resource pack, talk to server owner!" task-must-use-shovel: "You must use a shovel to dig this." task-must-use-axe: "You must use an axe to chop this." task-must-use-pick: "You must use a pick to mine this." task-must-use-shear: "You must use shears to cut this." -task-must-use-hammer: "You must use a hammer to construct this." +task-must-use-hammer: "You must use a hammer in your off-hand to construct this." task-must-use-sickle: "You must use a sickle to harvest this." -no-rename: "You cannot rename or repair this " -period: "." - charge: "CHARGE!" charge-ready: "Ready to charge!" charge-unable: "Unable to charge immediately." lack-of-energy: "Lack of energy, unable to spin." -arrows-off-hand: "&cYou must have arrows in your off hand." -arrows-off-hand-crossbow: "&cYou must load arrows from your off hand." -bow-main-hand: "&cYou must use a bow with your main hand." -recurved-bow: "&3Bow" -recurved-crossbow: "&3Crossbow" -recurved: "&7Recurved" - -fishing-off-hand: "&cYou must use a fishing pole with an empty off hand." -fishing-main-hand: "&cYou must use a fishing pole with your main hand." -grappling-off-hand: "&cYou must use a grappling hook with an empty off hand." -grappling-main-hand: "&cYou must use a grappling hook with your main hand." - -compass-pointed: "Compass has pointed at" -compass-coords: "Your coordinates are" -compass-lore: - - ' ' - - '&7Left-Click:' - - '&2 See coords of current location' - - '&7Shift-Right-Click:' - - '&2 Set waypoint for compass' - -players-only: "Works on players only." -toggle-chat-local: "&bToggled to &aLocal&b Chat." -toggle-chat-global: "&bToggled to &2Global&b Chat." -toggle-chat-disabled: "&cChat toggle has been disabled on this server." -invalid-arg: "Invalid Arguments." +arrows-off-hand: "You must have arrows in your off hand." +arrows-off-hand-crossbow: "You must load arrows from your off hand." +bow-main-hand: "You must use a bow with your main hand." + +fishing-off-hand: "You must use a fishing pole with an empty off hand." +fishing-main-hand: "You must use a fishing pole with your main hand." +grappling-off-hand: "You must use a grappling hook with an empty off hand." +grappling-main-hand: "You must use a grappling hook with your main hand." + +compass-waypoint-set: "Compass has pointed at %s" +compass-waypoint-get: "You are %s blocks away from your waypoint at %s" +compass-waypoint-unset: "You do not have a waypoint set for this world." + +toggle-chat-local: "Toggled to Local Chat." +toggle-chat-global: "Toggled to Global Chat." starved-eat: "You are starving, eat some food." dehydrated-drink: "You are dehydrated, drink some water." healthboard-title: "Status" hunger: "Hunger" thirst: "Thirst" -energy: "&dEnergy" -carbohydrates: "Carbohydrates" +energy: "Energy" +nutrients: "Nutrients" +carbohydrates: "Carbs" protein: "Protein" -vitamins: "Vitamins and Minerals" +vitamins: "Vitamins" nutrition-gui: "Nutrition GUI" -nutrition-gui-next-page: "&bNext Page" -nutrition-gui-last-page: "&bLast Page" +nutrition-gui-next-page: "Next Page" +nutrition-gui-last-page: "Last Page" carbohydrates-lack: "Eat your grains and sugar." vitamins-lack: "Eat your vegetables and fruit." protein-lack: "Eat your meat, poultry, and dairy." -healing: "&aHealing " -healing-self: "&aHealing &ryourself" -keep: "&a, keep " -on-hand: "&a on hand." -being-healed: "&aYou are being healed by " -stay-still: "&a, stay still." -healing-complete: "Healing complete." -healing-interrupted: "Healing interrupted." +healing-other: "Healing %s, heep Medic Kit on hand." +healing-self: "Healing yourself, keep Medic Kit on hand." +healing-being-healed: "You are being healed by %s" +healing-complete: "Healing complete." +healing-interrupted: "Healing interrupted." # Energy Level -energy-level-10: "&6You are starting to feel a little tired." -energy-level-6-5: "&6You are starting to feel a little worn out and weak." -energy-level-3-5: "&eYou are starting to feel a little nauseous, maybe it's time to get some sleep." -energy-level-2: "&cYou are starting to feel really sick, you should get some rest." -energy-level-1: "&cYour lack of sleep is really taking a toll on you." - -locked: "Locked" -missing-component: "Missing Component" +energy-level-10: "You are starting to feel a little tired." +energy-level-6-5: "You are starting to feel a little worn out and weak." +energy-level-3-5: "You are starting to feel a little nauseous, maybe it's time to get some sleep." +energy-level-2: "You are starting to feel really sick, you should get some rest." +energy-level-1: "Your lack of sleep is really taking a toll on you." #################### # Item Details #################### -in-main-hand: "When in main hand:" -in-off-hand: "When in off hand:" -attack-speed: "Attack Speed" -attack-damage: "Attack Damage" +# '%s' Will be replaced with the name of the item +prevent-dual-wield: "Unable to dual-wield with %s" + right-click-sprinting: "Right Click when sprinting:" right-click-sneaking: "Right Click when sneaking:" -decrease-hunger-value: "&7> Decreases hunger value" - -hatchet: "Hatchet" -mattock: "Mattock" -firestriker: "Firestriker" -firestriker-damaged: "Damaged Firestriker" -firestriker-lore: "&7Right-Click to burn things||&bSneak-Right-Click for portable smelter||&7 -Put smeltable into input slot||&7 -Click output slot to smelt" -shiv: "Shiv" -poisoned-enemy: "&2Poisoned: Poison enemy on hit" -poisoned-retain: "&2Poisoning Effect &7retains" -reduce-50: "&7> Reduce chance by 50%" -grappling-hook: "Grappling Hook" - -hammer: "Hammer" -workbench: "Workbench" - -valkyrie-axe: "Valkyrie's Axe" -valkyrie-axe-unable-dual: "&cUnable to dual-wield with Valkyrie's Axe" -valkyrie-axe-spin: "&aSpin: Spin your axe in a circle to attack all nearby enemies!" -valkyrie-axe-cooldown: "&7> Cooldown: 1 second" +decrease-hunger-value: " Decreases hunger value" + +poisoned-enemy: "Poisoned: Poison enemy on hit" +poisoned-retain: "Poisoning Effect retains" +reduce-50: " Reduce chance by 50%" + +valkyrie-axe-spin: "Spin: Spin your axe in a circle to attack all nearby enemies!" +valkyrie-axe-cooldown: " Cooldown: 1 second" quartz-breaker: "Quartz Breaker" -haste: "&eHaste" - -obsidian-mace: "Obsidian Mace" -cripple-hit: "&dCripple: Enemies hit become &8weakened" -drain-hit: "&aDrain: Gain &b2 hearts&a per hit" -exhausted-slow: "&8Exhausted: &cSlowness II" -expire-disarm: "&7> Expires after disarming for 5 seconds" -knockback-resistance: "&9+50% Knockback Resistance" - -ender-giant-blade: "Ender Giant Blade" -ender-giant-blade-unable-duel: "&cUnable to dual-wield with the Ender Giant Blade" -ender-giant-blade-charge: "&aCharge: Sprint forward, attack enemies in the way" -ender-giant-blade-cooldown: "&7> Cooldown: 5 seconds" -half-shield-resistance: "&aHalf-Shield: Gains &4Resistance II" -reflecting-coming: "&7> Reflecting incoming damage by 40%" - -blaze-sword: "Blaze Sword" -blaze-sword-fire-resistance: "&6Fire Resistance" -blaze-sword-fiery: "&cFiery: -3 Hearts" -blaze-sword-spread-fire: "&6Spread fire on the ground" -blaze-sword-cost: "&7> Costs 1 Durability" - -reinforced-boots: "Reinforced Leather Boots" -reinforced-tunic: "Reinforced Leather Tunic" -reinforced-pants: "Reinforced Leather Trousers" -reinforced-hat: "Reinforced Leather Hat" - -golden-sabatons: "Golden Sabatons" -golden-guard: "Golden Guard" -golden-greaves: "Golden Greaves" -golden-crown: "Golden Crown" - -fermented-skin: "Fermented Skin" -medical-kit: "Medical Kit" -water-bowl: "&bWater Bowl" - -suspicious-meat: "&eSuspicious Meat" - -# Water bottle names, lore and color -# I used this site to get the RGB color codes: -# http://minecraft.tools/en/potion.php -dirty-water: "Water Bottle" -dirty-water-lore: "&7Dirty" -dirty-water-color: 12769874 -clean-water: "&bWater Bottle" -clean-water-lore: "&7Clean" -clean-water-color: 1213666 -purified-water: "&bWater Bottle" -purified-water-lore: "&7Purified" -purified-water-color: 0x00FFFF - -coffee-bean-name: "Coffee Bean" -coffee-name: "&3Coffee" -coffee-color: 9461779 -cold-milk-name: "&bCold Milk" -cold-milk-color: 16250871 -hot-milk-name: "&cHot Milk" -hot-milk-color: 15456977 -hot-milk-drink: "&cOUCH, that was hot!" -breeding-egg-name: "Breeding Egg" - -flint_sickle: "&8Flint Sickle" -stone_sickle: "&7Stone Sickle" -iron_sickle: "&3Iron Sickle" -diamond_sickle: "&bDiamond Sickle" - -campfire-name: "&aCampfire" -campfire-lore: "&bUnlit||&7Hit with a stick a few times||&7to light the campfire" - -bee-helmet-name: '&6Beekeeper Helmet' -bee-chest-name: '&6Beekeeper Chestplate' -bee-legs-name: '&6Beekeeper Leggings' -bee-boots-name: '&6Beekeeper Boots' -bee-suit-lore: '&bPrevent bee stings' -snow-boots-name: '&x&9&E&C&9&C&ASnow Boots' -snow-boots-lore: '&bMove quicker in snow' -rain-boots-name: '&x&D&6&E&7&0&3Rain Boots' -rain-boots-lore: '&bMove quicker in rain' +haste: "Haste" + +cripple-hit: "Cripple: Enemies hit become weakened" +drain-hit: "Drain: Gain 2 hearts per hit" +exhausted-slow: "Exhausted: Slowness II" +expire-disarm: " Expires after disarming for 5 seconds" +knockback-resistance: "+50% Knockback Resistance" + +half-shield-resistance: "Half-Shield: Gains Resistance II" +reflecting-coming: " Reflecting incoming damage by 40%" + +blaze-sword-fire-resistance: "Fire Resistance" +blaze-sword-fiery: "Fiery: -3 Hearts" +blaze-sword-spread-fire: "Spread fire on the ground" +blaze-sword-cost: " Costs 1 Durability" #################### # Commands #################### -# will be replaced with a player name! -cmd-player-not-online: "&cIt appears is not online!" -cmd-heal-self: "&aYou have been healed!" -cmd-heal-by: "&aYou have been healed by !" -cmd-heal-other: "&aYou have headed !" +# %s will be replaced with a player name! +cmd-heal-self: "You have been healed!" +cmd-heal-by: "You have been healed by %s!" +cmd-heal-other: "You have healed %s!" diff --git a/src/main/resources/paper-plugin.yml b/src/main/resources/paper-plugin.yml new file mode 100644 index 0000000..710354a --- /dev/null +++ b/src/main/resources/paper-plugin.yml @@ -0,0 +1,13 @@ +name: SurvivalPlus +version: '${version}' +main: com.shanebeestudios.survival.plugin.SurvivalPlugin +description: "A fun new way to change mechanics of Minecraft" +authors: [ShaneBee] +website: 'https://github.com/ShaneBeeStudios/SurvivalPlus' +bootstrapper: com.shanebeestudios.survival.plugin.SurvivalBootstrap +api-version: '1.21.4' +dependencies: + server: + PlaceholderAPI: + load: BEFORE + required: false diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml deleted file mode 100644 index 35bfe6b..0000000 --- a/src/main/resources/plugin.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: SurvivalPlus -main: tk.shanebee.survival.Survival -authors: [FattyMieo, ShaneBee] -version: '${project.version}' -api-version: '1.15' -softdepend: - - PlaceholderAPI - - Multiverse-Core - - Oh_the_dungeons_youll_go -commands: - reload-survival: - aliases: [survival-reload] - description: Reload configurations - usage: / - permission: survivalplus.reload - recipes: - description: Unused - usage: / - togglechat: - description: Toggling between Global and Local Chat - usage: / [global|local] - aliases: [tc] - permission: survivalplus.togglechat - status: - description: Checking Hunger and Thirst Status - usage: / - aliases: [stat, s] - snowgen: - description: Regenerates snow layers for all chunks, or toggles real-time snow formation - usage: / [on|off] - permission: survivalplus.snowgen - giveitem: - description: Give a SurvivalPlus item to a player - usage: / - permission: survivalplus.giveitem - aliases: [survivalitem, itemgive] - nutrition: - description: Open the nutrition GUI - usage: / - permission: survivalplus.nutrition.gui - heal: - description: Heal a player - usage: / [player] - permission: survivalplus.heal - playerdata: - description: Adjust player data - usage: / (player) (add/remove/set) (stat) (amount) - permission: survivalplus.playerdata diff --git a/src/main/resources/registry/block-tags.yml b/src/main/resources/registry/block-tags.yml new file mode 100644 index 0000000..1c26e10 --- /dev/null +++ b/src/main/resources/registry/block-tags.yml @@ -0,0 +1,449 @@ +# Block Tags +# This file is used to create some tags the plugin uses. +# Modify this to your liking but be very careful when you do. +# +# This accepts both Minecraft block types `minecraft:stone` +# and block tags prefixed with `#`, ex: `#minecraft:logs` (minecraft or custom) +# +# The names of these sections double as namespaces. +# The `survival_plus` section will create new tags +# Example `requires_shovel` = `survival_plus:requires_shovel` +# +# You can optionally add a `minecraft` section to add blocks to current Minecraft tags +# Example (This would add oak_stairs to the `minecraft:logs` tag): +# minecraft: +# logs: +# - minecraft:oak_stairs + +survival_plus: + concrete: + - minecraft:black_concrete + - minecraft:blue_concrete + - minecraft:brown_concrete + - minecraft:cyan_concrete + - minecraft:gray_concrete + - minecraft:green_concrete + - minecraft:light_blue_concrete + - minecraft:light_gray_concrete + - minecraft:lime_concrete + - minecraft:magenta_concrete + - minecraft:orange_concrete + - minecraft:pink_concrete + - minecraft:purple_concrete + - minecraft:red_concrete + - minecraft:white_concrete + - minecraft:yellow_concrete + cooking_block: + - minecraft:furnace + - minecraft:blast_furnace + - minecraft:smoker + glazed_terracotta: + - minecraft:black_glazed_terracotta + - minecraft:blue_glazed_terracotta + - minecraft:brown_glazed_terracotta + - minecraft:cyan_glazed_terracotta + - minecraft:gray_glazed_terracotta + - minecraft:green_glazed_terracotta + - minecraft:light_blue_glazed_terracotta + - minecraft:light_gray_glazed_terracotta + - minecraft:lime_glazed_terracotta + - minecraft:magenta_glazed_terracotta + - minecraft:orange_glazed_terracotta + - minecraft:pink_glazed_terracotta + - minecraft:purple_glazed_terracotta + - minecraft:red_glazed_terracotta + - minecraft:white_glazed_terracotta + - minecraft:yellow_glazed_terracotta + ores: + - minecraft:coal_ore + - minecraft:copper_ore + - minecraft:deepslate_coal_ore + - minecraft:deepslate_copper_ore + - minecraft:deepslate_diamond_ore + - minecraft:deepslate_emerald_ore + - minecraft:deepslate_gold_ore + - minecraft:deepslate_iron_ore + - minecraft:deepslate_lapis_ore + - minecraft:deepslate_redstone_ore + - minecraft:diamond_ore + - minecraft:emerald_ore + - minecraft:gold_ore + - minecraft:iron_ore + - minecraft:lapis_ore + - minecraft:nether_gold_ore + - minecraft:nether_quartz_ore + - minecraft:redstone_ore + ore_type_block: + - minecraft:coal_block + - minecraft:diamond_block + - minecraft:emerald_block + - minecraft:gold_block + - minecraft:iron_block + - minecraft:lapis_block + - minecraft:quartz_block + - minecraft:redstone_block + - minecraft:netherite_block + stone_type: + - minecraft:stone + - minecraft:cobblestone + - minecraft:mossy_cobblestone + - minecraft:infested_cobblestone + - minecraft:andesite + - minecraft:polished_andesite + - minecraft:diorite + - minecraft:polished_diorite + - minecraft:granite + - minecraft:polished_granite + - minecraft:bricks + - minecraft:nether_bricks + - minecraft:sandstone + - minecraft:chiseled_sandstone + - minecraft:smooth_sandstone + - minecraft:cut_sandstone + - minecraft:red_sandstone + - minecraft:chiseled_red_sandstone + - minecraft:cut_red_sandstone + - minecraft:smooth_red_sandstone + - minecraft:prismarine + - minecraft:prismarine_bricks + - minecraft:dark_prismarine + - minecraft:netherrack + - minecraft:end_stone + - minecraft:end_stone_bricks + - minecraft:purpur_block + - minecraft:purpur_pillar + - minecraft:basalt + - minecraft:polished_basalt + - minecraft:blackstone + - minecraft:polished_blackstone + - minecraft:chiseled_polished_blackstone + - minecraft:chiseled_nether_bricks + - minecraft:cracked_nether_bricks + - minecraft:quartz_bricks + storage_block: + - '#minecraft:shulker_boxes' + - minecraft:chest + - minecraft:ender_chest + - minecraft:trapped_chest + - minecraft:barrel + utility_block: + - minecraft:cartography_table + - minecraft:fletching_table + - minecraft:lectern + - minecraft:loom + - minecraft:stonecutter + - minecraft:grindstone + - minecraft:smithing_table + - minecraft:anvil + - minecraft:enchanting_table + - minecraft:jukebox + - minecraft:note_block + - minecraft:brewing_stand + - minecraft:cauldron + - minecraft:composter + - minecraft:respawn_anchor + - minecraft:lodestone + requires_axe: # Blocks which require an axe to break. + - minecraft:acacia_button + - minecraft:acacia_door + - minecraft:acacia_fence + - minecraft:acacia_fence_gate + - minecraft:acacia_hanging_sign + - minecraft:acacia_log + - minecraft:acacia_planks + - minecraft:acacia_pressure_plate + - minecraft:acacia_sign + - minecraft:acacia_slab + - minecraft:acacia_stairs + - minecraft:acacia_trapdoor + - minecraft:acacia_wall_hanging_sign + - minecraft:acacia_wall_sign + - minecraft:acacia_wood + - minecraft:bamboo + - minecraft:bamboo_block + - minecraft:bamboo_button + - minecraft:bamboo_door + - minecraft:bamboo_fence + - minecraft:bamboo_fence_gate + - minecraft:bamboo_hanging_sign + - minecraft:bamboo_mosaic + - minecraft:bamboo_mosaic_slab + - minecraft:bamboo_mosaic_stairs + - minecraft:bamboo_planks + - minecraft:bamboo_pressure_plate + - minecraft:bamboo_sign + - minecraft:bamboo_slab + - minecraft:bamboo_stairs + - minecraft:bamboo_trapdoor + - minecraft:bamboo_wall_hanging_sign + - minecraft:bamboo_wall_sign + - minecraft:barrel + - minecraft:bee_nest + - minecraft:beehive + - minecraft:birch_button + - minecraft:birch_door + - minecraft:birch_fence + - minecraft:birch_fence_gate + - minecraft:birch_hanging_sign + - minecraft:birch_log + - minecraft:birch_planks + - minecraft:birch_pressure_plate + - minecraft:birch_sign + - minecraft:birch_slab + - minecraft:birch_stairs + - minecraft:birch_trapdoor + - minecraft:birch_wall_hanging_sign + - minecraft:birch_wall_sign + - minecraft:birch_wood + - minecraft:black_banner + - minecraft:black_wall_banner + - minecraft:blue_banner + - minecraft:blue_wall_banner + - minecraft:bookshelf + - minecraft:brown_banner + - minecraft:brown_mushroom_block + - minecraft:brown_wall_banner + - minecraft:campfire + - minecraft:cartography_table + - minecraft:cherry_button + - minecraft:cherry_door + - minecraft:cherry_fence + - minecraft:cherry_fence_gate + - minecraft:cherry_hanging_sign + - minecraft:cherry_log + - minecraft:cherry_planks + - minecraft:cherry_pressure_plate + - minecraft:cherry_sign + - minecraft:cherry_slab + - minecraft:cherry_stairs + - minecraft:cherry_trapdoor + - minecraft:cherry_wall_hanging_sign + - minecraft:cherry_wall_sign + - minecraft:cherry_wood + - minecraft:chest + - minecraft:chiseled_bookshelf + - minecraft:composter + - minecraft:crafting_table + - minecraft:creaking_heart + - minecraft:crimson_button + - minecraft:crimson_door + - minecraft:crimson_fence + - minecraft:crimson_fence_gate + - minecraft:crimson_hanging_sign + - minecraft:crimson_hyphae + - minecraft:crimson_planks + - minecraft:crimson_pressure_plate + - minecraft:crimson_sign + - minecraft:crimson_slab + - minecraft:crimson_stairs + - minecraft:crimson_stem + - minecraft:crimson_trapdoor + - minecraft:crimson_wall_hanging_sign + - minecraft:crimson_wall_sign + - minecraft:cyan_banner + - minecraft:cyan_wall_banner + - minecraft:dark_oak_button + - minecraft:dark_oak_door + - minecraft:dark_oak_fence + - minecraft:dark_oak_fence_gate + - minecraft:dark_oak_hanging_sign + - minecraft:dark_oak_log + - minecraft:dark_oak_planks + - minecraft:dark_oak_pressure_plate + - minecraft:dark_oak_sign + - minecraft:dark_oak_slab + - minecraft:dark_oak_stairs + - minecraft:dark_oak_trapdoor + - minecraft:dark_oak_wall_hanging_sign + - minecraft:dark_oak_wall_sign + - minecraft:dark_oak_wood + - minecraft:daylight_detector + - minecraft:fletching_table + - minecraft:gray_banner + - minecraft:gray_wall_banner + - minecraft:green_banner + - minecraft:green_wall_banner + - minecraft:jukebox + - minecraft:jungle_button + - minecraft:jungle_door + - minecraft:jungle_fence + - minecraft:jungle_fence_gate + - minecraft:jungle_hanging_sign + - minecraft:jungle_log + - minecraft:jungle_planks + - minecraft:jungle_pressure_plate + - minecraft:jungle_sign + - minecraft:jungle_slab + - minecraft:jungle_stairs + - minecraft:jungle_trapdoor + - minecraft:jungle_wall_hanging_sign + - minecraft:jungle_wall_sign + - minecraft:jungle_wood + - minecraft:ladder + - minecraft:lectern + - minecraft:light_blue_banner + - minecraft:light_blue_wall_banner + - minecraft:light_gray_banner + - minecraft:light_gray_wall_banner + - minecraft:lime_banner + - minecraft:lime_wall_banner + - minecraft:loom + - minecraft:magenta_banner + - minecraft:magenta_wall_banner + - minecraft:mangrove_button + - minecraft:mangrove_door + - minecraft:mangrove_fence + - minecraft:mangrove_fence_gate + - minecraft:mangrove_hanging_sign + - minecraft:mangrove_log + - minecraft:mangrove_planks + - minecraft:mangrove_pressure_plate + - minecraft:mangrove_roots + - minecraft:mangrove_sign + - minecraft:mangrove_slab + - minecraft:mangrove_stairs + - minecraft:mangrove_trapdoor + - minecraft:mangrove_wall_hanging_sign + - minecraft:mangrove_wall_sign + - minecraft:mangrove_wood + - minecraft:mushroom_stem + - minecraft:note_block + - minecraft:oak_button + - minecraft:oak_door + - minecraft:oak_fence + - minecraft:oak_fence_gate + - minecraft:oak_hanging_sign + - minecraft:oak_log + - minecraft:oak_planks + - minecraft:oak_pressure_plate + - minecraft:oak_sign + - minecraft:oak_slab + - minecraft:oak_stairs + - minecraft:oak_trapdoor + - minecraft:oak_wall_hanging_sign + - minecraft:oak_wall_sign + - minecraft:oak_wood + - minecraft:orange_banner + - minecraft:orange_wall_banner + - minecraft:pale_oak_button + - minecraft:pale_oak_door + - minecraft:pale_oak_fence + - minecraft:pale_oak_fence_gate + - minecraft:pale_oak_hanging_sign + - minecraft:pale_oak_log + - minecraft:pale_oak_planks + - minecraft:pale_oak_pressure_plate + - minecraft:pale_oak_sign + - minecraft:pale_oak_slab + - minecraft:pale_oak_stairs + - minecraft:pale_oak_trapdoor + - minecraft:pale_oak_wall_hanging_sign + - minecraft:pale_oak_wall_sign + - minecraft:pale_oak_wood + - minecraft:pink_banner + - minecraft:pink_wall_banner + - minecraft:purple_banner + - minecraft:purple_wall_banner + - minecraft:red_banner + - minecraft:red_mushroom_block + - minecraft:red_wall_banner + - minecraft:scaffolding + - minecraft:smithing_table + - minecraft:soul_campfire + - minecraft:spruce_button + - minecraft:spruce_door + - minecraft:spruce_fence + - minecraft:spruce_fence_gate + - minecraft:spruce_hanging_sign + - minecraft:spruce_log + - minecraft:spruce_planks + - minecraft:spruce_pressure_plate + - minecraft:spruce_sign + - minecraft:spruce_slab + - minecraft:spruce_stairs + - minecraft:spruce_trapdoor + - minecraft:spruce_wall_hanging_sign + - minecraft:spruce_wall_sign + - minecraft:spruce_wood + - minecraft:stripped_acacia_log + - minecraft:stripped_acacia_wood + - minecraft:stripped_bamboo_block + - minecraft:stripped_birch_log + - minecraft:stripped_birch_wood + - minecraft:stripped_cherry_log + - minecraft:stripped_cherry_wood + - minecraft:stripped_crimson_hyphae + - minecraft:stripped_crimson_stem + - minecraft:stripped_dark_oak_log + - minecraft:stripped_dark_oak_wood + - minecraft:stripped_jungle_log + - minecraft:stripped_jungle_wood + - minecraft:stripped_mangrove_log + - minecraft:stripped_mangrove_wood + - minecraft:stripped_oak_log + - minecraft:stripped_oak_wood + - minecraft:stripped_pale_oak_log + - minecraft:stripped_pale_oak_wood + - minecraft:stripped_spruce_log + - minecraft:stripped_spruce_wood + - minecraft:stripped_warped_hyphae + - minecraft:stripped_warped_stem + - minecraft:trapped_chest + - minecraft:warped_button + - minecraft:warped_door + - minecraft:warped_fence + - minecraft:warped_fence_gate + - minecraft:warped_hanging_sign + - minecraft:warped_hyphae + - minecraft:warped_planks + - minecraft:warped_pressure_plate + - minecraft:warped_sign + - minecraft:warped_slab + - minecraft:warped_stairs + - minecraft:warped_stem + - minecraft:warped_trapdoor + - minecraft:warped_wall_hanging_sign + - minecraft:warped_wall_sign + - minecraft:white_banner + - minecraft:white_wall_banner + - minecraft:yellow_banner + - minecraft:yellow_wall_banner + requires_pickaxe: # Blocks which require a pickaxe to break. + - '#minecraft:mineable/pickaxe' + requires_shovel: # Blocks which require a shovel to break. + - '#minecraft:mineable/shovel' + requires_shears: # Blocks which require shears to break. + - minecraft:cobweb + - minecraft:tripwire + - minecraft:tnt + - minecraft:mushroom_stem + requires_sickle: # Blocks which require a sickle to break. + - '#minecraft:crops' + - minecraft:melon + - minecraft:pumpkin + - minecraft:chorus_flower + - minecraft:chorus_plant + - minecraft:sweet_berry_bush + - minecraft:cocoa + requires_hammer: # Blocks which require a hammer to place. + - '#minecraft:fence_gates' + - '#minecraft:terracotta' + - '#minecraft:shulker_boxes' + - '#minecraft:beds' + - '#minecraft:logs' + - '#minecraft:stairs' + - '#minecraft:slabs' + - '#minecraft:planks' + - '#minecraft:wooden_pressure_plates' + - '#minecraft:wooden_fences' + - '#minecraft:rails' + - '#minecraft:banners' + - '#minecraft:fences' + - '#minecraft:signs' + - '#survival_plus:glazed_terracotta' + - '#survival_plus:concrete' + - '#survival_plus:stone_type' + - '#survival_plus:cooking_block' + - '#survival_plus:storage_block' + - '#survival_plus:utility_block' + - '#survival_plus:ore_type_block' diff --git a/src/main/resources/registry/enchantment-tags.yml b/src/main/resources/registry/enchantment-tags.yml new file mode 100644 index 0000000..7ba7df5 --- /dev/null +++ b/src/main/resources/registry/enchantment-tags.yml @@ -0,0 +1,14 @@ +# Enchantment Tags +# This file is used to create some tags the plugin uses. +# Modify this to your liking but be very careful when you do. +# +# This accepts both Minecraft enchantment types `minecraft:sharpness` +# and enchantment tags prefixed with `#`, ex: `#minecraft:curse` (minecraft or custom) +# +# The names of these sections double as namespaces. +# The `survival_plus` section will create new tags +# The `minecraft` section will add to vanilla Minecraft enchantment tags. + +minecraft: + in_enchanting_table: # Custom enchantments which can be used in the enchanting table. + - survival_plus:building_reach diff --git a/src/main/resources/registry/item-tags.yml b/src/main/resources/registry/item-tags.yml new file mode 100644 index 0000000..0b4c13d --- /dev/null +++ b/src/main/resources/registry/item-tags.yml @@ -0,0 +1,24 @@ +# Items Tags +# This file is used to create some tags the plugin uses. +# Modify this to your liking but be very careful when you do. +# +# This accepts both Minecraft item types `minecraft:diamond_sword` +# and item tags prefixed with `#`, ex: `#minecraft:swords` (minecraft or custom) +# +# The names of these sections double as namespaces. +# The `survival_plus` section will create new tags +# Example `prevent_duel_wield` = `survival_plus:prevent_duel_wield` +# +# You can optionally add a `minecraft` section to add items to current Minecraft tags +# Example (This would add stick to the `minecraft:swords` tag): +# minecraft: +# swords: +# - minecraft:stick + +survival_plus: + prevent_dual_wield: # Items which cannot dual wield with legendary tools. + - '#minecraft:axes' + - '#minecraft:pickaxes' + - '#minecraft:hoes' + - '#minecraft:shovels' + - '#minecraft:swords' diff --git a/src/main/resources/resource-pack/assets/survival_plus/equipment/gold.json b/src/main/resources/resource-pack/assets/survival_plus/equipment/gold.json new file mode 100644 index 0000000..4538465 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/equipment/gold.json @@ -0,0 +1,19 @@ +{ + "layers": { + "horse_body": [ + { + "texture": "minecraft:gold" + } + ], + "humanoid": [ + { + "texture": "survival_plus:gold" + } + ], + "humanoid_leggings": [ + { + "texture": "minecraft:gold" + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/equipment/reinforced_leather.json b/src/main/resources/resource-pack/assets/survival_plus/equipment/reinforced_leather.json new file mode 100644 index 0000000..d3bf20d --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/equipment/reinforced_leather.json @@ -0,0 +1,25 @@ +{ + "layers": { + "horse_body": [ + { + "texture": "minecraft:leather" + } + ], + "humanoid": [ + { + "texture": "survival_plus:reinforced_leather", + "dyeable": { + "color_when_undyed": -2302756 + } + } + ], + "humanoid_leggings": [ + { + "texture": "survival_plus:reinforced_leather", + "dyeable": { + "color_when_undyed": -2302756 + } + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_boots.json b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_boots.json new file mode 100644 index 0000000..06e8c02 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_boots.json @@ -0,0 +1,161 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_quartz_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_iron_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_netherite_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_redstone_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_copper_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_gold_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_emerald_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_diamond_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_lapis_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_amethyst_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_resin_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "property": "minecraft:trim_material" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_chestplate.json b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_chestplate.json new file mode 100644 index 0000000..9def761 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_chestplate.json @@ -0,0 +1,161 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_quartz_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_iron_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_netherite_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_redstone_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_copper_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_gold_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_emerald_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_diamond_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_lapis_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_amethyst_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate_resin_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/leather_chestplate", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "property": "minecraft:trim_material" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_helmet.json b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_helmet.json new file mode 100644 index 0000000..82ac5ab --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_helmet.json @@ -0,0 +1,161 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_quartz_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_iron_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_netherite_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_redstone_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_copper_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_gold_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_emerald_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_diamond_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_lapis_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_amethyst_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet_resin_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/leather_helmet", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "property": "minecraft:trim_material" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_leggings.json b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_leggings.json new file mode 100644 index 0000000..d2d3d8d --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/beekeeper_leggings.json @@ -0,0 +1,161 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_quartz_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_iron_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_netherite_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_redstone_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_copper_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_gold_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_emerald_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_diamond_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_lapis_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_amethyst_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings_resin_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/leather_leggings", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "property": "minecraft:trim_material" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/blaze_sword.json b/src/main/resources/resource-pack/assets/survival_plus/items/blaze_sword.json new file mode 100644 index 0000000..36f834e --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/blaze_sword.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/blaze_sword" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/breeding_egg.json b/src/main/resources/resource-pack/assets/survival_plus/items/breeding_egg.json new file mode 100644 index 0000000..7484346 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/breeding_egg.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/breeding_egg" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/clean_water.json b/src/main/resources/resource-pack/assets/survival_plus/items/clean_water.json new file mode 100644 index 0000000..5233963 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/clean_water.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "minecraft:item/potion", + "tints": [ + { + "type": "minecraft:dye", + "default": -13083194 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/coffee.json b/src/main/resources/resource-pack/assets/survival_plus/items/coffee.json new file mode 100644 index 0000000..c3face6 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/coffee.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/coffee" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/coffee_bean.json b/src/main/resources/resource-pack/assets/survival_plus/items/coffee_bean.json new file mode 100644 index 0000000..bc82092 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/coffee_bean.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/coffee_bean" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/cold_milk.json b/src/main/resources/resource-pack/assets/survival_plus/items/cold_milk.json new file mode 100644 index 0000000..3746592 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/cold_milk.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/cold_milk", + "tints": [ + { + "type": "minecraft:dye", + "default": -13083194 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/diamond_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/items/diamond_sickle.json new file mode 100644 index 0000000..1f737af --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/diamond_sickle.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/diamond_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/dirty_water.json b/src/main/resources/resource-pack/assets/survival_plus/items/dirty_water.json new file mode 100644 index 0000000..5233963 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/dirty_water.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "minecraft:item/potion", + "tints": [ + { + "type": "minecraft:dye", + "default": -13083194 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/ender_giant_blade.json b/src/main/resources/resource-pack/assets/survival_plus/items/ender_giant_blade.json new file mode 100644 index 0000000..9da87c2 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/ender_giant_blade.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/ender_giant_blade" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/fermented_skin.json b/src/main/resources/resource-pack/assets/survival_plus/items/fermented_skin.json new file mode 100644 index 0000000..2de0686 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/fermented_skin.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/fermented_skin" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/firestriker.json b/src/main/resources/resource-pack/assets/survival_plus/items/firestriker.json new file mode 100644 index 0000000..5651bca --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/firestriker.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/firestriker" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/flint_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/items/flint_sickle.json new file mode 100644 index 0000000..a80584d --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/flint_sickle.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/flint_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/golden_crown.json b/src/main/resources/resource-pack/assets/survival_plus/items/golden_crown.json new file mode 100755 index 0000000..6a858c9 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/golden_crown.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/golden_crown" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/golden_greaves.json b/src/main/resources/resource-pack/assets/survival_plus/items/golden_greaves.json new file mode 100755 index 0000000..59eba29 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/golden_greaves.json @@ -0,0 +1,89 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_quartz_trim" + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_iron_trim" + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_netherite_trim" + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_redstone_trim" + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_copper_trim" + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_gold_trim" + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_emerald_trim" + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_diamond_trim" + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_lapis_trim" + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_amethyst_trim" + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings_resin_trim" + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/golden_leggings" + }, + "property": "minecraft:trim_material" + } +} \ No newline at end of file diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/golden_guard.json b/src/main/resources/resource-pack/assets/survival_plus/items/golden_guard.json new file mode 100755 index 0000000..7478fd9 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/golden_guard.json @@ -0,0 +1,89 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_quartz_trim" + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_iron_trim" + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_netherite_trim" + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_redstone_trim" + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_copper_trim" + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_gold_trim" + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_emerald_trim" + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_diamond_trim" + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_lapis_trim" + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_amethyst_trim" + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate_resin_trim" + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/golden_chestplate" + }, + "property": "minecraft:trim_material" + } +} \ No newline at end of file diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/golden_sabatons.json b/src/main/resources/resource-pack/assets/survival_plus/items/golden_sabatons.json new file mode 100755 index 0000000..245b342 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/golden_sabatons.json @@ -0,0 +1,89 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_quartz_trim" + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_iron_trim" + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_netherite_trim" + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_redstone_trim" + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_copper_trim" + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_gold_trim" + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_emerald_trim" + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_diamond_trim" + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_lapis_trim" + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_amethyst_trim" + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots_resin_trim" + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/golden_boots" + }, + "property": "minecraft:trim_material" + } +} \ No newline at end of file diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/grappling_hook.json b/src/main/resources/resource-pack/assets/survival_plus/items/grappling_hook.json new file mode 100644 index 0000000..9709e8c --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/grappling_hook.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/grappling_hook" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/hammer.json b/src/main/resources/resource-pack/assets/survival_plus/items/hammer.json new file mode 100644 index 0000000..8e5306b --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/hammer.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/hammer" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/hatchet.json b/src/main/resources/resource-pack/assets/survival_plus/items/hatchet.json new file mode 100644 index 0000000..9ca1f99 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/hatchet.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/hatchet" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/hot_milk.json b/src/main/resources/resource-pack/assets/survival_plus/items/hot_milk.json new file mode 100644 index 0000000..f5b9b99 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/hot_milk.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/hot_milk", + "tints": [ + { + "type": "minecraft:dye", + "default": -13083194 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/iron_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/items/iron_sickle.json new file mode 100644 index 0000000..e104cbc --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/iron_sickle.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/iron_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/mattock.json b/src/main/resources/resource-pack/assets/survival_plus/items/mattock.json new file mode 100644 index 0000000..1b4bf94 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/mattock.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/mattock" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/medic_kit.json b/src/main/resources/resource-pack/assets/survival_plus/items/medic_kit.json new file mode 100644 index 0000000..b823655 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/medic_kit.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/medic_kit" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/murky_water.json b/src/main/resources/resource-pack/assets/survival_plus/items/murky_water.json new file mode 100644 index 0000000..5233963 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/murky_water.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "minecraft:item/potion", + "tints": [ + { + "type": "minecraft:dye", + "default": -13083194 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/obsidian_mace.json b/src/main/resources/resource-pack/assets/survival_plus/items/obsidian_mace.json new file mode 100644 index 0000000..4901beb --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/obsidian_mace.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/obsidian_mace" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/purified_water.json b/src/main/resources/resource-pack/assets/survival_plus/items/purified_water.json new file mode 100644 index 0000000..5233963 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/purified_water.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "minecraft:item/potion", + "tints": [ + { + "type": "minecraft:dye", + "default": -13083194 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/quartz_pickaxe.json b/src/main/resources/resource-pack/assets/survival_plus/items/quartz_pickaxe.json new file mode 100644 index 0000000..8dac1b3 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/quartz_pickaxe.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/quartz_pickaxe" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/rain_boots.json b/src/main/resources/resource-pack/assets/survival_plus/items/rain_boots.json new file mode 100644 index 0000000..06e8c02 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/rain_boots.json @@ -0,0 +1,161 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_quartz_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_iron_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_netherite_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_redstone_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_copper_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_gold_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_emerald_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_diamond_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_lapis_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_amethyst_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_resin_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "property": "minecraft:trim_material" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/recurved_bow.json b/src/main/resources/resource-pack/assets/survival_plus/items/recurved_bow.json new file mode 100644 index 0000000..c177116 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/recurved_bow.json @@ -0,0 +1,35 @@ +{ + "model": { + "type": "minecraft:condition", + "on_false": { + "type": "minecraft:model", + "model": "minecraft:item/bow" + }, + "on_true": { + "type": "minecraft:range_dispatch", + "entries": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/bow_pulling_1" + }, + "threshold": 0.65 + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/bow_pulling_2" + }, + "threshold": 0.9 + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/bow_pulling_0" + }, + "property": "minecraft:use_duration", + "scale": 0.05 + }, + "property": "minecraft:using_item" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/recurved_crossbow.json b/src/main/resources/resource-pack/assets/survival_plus/items/recurved_crossbow.json new file mode 100644 index 0000000..87f8923 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/recurved_crossbow.json @@ -0,0 +1,54 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/crossbow_arrow" + }, + "when": "arrow" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/crossbow_firework" + }, + "when": "rocket" + } + ], + "fallback": { + "type": "minecraft:condition", + "on_false": { + "type": "minecraft:model", + "model": "minecraft:item/crossbow" + }, + "on_true": { + "type": "minecraft:range_dispatch", + "entries": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/crossbow_pulling_1" + }, + "threshold": 0.58 + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/crossbow_pulling_2" + }, + "threshold": 1.0 + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/crossbow_pulling_0" + }, + "property": "minecraft:crossbow/pull" + }, + "property": "minecraft:using_item" + }, + "property": "minecraft:charge_type" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_boots.json b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_boots.json new file mode 100644 index 0000000..25b62eb --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_boots.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/reinforced_leather_boots", + "tints": [ + { + "type": "minecraft:dye", + "default": -2302756 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_helmet.json b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_helmet.json new file mode 100644 index 0000000..aa375e5 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_helmet.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/reinforced_leather_helmet", + "tints": [ + { + "type": "minecraft:dye", + "default": -2302756 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_trousers.json b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_trousers.json new file mode 100644 index 0000000..498ec0b --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_trousers.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/reinforced_leather_leggings", + "tints": [ + { + "type": "minecraft:dye", + "default": -2302756 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_tunic.json b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_tunic.json new file mode 100644 index 0000000..1d24f54 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/reinforced_leather_tunic.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/reinforced_leather_chestplate", + "tints": [ + { + "type": "minecraft:dye", + "default": -2302756 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/rock.json b/src/main/resources/resource-pack/assets/survival_plus/items/rock.json new file mode 100644 index 0000000..d55967b --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/rock.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/rock" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/salty_water.json b/src/main/resources/resource-pack/assets/survival_plus/items/salty_water.json new file mode 100644 index 0000000..5233963 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/salty_water.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "minecraft:item/potion", + "tints": [ + { + "type": "minecraft:dye", + "default": -13083194 + } + ] + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/shiv.json b/src/main/resources/resource-pack/assets/survival_plus/items/shiv.json new file mode 100644 index 0000000..77e4e1e --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/shiv.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/shiv" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/snow_boots.json b/src/main/resources/resource-pack/assets/survival_plus/items/snow_boots.json new file mode 100644 index 0000000..06e8c02 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/snow_boots.json @@ -0,0 +1,161 @@ +{ + "model": { + "type": "minecraft:select", + "cases": [ + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_quartz_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:quartz" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_iron_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:iron" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_netherite_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:netherite" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_redstone_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:redstone" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_copper_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:copper" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_gold_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:gold" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_emerald_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:emerald" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_diamond_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:diamond" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_lapis_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:lapis" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_amethyst_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:amethyst" + }, + { + "model": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots_resin_trim", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "when": "minecraft:resin" + } + ], + "fallback": { + "type": "minecraft:model", + "model": "minecraft:item/leather_boots", + "tints": [ + { + "type": "minecraft:dye", + "default": -6265536 + } + ] + }, + "property": "minecraft:trim_material" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/stone_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/items/stone_sickle.json new file mode 100644 index 0000000..3dc661c --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/stone_sickle.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/stone_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/suspicious_meat.json b/src/main/resources/resource-pack/assets/survival_plus/items/suspicious_meat.json new file mode 100644 index 0000000..94c1dae --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/suspicious_meat.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/suspicious_meat" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/unlit_campfire.json b/src/main/resources/resource-pack/assets/survival_plus/items/unlit_campfire.json new file mode 100644 index 0000000..4334790 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/unlit_campfire.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/unlit_campfire" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/valkyries_axe.json b/src/main/resources/resource-pack/assets/survival_plus/items/valkyries_axe.json new file mode 100644 index 0000000..447a417 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/valkyries_axe.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/valkyries_axe" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/items/water_bowl.json b/src/main/resources/resource-pack/assets/survival_plus/items/water_bowl.json new file mode 100644 index 0000000..d941515 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/items/water_bowl.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "survival_plus:item/water_bowl" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/lang/en_us.json b/src/main/resources/resource-pack/assets/survival_plus/lang/en_us.json new file mode 100644 index 0000000..03c7e76 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/lang/en_us.json @@ -0,0 +1,4 @@ +{ + "death.attack.ender_power": "%1$s was charged at by %2$s", + "death.attack.ender_power.item": "%1$s was charged at by %2$s using %3$s" +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/blaze_sword.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/blaze_sword.json new file mode 100755 index 0000000..5fe4ab2 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/blaze_sword.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/blaze_sword" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/breeding_egg.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/breeding_egg.json new file mode 100755 index 0000000..7e070f4 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/breeding_egg.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/breeding_egg" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/coffee.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/coffee.json new file mode 100755 index 0000000..b377cf0 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/coffee.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/coffee" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/coffee_bean.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/coffee_bean.json new file mode 100755 index 0000000..f860433 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/coffee_bean.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/coffee_bean" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/cold_milk.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/cold_milk.json new file mode 100755 index 0000000..6084954 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/cold_milk.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/cold_milk" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/diamond_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/diamond_sickle.json new file mode 100755 index 0000000..a24c403 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/diamond_sickle.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/diamond_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/ender_giant_blade.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/ender_giant_blade.json new file mode 100755 index 0000000..1aa4bc0 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/ender_giant_blade.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/ender_giant_blade" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/fermented_skin.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/fermented_skin.json new file mode 100755 index 0000000..fce998d --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/fermented_skin.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/fermented_skin" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/firestriker.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/firestriker.json new file mode 100755 index 0000000..291d113 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/firestriker.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/firestriker" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/flint_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/flint_sickle.json new file mode 100755 index 0000000..2e7940c --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/flint_sickle.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/flint_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/golden_crown.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/golden_crown.json new file mode 100755 index 0000000..2f2109b --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/golden_crown.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/golden_crown" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/grappling_hook.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/grappling_hook.json new file mode 100755 index 0000000..bc34661 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/grappling_hook.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/grappling_hook" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/hammer.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/hammer.json new file mode 100755 index 0000000..50d8e30 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/hammer.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/hammer" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/hatchet.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/hatchet.json new file mode 100755 index 0000000..913c582 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/hatchet.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/hatchet" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/hot_milk.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/hot_milk.json new file mode 100755 index 0000000..a56dfd2 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/hot_milk.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/hot_milk" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/iron_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/iron_sickle.json new file mode 100755 index 0000000..f2f915b --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/iron_sickle.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/iron_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/mattock.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/mattock.json new file mode 100755 index 0000000..0816f09 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/mattock.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/mattock" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/medic_kit.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/medic_kit.json new file mode 100755 index 0000000..eb90bd1 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/medic_kit.json @@ -0,0 +1,200 @@ +{ + "parent": "block/furnace", + "textures": { + "texture": "survival_plus:item/medic_kit" + }, + "elements": [ + { + "__comment": "Box1", + "from": [ + 0, + 0, + 0 + ], + "to": [ + 16, + 16.5, + 16 + ], + "faces": { + "down": { + "uv": [ + 4, + 0, + 6, + 2 + ], + "texture": "#texture" + }, + "up": { + "uv": [ + 2, + 0, + 4, + 2 + ], + "texture": "#texture" + }, + "north": { + "uv": [ + 2, + 2, + 4, + 4 + ], + "texture": "#texture" + }, + "south": { + "uv": [ + 0, + 2, + 2, + 4 + ], + "texture": "#texture" + }, + "west": { + "uv": [ + 4, + 2, + 6, + 4 + ], + "texture": "#texture" + }, + "east": { + "uv": [ + 6, + 2, + 8, + 4 + ], + "texture": "#texture" + } + } + }, + { + "__comment": "Box2", + "from": [ + 0, + 16.4, + 0 + ], + "to": [ + 16, + 16.401, + 16 + ], + "faces": { + "down": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture" + }, + "up": { + "uv": [ + 4, + 0, + 6, + 2 + ], + "texture": "#texture" + }, + "north": { + "uv": [ + 0, + 12.999, + 16, + 13 + ], + "texture": "#texture" + }, + "south": { + "uv": [ + 0, + 12.999, + 16, + 13 + ], + "texture": "#texture" + }, + "west": { + "uv": [ + 0, + 12.999, + 16, + 13 + ], + "texture": "#texture" + }, + "east": { + "uv": [ + 0, + 12.999, + 16, + 13 + ], + "texture": "#texture" + } + } + } + ], + "display": { + "thirdperson_righthand": { + "scale": [ + 0.2, + 0.2, + 0.2 + ] + }, + "thirdperson_lefthand": { + "scale": [ + 0.0001, + 0.0001, + 0.0001 + ] + }, + "firstperson_righthand": { + "rotation": [ + 2, + 135, + 0 + ], + "translation": [ + -2.086, + 0.4782, + 0 + ], + "scale": [ + 0.25, + 0.25, + 0.25 + ] + }, + "firstperson_lefthand": { + "scale": [ + 0.0001, + 0.0001, + 0.0001 + ] + }, + "ground": { + "scale": [ + 0.2, + 0.2, + 0.2 + ] + }, + "fixed": { + "scale": [ + 0.4, + 0.4, + 0.4 + ] + } + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/obsidian_mace.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/obsidian_mace.json new file mode 100755 index 0000000..1adca96 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/obsidian_mace.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/obsidian_mace" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/quartz_pickaxe.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/quartz_pickaxe.json new file mode 100755 index 0000000..2a0e162 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/quartz_pickaxe.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/quartz_pickaxe" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_boots.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_boots.json new file mode 100755 index 0000000..a8f7113 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_boots.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/reinforced_leather_boots" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_chestplate.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_chestplate.json new file mode 100755 index 0000000..1e62882 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_chestplate.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/reinforced_leather_chestplate" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_helmet.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_helmet.json new file mode 100755 index 0000000..bcb540d --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_helmet.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/reinforced_leather_helmet" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_leggings.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_leggings.json new file mode 100755 index 0000000..5b0bdf5 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/reinforced_leather_leggings.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/reinforced_leather_leggings" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/rock.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/rock.json new file mode 100755 index 0000000..8509cc7 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/rock.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/rock" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/shiv.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/shiv.json new file mode 100755 index 0000000..5dafb2e --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/shiv.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/shiv" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/stone_sickle.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/stone_sickle.json new file mode 100755 index 0000000..ff79211 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/stone_sickle.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/stone_sickle" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/suspicious_meat.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/suspicious_meat.json new file mode 100755 index 0000000..b666731 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/suspicious_meat.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/suspicious_meat" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/unlit_campfire.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/unlit_campfire.json new file mode 100755 index 0000000..2c518d8 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/unlit_campfire.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/unlit_campfire" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/valkyries_axe.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/valkyries_axe.json new file mode 100755 index 0000000..7fea217 --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/valkyries_axe.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/handheld", + "textures": { + "layer0": "survival_plus:item/valkyries_axe" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/models/item/water_bowl.json b/src/main/resources/resource-pack/assets/survival_plus/models/item/water_bowl.json new file mode 100755 index 0000000..d334a7c --- /dev/null +++ b/src/main/resources/resource-pack/assets/survival_plus/models/item/water_bowl.json @@ -0,0 +1,6 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "survival_plus:item/water_bowl" + } +} diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid/gold.png b/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid/gold.png new file mode 100755 index 0000000..b5007d8 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid/gold.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid/reinforced_leather.png b/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid/reinforced_leather.png new file mode 100755 index 0000000..9f97fe7 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid/reinforced_leather.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid_leggings/reinforced_leather.png b/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid_leggings/reinforced_leather.png new file mode 100755 index 0000000..7d8aa8b Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/entity/equipment/humanoid_leggings/reinforced_leather.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/blaze_sword.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/blaze_sword.png new file mode 100755 index 0000000..9fda9ae Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/blaze_sword.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/breeding_egg.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/breeding_egg.png new file mode 100755 index 0000000..37e4873 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/breeding_egg.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/coffee.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/coffee.png new file mode 100755 index 0000000..476253d Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/coffee.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/coffee_bean.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/coffee_bean.png new file mode 100755 index 0000000..f7e7534 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/coffee_bean.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/cold_milk.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/cold_milk.png new file mode 100755 index 0000000..ed72d36 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/cold_milk.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/diamond_sickle.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/diamond_sickle.png new file mode 100755 index 0000000..499dcf8 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/diamond_sickle.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/ender_giant_blade.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/ender_giant_blade.png new file mode 100755 index 0000000..bc5bdae Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/ender_giant_blade.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/fermented_skin.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/fermented_skin.png new file mode 100755 index 0000000..980b69c Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/fermented_skin.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/firestriker.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/firestriker.png new file mode 100755 index 0000000..2b3eef3 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/firestriker.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/flint_sickle.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/flint_sickle.png new file mode 100755 index 0000000..ce9e901 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/flint_sickle.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/golden_crown.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/golden_crown.png new file mode 100755 index 0000000..7e21904 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/golden_crown.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/grappling_hook.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/grappling_hook.png new file mode 100644 index 0000000..bcec15a Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/grappling_hook.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/hammer.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/hammer.png new file mode 100755 index 0000000..23b3ea2 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/hammer.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/hatchet.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/hatchet.png new file mode 100755 index 0000000..19b966d Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/hatchet.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/hot_milk.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/hot_milk.png new file mode 100755 index 0000000..58acc9e Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/hot_milk.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/iron_sickle.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/iron_sickle.png new file mode 100755 index 0000000..6ccf374 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/iron_sickle.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/mattock.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/mattock.png new file mode 100755 index 0000000..9afd191 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/mattock.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/medic_kit.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/medic_kit.png new file mode 100644 index 0000000..3040e4f Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/medic_kit.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/melon_slice.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/melon_slice.png new file mode 100644 index 0000000..dc3c792 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/melon_slice.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/obsidian_mace.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/obsidian_mace.png new file mode 100755 index 0000000..5262fd2 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/obsidian_mace.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/quartz_pickaxe.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/quartz_pickaxe.png new file mode 100755 index 0000000..b6c49fd Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/quartz_pickaxe.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_boots.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_boots.png new file mode 100755 index 0000000..d618f10 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_boots.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_chestplate.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_chestplate.png new file mode 100755 index 0000000..b9db7d6 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_chestplate.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_helmet.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_helmet.png new file mode 100755 index 0000000..aa9a42f Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_helmet.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_leggings.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_leggings.png new file mode 100755 index 0000000..ff7965f Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/reinforced_leather_leggings.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/rock.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/rock.png new file mode 100755 index 0000000..d3dd08a Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/rock.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/shiv.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/shiv.png new file mode 100755 index 0000000..6a20ec0 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/shiv.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/stone_sickle.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/stone_sickle.png new file mode 100755 index 0000000..43fc68a Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/stone_sickle.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/suspicious_meat.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/suspicious_meat.png new file mode 100644 index 0000000..9a6c4b8 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/suspicious_meat.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/unlit_campfire.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/unlit_campfire.png new file mode 100644 index 0000000..5791348 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/unlit_campfire.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/valkyries_axe.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/valkyries_axe.png new file mode 100755 index 0000000..dc77760 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/valkyries_axe.png differ diff --git a/src/main/resources/resource-pack/assets/survival_plus/textures/item/water_bowl.png b/src/main/resources/resource-pack/assets/survival_plus/textures/item/water_bowl.png new file mode 100755 index 0000000..1fba2e1 Binary files /dev/null and b/src/main/resources/resource-pack/assets/survival_plus/textures/item/water_bowl.png differ diff --git a/src/main/resources/resource-pack/license.txt b/src/main/resources/resource-pack/license.txt new file mode 100755 index 0000000..4741623 --- /dev/null +++ b/src/main/resources/resource-pack/license.txt @@ -0,0 +1,14 @@ + +#Survival Plus Resource Pack + +A lot of inspiration for this plugin was taken from TerraFirmaCraft +That being said, we have used some of their textures as well (ex: The sickles are from TFC's Scythe) + + +Licenses for TerraFirmaCraft can be found here + +Original Mod: +- https://github.com/Deadrik/TFCraft/blob/master/license.txt + +Revamped Mod: +- https://github.com/TerraFirmaCraft/TerraFirmaCraft/blob/master/LICENSE.txt diff --git a/src/main/resources/resource-pack/pack.mcmeta b/src/main/resources/resource-pack/pack.mcmeta new file mode 100755 index 0000000..3f9ccad --- /dev/null +++ b/src/main/resources/resource-pack/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 46, + "description": "SurvivalPlus Custom Items" + } +} diff --git a/src/main/resources/resource-pack/pack.png b/src/main/resources/resource-pack/pack.png new file mode 100644 index 0000000..69f9119 Binary files /dev/null and b/src/main/resources/resource-pack/pack.png differ