Compare commits

..
11 Commits
Author SHA1 Message Date
stijn 97c711ea29 Updated VillagerShopUI to 1.21.6 (using Cosmos) 2025-06-27 20:39:21 +02:00
auto 3fc8561265 Add Jenkinsfile for CI pipeline
Set up a Jenkins pipeline with stages for building using Gradle, archiving artifacts, and sending notifications to Discord. This configuration ensures that builds are processed with Gradle and results are communicated effectively for branches 'main' and 'master'.
2024-08-20 21:12:13 +02:00
auto ab9a7b22cb Refactor code for creating and retrieving villager profession
Removed the deprecated use of OldEnum and Villager.Profession.valueOf in creating villagers and retrieving their professions. Refactored code to use the more updated NamespacedKey and Registry methods to handle these tasks, enhancing both code stability and maintainability.
2024-07-20 01:35:20 +02:00
auto 30a7d85f3d Update configuration file paths and enum usage
The configuration files for the VillagerShopUI have been relocated from the home directory to a mounted volume at "/mnt/configs/VillagerShopUI". Also, an outdated way of accessing enums in the 'CommandCreateVillager' class has been updated to use 'OldEnum' instead of 'Enum'.
2024-07-19 23:33:33 +02:00
auto dc4b618a80 Remove redundant null check in WorthConfig
The revised version of WorthConfig.java removes a redundant check for null material. This null check was duplicated due to a merge.
2024-07-09 18:34:18 +02:00
auto 09cfc91dc0 Merge remote-tracking branch 'origin/master' 2024-07-09 18:33:05 +02:00
auto 9f18b41925 Update build configurations and add villager messaging functionality
This commit updates the version of the shadow plugin and the Java language version in the build configuration. Modifications have been made in the shadowJar configuration. The main feature in this commit is the introduction of a messaging system for villagers. This includes the necessary methods and fields in the existing villager classes and the addition of a new VillagerMessagesConfig class. Messages can now be added via config and each villager type can potentially return a random message when interacted with. A sound effect has also been added to correlate with the villager type. The WorthConfig class has been additionally refined to handle invalid material cases.
2024-07-09 18:32:50 +02:00
Len c8802b9e13 Update gradle 2023-12-31 16:36:39 +01:00
Len ae3baa5b81 Do not error when loading in null materials 2023-12-31 16:35:12 +01:00
auto cbae508f04 Added random variations of Tropical fish buckets and Axolotl buckets for the trade gui 2023-09-10 23:06:36 +02:00
auto cd2b23c7c2 Fix <points> placeholder being in trade gui 2023-09-10 22:50:36 +02:00
28 changed files with 521 additions and 229 deletions
Vendored
+26
View File
@@ -0,0 +1,26 @@
pipeline {
agent any
stages {
stage('Gradle') {
steps {
sh 'bash gradlew build'
}
}
stage('Archive') {
steps {
archiveArtifacts artifacts: 'build/libs/', followSymlinks: false
}
}
stage('discord') {
when {
anyOf {
branch 'main'
branch 'master'
}
}
steps {
discordSend description: "Build: ${BUILD_NUMBER}", showChangeset: true, result: currentBuild.currentResult, title: currentBuild.fullProjectName, webhookURL: env.discordwebhook
}
}
}
}
+15 -16
View File
@@ -1,8 +1,6 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
plugins { plugins {
id("java") id("java")
id("com.github.johnrengelman.shadow") version "7.1.0" id("com.github.johnrengelman.shadow") version "7.1.1"
id("maven-publish") id("maven-publish")
} }
@@ -14,7 +12,7 @@ apply<JavaLibraryPlugin>()
java { java {
toolchain { toolchain {
languageVersion.set(JavaLanguageVersion.of(17)) languageVersion.set(JavaLanguageVersion.of(21))
} }
} }
@@ -27,9 +25,12 @@ publishing {
repositories{ repositories{
maven { maven {
name = "alttd" name = "nexus"
url = uri("https://repo.destro.xyz/snapshots") url = uri("https://repo.alttd.com/repository/alttd-snapshot/")
credentials(PasswordCredentials::class) credentials {
username = project.property("alttdSnapshotUsername") as String
password = project.property("alttdSnapshotPassword") as String
}
} }
} }
} }
@@ -44,24 +45,22 @@ tasks {
} }
shadowJar { shadowJar {
dependsOn(getByName("relocateJars") as ConfigureShadowRelocation) archiveFileName.set("${rootProject.name}.jar")
archiveFileName.set("${project.name}-${project.version}.jar") manifest {
minimize() attributes("Main-Class" to "VillagerUI")
configurations = listOf(project.configurations.shadow.get()) }
} }
build { build {
dependsOn(shadowJar) dependsOn(shadowJar)
} }
create<ConfigureShadowRelocation>("relocateJars") {
target = shadowJar.get()
prefix = "${project.name}.lib"
}
} }
dependencies { dependencies {
compileOnly("com.alttd:Galaxy-API:1.19-R0.1-SNAPSHOT") compileOnly("com.alttd.cosmos:cosmos-api:1.21.6-R0.1-SNAPSHOT") {
isChanging = true
}
compileOnly("com.github.milkbowl:VaultAPI:1.7") { compileOnly("com.github.milkbowl:VaultAPI:1.7") {
exclude("org.bukkit","bukkit") exclude("org.bukkit","bukkit")
} }
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored
+159 -110
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -17,67 +17,101 @@
# #
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # 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/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"` APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # 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"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
@@ -106,80 +140,95 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD=$( ulimit -H -n ) ||
MAX_FD="$MAX_FD_LIMIT" warn "Could not query maximum file descriptor limit"
fi esac
ulimit -n $MAX_FD case $MAX_FD in #(
if [ $? -ne 0 ] ; then '' | soft) :;; #(
warn "Could not set maximum file descriptor limit: $MAX_FD" *)
fi ulimit -n "$MAX_FD" ||
else warn "Could not set maximum file descriptor limit to $MAX_FD"
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 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
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@" exec "$JAVACMD" "$@"
+12 -1
View File
@@ -1,10 +1,21 @@
rootProject.name = "VillagerShopUI" rootProject.name = "VillagerShopUI"
val nexusUser = providers.gradleProperty("alttdSnapshotUsername").get()
val nexusPass = providers.gradleProperty("alttdSnapshotPassword").get()
dependencyResolutionManagement { dependencyResolutionManagement {
repositories { repositories {
mavenLocal() mavenLocal()
mavenCentral() mavenCentral()
maven("https://repo.destro.xyz/snapshots") // Altitude - Galaxy maven {
name = "nexus"
url = uri("https://repo.alttd.com/repository/alttd-snapshot/")
credentials {
username = nexusUser
password = nexusPass
}
}
maven("https://repo.destro.xyz/snapshots") // Cosmos
maven("https://jitpack.io") { // Vault maven("https://jitpack.io") { // Vault
content { includeGroup("com.github.milkbowl") } content { includeGroup("com.github.milkbowl") }
} }
@@ -64,7 +64,7 @@ public class BuyGUI extends GUIMerchant {
int transPts = itemPts * amount; int transPts = itemPts * amount;
EconUser econUser = EconUser.getUser(player.getUniqueId()); EconUser econUser = EconUser.getUser(player.getUniqueId());
if (econUser == null) { if (econUser == null) {
player.sendMiniMessage(Config.LOADING_ECON_DATA, null); player.sendRichMessage(Config.LOADING_ECON_DATA);
return; return;
} }
int oldPoints = econUser.getPointsMap().getOrDefault(villagerType.getName(), 0); int oldPoints = econUser.getPointsMap().getOrDefault(villagerType.getName(), 0);
@@ -87,14 +87,14 @@ public class BuyGUI extends GUIMerchant {
if ((newTime - 120) > lastClicked) if ((newTime - 120) > lastClicked)
lastClicked = newTime; lastClicked = newTime;
else { else {
player.sendMiniMessage(Config.CLICKING_TOO_FAST, null); player.sendRichMessage(Config.CLICKING_TOO_FAST);
return; return;
} }
Economy econ = VillagerUI.getInstance().getEconomy(); Economy econ = VillagerUI.getInstance().getEconomy();
double balance = econ.getBalance(player); double balance = econ.getBalance(player);
if (balance < purchase.price()) { if (balance < purchase.price()) {
player.sendMiniMessage(Config.NOT_ENOUGH_MONEY, TagResolver.resolver( player.sendRichMessage(Config.NOT_ENOUGH_MONEY, TagResolver.resolver(
Placeholder.unparsed("money", String.valueOf(Utilities.round(balance, 2))), Placeholder.unparsed("money", String.valueOf(Utilities.round(balance, 2))),
Placeholder.unparsed("price", String.format("%,.2f", purchase.price())) Placeholder.unparsed("price", String.format("%,.2f", purchase.price()))
)); ));
@@ -113,7 +113,7 @@ public class BuyGUI extends GUIMerchant {
ref.space += itemStack.getMaxStackSize() - itemStack.getAmount(); ref.space += itemStack.getMaxStackSize() - itemStack.getAmount();
}); });
if (ref.space < purchase.amount()) { if (ref.space < purchase.amount()) {
player.sendMiniMessage(Config.NOT_ENOUGH_SPACE, TagResolver.resolver( player.sendRichMessage(Config.NOT_ENOUGH_SPACE, TagResolver.resolver(
Placeholder.unparsed("space", String.valueOf(ref.space)), Placeholder.unparsed("space", String.valueOf(ref.space)),
Placeholder.unparsed("amount", String.valueOf(purchase.amount())) Placeholder.unparsed("amount", String.valueOf(purchase.amount()))
)); ));
@@ -125,7 +125,7 @@ public class BuyGUI extends GUIMerchant {
player.getInventory().addItem(new ItemStack(purchase.material(), purchase.amount())); player.getInventory().addItem(new ItemStack(purchase.material(), purchase.amount()));
int newPoints = econUser.getPointsMap().get(villagerType.getName()); int newPoints = econUser.getPointsMap().get(villagerType.getName());
player.sendMiniMessage(Config.PURCHASED_ITEM, TagResolver.resolver( player.sendRichMessage(Config.PURCHASED_ITEM, TagResolver.resolver(
Placeholder.unparsed("amount", String.valueOf(purchase.amount())), Placeholder.unparsed("amount", String.valueOf(purchase.amount())),
Placeholder.unparsed("item", Utilities.capitalize(purchase.material().name() Placeholder.unparsed("item", Utilities.capitalize(purchase.material().name()
.toLowerCase().replaceAll("_", " "))), .toLowerCase().replaceAll("_", " "))),
@@ -94,7 +94,7 @@ public class SellGUI extends GUIMerchant {
private void sell(VillagerType villagerType, Player player, Material material, int amount, Price price, boolean bulk) { private void sell(VillagerType villagerType, Player player, Material material, int amount, Price price, boolean bulk) {
EconUser econUser = EconUser.getUser(player.getUniqueId()); EconUser econUser = EconUser.getUser(player.getUniqueId());
if (econUser == null) { if (econUser == null) {
player.sendMiniMessage(Config.LOADING_ECON_DATA, null); player.sendRichMessage(Config.LOADING_ECON_DATA);
return; return;
} }
@@ -120,12 +120,12 @@ public class SellGUI extends GUIMerchant {
if ((newTime - 120) > lastClicked) if ((newTime - 120) > lastClicked)
lastClicked = newTime; lastClicked = newTime;
else { else {
player.sendMiniMessage(Config.CLICKING_TOO_FAST, null); player.sendRichMessage(Config.CLICKING_TOO_FAST);
return; return;
} }
PlayerInventory inventory = player.getInventory(); PlayerInventory inventory = player.getInventory();
if (countTotalBlocksInInventory(inventory, purchase.material()) < purchase.amount()) { if (countTotalBlocksInInventory(inventory, purchase.material()) < purchase.amount()) {
player.sendMiniMessage(Config.NOT_ENOUGH_ITEMS, TagResolver.resolver( player.sendRichMessage(Config.NOT_ENOUGH_ITEMS, TagResolver.resolver(
Placeholder.unparsed("type", purchase.material().name()), Placeholder.unparsed("type", purchase.material().name()),
Placeholder.unparsed("amount", String.valueOf(purchase.amount())))); Placeholder.unparsed("amount", String.valueOf(purchase.amount()))));
return; return;
@@ -153,7 +153,7 @@ public class SellGUI extends GUIMerchant {
int newPoints = econUser.getPointsMap().get(villagerType.getName()); int newPoints = econUser.getPointsMap().get(villagerType.getName());
player.sendMiniMessage(Config.SOLD_ITEM, TagResolver.resolver( player.sendRichMessage(Config.SOLD_ITEM, TagResolver.resolver(
Placeholder.unparsed("amount", String.valueOf(purchase.amount())), Placeholder.unparsed("amount", String.valueOf(purchase.amount())),
Placeholder.unparsed("item", Utilities.capitalize(purchase.material().name() Placeholder.unparsed("item", Utilities.capitalize(purchase.material().name()
.toLowerCase().replaceAll("_", " "))), .toLowerCase().replaceAll("_", " "))),
@@ -15,10 +15,15 @@ import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Axolotl;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.TropicalFish;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.AxolotlBucketMeta;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.TropicalFishBucketMeta;
import java.util.*; import java.util.*;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@@ -61,7 +66,7 @@ public class TradeGUI extends GUIMerchant {
private void trade(BlackMarketVillagerType villagerType, Player player, Material material, int amount, Double price) { private void trade(BlackMarketVillagerType villagerType, Player player, Material material, int amount, Double price) {
EconUser econUser = EconUser.getUser(player.getUniqueId()); EconUser econUser = EconUser.getUser(player.getUniqueId());
if (econUser == null) { if (econUser == null) {
player.sendMiniMessage(Config.LOADING_ECON_DATA, null); player.sendRichMessage(Config.LOADING_ECON_DATA);
return; return;
} }
@@ -78,7 +83,7 @@ public class TradeGUI extends GUIMerchant {
Placeholder.unparsed("item_name", material.name()) Placeholder.unparsed("item_name", material.name())
))); )));
List<Component> lore = new ArrayList<>(); List<Component> lore = new ArrayList<>();
for (String entry : Config.TRANSACTION_ITEM_DESCRIPTION) { for (String entry : Config.TRANSACTION_ITEM_DESCRIPTION_NO_POINTS) {
lore.add(miniMessage.deserialize(entry, TagResolver.resolver( lore.add(miniMessage.deserialize(entry, TagResolver.resolver(
Placeholder.unparsed("amount", String.valueOf(amount)), Placeholder.unparsed("amount", String.valueOf(amount)),
Placeholder.unparsed("price", String.format("%,.2f", price)) Placeholder.unparsed("price", String.format("%,.2f", price))
@@ -94,13 +99,13 @@ public class TradeGUI extends GUIMerchant {
if ((newTime - 120) > lastClicked) if ((newTime - 120) > lastClicked)
lastClicked = newTime; lastClicked = newTime;
else { else {
player.sendMiniMessage(Config.CLICKING_TOO_FAST, null); player.sendRichMessage(Config.CLICKING_TOO_FAST);
return; return;
} }
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
if (villagerType.getRemainingTrades(uuid) <= 0) { if (villagerType.getRemainingTrades(uuid) <= 0) {
player.sendMiniMessage(Config.NO_TRADES_REMAINING, null); player.sendRichMessage(Config.NO_TRADES_REMAINING);
return; return;
} }
@@ -108,7 +113,7 @@ public class TradeGUI extends GUIMerchant {
double balance = econ.getBalance(player); double balance = econ.getBalance(player);
if (balance < price) { if (balance < price) {
player.sendMiniMessage(Config.NOT_ENOUGH_MONEY, TagResolver.resolver( player.sendRichMessage(Config.NOT_ENOUGH_MONEY, TagResolver.resolver(
Placeholder.unparsed("money", String.valueOf(Utilities.round(balance, 2))), Placeholder.unparsed("money", String.valueOf(Utilities.round(balance, 2))),
Placeholder.unparsed("price", String.format("%,.2f", price)) Placeholder.unparsed("price", String.format("%,.2f", price))
)); ));
@@ -125,7 +130,7 @@ public class TradeGUI extends GUIMerchant {
atomicInteger.addAndGet(itemStack.getMaxStackSize() - itemStack.getAmount()); atomicInteger.addAndGet(itemStack.getMaxStackSize() - itemStack.getAmount());
}); });
if (atomicInteger.get() < amount) { if (atomicInteger.get() < amount) {
player.sendMiniMessage(Config.NOT_ENOUGH_SPACE, TagResolver.resolver( player.sendRichMessage(Config.NOT_ENOUGH_SPACE, TagResolver.resolver(
Placeholder.unparsed("space", String.valueOf(atomicInteger.get())), Placeholder.unparsed("space", String.valueOf(atomicInteger.get())),
Placeholder.unparsed("amount", String.valueOf(amount)) Placeholder.unparsed("amount", String.valueOf(amount))
)); ));
@@ -133,9 +138,11 @@ public class TradeGUI extends GUIMerchant {
} }
econ.withdrawPlayer(player, price); econ.withdrawPlayer(player, price);
villagerType.makeTrade(uuid); villagerType.makeTrade(uuid);
player.getInventory().addItem(new ItemStack(material, amount)); ItemStack itemStack = new ItemStack(material, amount);
randomizeMetaIfNeeded(material, itemStack);
player.getInventory().addItem(itemStack);
player.sendMiniMessage(Config.TRADED_ITEM, TagResolver.resolver( player.sendRichMessage(Config.TRADED_ITEM, TagResolver.resolver(
Placeholder.parsed("amount", String.valueOf(amount)), Placeholder.parsed("amount", String.valueOf(amount)),
Placeholder.parsed("item", Utilities.capitalize(material.name() Placeholder.parsed("item", Utilities.capitalize(material.name()
.toLowerCase().replaceAll("_", " "))), .toLowerCase().replaceAll("_", " "))),
@@ -149,6 +156,25 @@ public class TradeGUI extends GUIMerchant {
trade(villagerType, player, material, amount, price); trade(villagerType, player, material, amount, price);
} }
private void randomizeMetaIfNeeded(Material material, ItemStack itemStack) {
if (material.equals(Material.AXOLOTL_BUCKET)) {
AxolotlBucketMeta axolotlBucketMeta = (AxolotlBucketMeta) itemStack.getItemMeta();
int value = new Random().nextInt(0, Axolotl.Variant.values().length - 1);
axolotlBucketMeta.setVariant(Axolotl.Variant.values()[value]);
itemStack.setItemMeta(axolotlBucketMeta);
} else if (material.equals(Material.TROPICAL_FISH_BUCKET)) {
TropicalFishBucketMeta tropicalFishBucketMeta = (TropicalFishBucketMeta) itemStack.getItemMeta();
Random random = new Random();
int bodyColor = random.nextInt(0, DyeColor.values().length - 1);
int pattern = random.nextInt(0, TropicalFish.Pattern.values().length - 1);
int patternColor = random.nextInt(0, DyeColor.values().length - 1);
tropicalFishBucketMeta.setBodyColor(DyeColor.values()[bodyColor]);
tropicalFishBucketMeta.setPattern(TropicalFish.Pattern.values()[pattern]);
tropicalFishBucketMeta.setPatternColor(DyeColor.values()[patternColor]);
itemStack.setItemMeta(tropicalFishBucketMeta);
}
}
private ItemStack getPriceItem(double price) { private ItemStack getPriceItem(double price) {
if (price < 0) return nameItem(new ItemStack(Material.BARRIER), -1); if (price < 0) return nameItem(new ItemStack(Material.BARRIER), -1);
else if (price <= 10) return nameItem(new ItemStack(Material.IRON_INGOT), price); else if (price <= 10) return nameItem(new ItemStack(Material.IRON_INGOT), price);
@@ -45,17 +45,17 @@ public class CommandManager implements CommandExecutor, TabExecutor {
@Override @Override
public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String cmd, @NotNull String[] args) { public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String cmd, @NotNull String[] args) {
if (args.length == 0) { if (args.length == 0) {
commandSender.sendMiniMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", subCommands.stream() commandSender.sendRichMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", subCommands.stream()
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission())) .filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getHelpMessage) .map(SubCommand::getHelpMessage)
.collect(Collectors.joining("\n"))), null); .collect(Collectors.joining("\n"))));
return true; return true;
} }
SubCommand subCommand = getSubCommand(args[0]); SubCommand subCommand = getSubCommand(args[0]);
if (!commandSender.hasPermission(subCommand.getPermission())) { if (!commandSender.hasPermission(subCommand.getPermission())) {
commandSender.sendMiniMessage(Config.NO_PERMISSION, null); commandSender.sendRichMessage(Config.NO_PERMISSION);
return true; return true;
} }
@@ -26,21 +26,21 @@ public class CommandBuy extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
if (!(commandSender instanceof Player player)) { if (!(commandSender instanceof Player player)) {
commandSender.sendMiniMessage(Config.NO_CONSOLE, null); commandSender.sendRichMessage(Config.NO_CONSOLE);
return true; return true;
} }
if (args.length == 1) { if (args.length == 1) {
//TODO open gui //TODO open gui
player.sendMiniMessage(getHelpMessage(), null); //TODO remove later player.sendRichMessage(getHelpMessage()); //TODO remove later
return true; return true;
} }
if (args.length != 2) { if (args.length != 2) {
player.sendMiniMessage(getHelpMessage(), null); player.sendRichMessage(getHelpMessage());
return true; return true;
} }
EconUser user = EconUser.getUser(player.getUniqueId()); EconUser user = EconUser.getUser(player.getUniqueId());
if (user == null) { if (user == null) {
player.sendMiniMessage(Config.LOADING_ECON_DATA, null); player.sendRichMessage(Config.LOADING_ECON_DATA);
return true; return true;
} }
Material item = Material.valueOf(args[1].toUpperCase()); Material item = Material.valueOf(args[1].toUpperCase());
@@ -50,7 +50,7 @@ public class CommandBuy extends SubCommand {
.anyMatch(material -> material.equals(item))) .anyMatch(material -> material.equals(item)))
.findFirst(); .findFirst();
if (optionalVillagerType.isEmpty()) { if (optionalVillagerType.isEmpty()) {
player.sendMiniMessage(Config.NO_BUY_AT_SPAWN, TagResolver.resolver(Placeholder.unparsed("material", item.name()))); player.sendRichMessage(Config.NO_BUY_AT_SPAWN, TagResolver.resolver(Placeholder.unparsed("material", item.name())));
return true; return true;
} }
VillagerType villagerType = optionalVillagerType.get(); VillagerType villagerType = optionalVillagerType.get();
@@ -61,7 +61,7 @@ public class CommandBuy extends SubCommand {
} }
Integer curPoints = user.getPointsMap().getOrDefault(villagerType.getName(), 0); Integer curPoints = user.getPointsMap().getOrDefault(villagerType.getName(), 0);
double cost = price.calculatePriceThing(curPoints, price.getPoints(), true, price.getPoints()); double cost = price.calculatePriceThing(curPoints, price.getPoints(), true, price.getPoints());
player.sendMiniMessage(Config.BUY_ITEM_MESSAGE, TagResolver.resolver( player.sendRichMessage(Config.BUY_ITEM_MESSAGE, TagResolver.resolver(
Placeholder.unparsed("material", item.name()), Placeholder.unparsed("material", item.name()),
Placeholder.unparsed("price", String.valueOf(cost)), Placeholder.unparsed("price", String.valueOf(cost)),
Placeholder.unparsed("points", String.valueOf(price.getPoints())), Placeholder.unparsed("points", String.valueOf(price.getPoints())),
@@ -3,6 +3,7 @@ package com.alttd.commands.subcommands;
import com.alttd.commands.SubCommand; import com.alttd.commands.SubCommand;
import com.alttd.config.Config; import com.alttd.config.Config;
import com.alttd.config.VillagerConfig; import com.alttd.config.VillagerConfig;
import com.alttd.mappers.VillagerTypeMapper;
import com.alttd.objects.LoadedVillagers; import com.alttd.objects.LoadedVillagers;
import com.alttd.objects.VillagerType; import com.alttd.objects.VillagerType;
import com.alttd.objects.VillagerTypeManager; import com.alttd.objects.VillagerTypeManager;
@@ -19,40 +20,39 @@ import org.bukkit.entity.Villager;
import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
public class CommandCreateVillager extends SubCommand { public class CommandCreateVillager extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
if (args.length != 9) { if (args.length != 9) {
commandSender.sendMiniMessage(getHelpMessage(), null); commandSender.sendRichMessage(getHelpMessage());
return true; return true;
} }
Optional<VillagerType> first = VillagerTypeManager.getVillagerTypes().stream().filter(villagerType -> villagerType.getName().equalsIgnoreCase(args[1])).findFirst(); Optional<VillagerType> first = VillagerTypeManager.getVillagerType(args[1]);
if (first.isEmpty()) { if (first.isEmpty()) {
commandSender.sendMiniMessage(getHelpMessage(), null); commandSender.sendRichMessage(getHelpMessage());
return true; return true;
} }
VillagerType villagerType = first.get(); VillagerType villagerType = first.get();
Villager.Type type = Villager.Type.valueOf(args[2].toUpperCase()); Optional<Villager.Type> optionalVillagerType = VillagerTypeMapper.map(args[2]);
if (type == null) { //TODO test if this might need a try catch? if (optionalVillagerType.isEmpty()) {
commandSender.sendMiniMessage(getHelpMessage(), null); commandSender.sendRichMessage(getHelpMessage());
return true; return true;
} }
World world = Bukkit.getServer().getWorld(args[8]); World world = Bukkit.getServer().getWorld(args[8]);
if (world == null) { if (world == null) {
commandSender.sendMiniMessage(getHelpMessage(), null); commandSender.sendRichMessage(getHelpMessage());
return true; return true;
} }
Location location = new Location(world, Double.parseDouble(args[3]),Double.parseDouble(args[4]),Double.parseDouble(args[5]), Float.parseFloat(args[6]), Float.parseFloat(args[7])); Location location = new Location(world, Double.parseDouble(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Float.parseFloat(args[6]), Float.parseFloat(args[7]));
Villager villager = (Villager) world.spawnEntity(location, EntityType.VILLAGER, CreatureSpawnEvent.SpawnReason.CUSTOM); Villager villager = (Villager) world.spawnEntity(location, EntityType.VILLAGER, CreatureSpawnEvent.SpawnReason.CUSTOM);
villager.setPersistent(true); villager.setPersistent(true);
villager.setInvulnerable(true); villager.setInvulnerable(true);
villager.setVillagerType(type); villager.setVillagerType(optionalVillagerType.get());
villager.setProfession(villagerType.getProfession()); villager.setProfession(villagerType.getProfession());
villager.setRemoveWhenFarAway(false); villager.setRemoveWhenFarAway(false);
villager.setCollidable(false); villager.setCollidable(false);
@@ -80,8 +80,10 @@ public class CommandCreateVillager extends SubCommand {
switch (args.length) { switch (args.length) {
case 2 -> res.addAll(VillagerTypeManager.getVillagerTypes().stream() case 2 -> res.addAll(VillagerTypeManager.getVillagerTypes().stream()
.map(VillagerType::getName) .map(VillagerType::getName)
.collect(Collectors.toList())); .toList());
case 3 -> res.addAll(Arrays.stream(Villager.Type.values()).map(Enum::name).collect(Collectors.toList())); case 3 -> res.addAll(Arrays.stream(Villager.Type.values())
.map(something -> something.name())
.toList());
case 4 -> { case 4 -> {
if (commandSender instanceof Player player) { if (commandSender instanceof Player player) {
res.add(String.valueOf(Utilities.round(player.getLocation().getX(), 2))); res.add(String.valueOf(Utilities.round(player.getLocation().getX(), 2)));
@@ -20,11 +20,11 @@ public class CommandHelp extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
commandSender.sendMiniMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", commandManager commandSender.sendRichMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", commandManager
.getSubCommands().stream() .getSubCommands().stream()
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission())) .filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getHelpMessage) .map(SubCommand::getHelpMessage)
.collect(Collectors.joining("\n"))), null); .collect(Collectors.joining("\n"))));
return true; return true;
} }
@@ -9,6 +9,7 @@ import com.alttd.objects.VillagerTypeManager;
import com.alttd.util.Logger; import com.alttd.util.Logger;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
@@ -17,6 +18,7 @@ import org.bukkit.entity.Player;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -27,12 +29,12 @@ public class CommandPoints extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
if (!(commandSender instanceof Player player)) { if (!(commandSender instanceof Player player)) {
commandSender.sendMiniMessage(Config.NO_CONSOLE, null); commandSender.sendRichMessage(Config.NO_CONSOLE);
return true; return true;
} }
EconUser user = EconUser.getUser(player.getUniqueId()); EconUser user = EconUser.getUser(player.getUniqueId());
if (user == null) { if (user == null) {
player.sendMiniMessage(Config.LOADING_ECON_DATA, null); player.sendRichMessage(Config.LOADING_ECON_DATA);
return true; return true;
} }
var ref = new Object() { var ref = new Object() {
@@ -45,20 +47,18 @@ public class CommandPoints extends SubCommand {
Object2ObjectOpenHashMap<String, Integer> pointsMap = user.getPointsMap(); Object2ObjectOpenHashMap<String, Integer> pointsMap = user.getPointsMap();
pointsMap.keySet().forEach(key -> { pointsMap.keySet().forEach(key -> {
VillagerType villagerType = VillagerTypeManager.getVillagerType(key); Optional<VillagerType> optionalVillagerType = VillagerTypeManager.getVillagerType(key);
if (villagerType == null) { if (optionalVillagerType.isEmpty()) {
Logger.warning("Player % has unused villager type % in their point list.", player.getName(), key); Logger.warning("Player % has unused villager type % in their point list.", player.getName(), key);
return; return;
} }
VillagerType villagerType = optionalVillagerType.get();
int currentPoints = pointsMap.getOrDefault(key, 0); int currentPoints = pointsMap.getOrDefault(key, 0);
if (currentPoints == 0) return; if (currentPoints == 0) {
return;
}
allPointsAreZero.set(false); allPointsAreZero.set(false);
ref.message = ref.message.append(miniMessage.deserialize("\n", TagResolver.resolver())); ref.message = ref.message.append(getPointContentComponent(villagerType, currentPoints));
ref.message = ref.message.append(miniMessage.deserialize(Config.POINTS_CONTENT, TagResolver.resolver(
Placeholder.unparsed("villager_type", VillagerTypeManager.getVillagerType(key).getDisplayName()),
Placeholder.unparsed("points", String.valueOf(currentPoints)),
Placeholder.unparsed("buy_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, true))),
Placeholder.unparsed("sell_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, false))))));
}); });
if (allPointsAreZero.get()) { if (allPointsAreZero.get()) {
ref.message = miniMessage.deserialize(Config.NO_VILLAGER_POINTS); ref.message = miniMessage.deserialize(Config.NO_VILLAGER_POINTS);
@@ -70,36 +70,41 @@ public class CommandPoints extends SubCommand {
Object2ObjectOpenHashMap<String, Integer> pointsMap = user.getPointsMap(); Object2ObjectOpenHashMap<String, Integer> pointsMap = user.getPointsMap();
int currentPoints = pointsMap.getOrDefault(villagerType.getName(), 0); int currentPoints = pointsMap.getOrDefault(villagerType.getName(), 0);
ref.message = ref.message.append(miniMessage.deserialize("\n", TagResolver.resolver())); ref.message = ref.message.append(getPointContentComponent(villagerType, currentPoints));
ref.message = ref.message.append(miniMessage.deserialize(Config.POINTS_CONTENT, TagResolver.resolver(
Placeholder.unparsed("villager_type", villagerType.getDisplayName()),
Placeholder.unparsed("points", String.valueOf(currentPoints)),
Placeholder.unparsed("buy_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, true))),
Placeholder.unparsed("sell_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, false)))
)));
} }
} else { } else {
VillagerType villagerType = VillagerTypeManager.getVillagerType(args[1].toLowerCase()); Optional<VillagerType> optionalVillagerType = VillagerTypeManager.getVillagerType(args[1].toLowerCase());
Object2ObjectOpenHashMap<String, Integer> pointsMap = user.getPointsMap(); Object2ObjectOpenHashMap<String, Integer> pointsMap = user.getPointsMap();
if (villagerType == null) { if (optionalVillagerType.isEmpty()) {
player.sendMiniMessage(Config.NOT_A_VILLAGER, TagResolver.resolver(Placeholder.unparsed("villager_type", args[1]))); player.sendRichMessage(Config.NOT_A_VILLAGER, TagResolver.resolver(Placeholder.unparsed("villager_type", args[1])));
return true; return true;
} }
VillagerType villagerType = optionalVillagerType.get();
int currentPoints = pointsMap.getOrDefault(villagerType.getName(), 0); int currentPoints = pointsMap.getOrDefault(villagerType.getName(), 0);
ref.message = ref.message.append(miniMessage.deserialize(Config.POINTS_CONTENT, TagResolver.resolver( ref.message = ref.message.append(miniMessage.deserialize(Config.POINTS_CONTENT, TagResolver.resolver(
Placeholder.unparsed("villager_type", villagerType.getDisplayName()), Placeholder.unparsed("villager_type", villagerType.getDisplayName()),
Placeholder.unparsed("points", String.valueOf(currentPoints)), Placeholder.unparsed("points", String.valueOf(currentPoints)),
Placeholder.unparsed("buy_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, true))), Placeholder.unparsed("buy_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, true))),
Placeholder.unparsed("sell_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, false))) Placeholder.unparsed("sell_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, false)))
))); )));
} }
} else } else {
player.sendMiniMessage(getHelpMessage(), null); player.sendRichMessage(getHelpMessage());
}
player.sendMessage(ref.message); player.sendMessage((ComponentLike) ref.message);
return true; return true;
} }
private Component getPointContentComponent(VillagerType villagerType, int currentPoints) {
return miniMessage.deserialize("\n", TagResolver.resolver())
.append(miniMessage.deserialize(Config.POINTS_CONTENT, TagResolver.resolver(
Placeholder.unparsed("villager_type", villagerType.getDisplayName()),
Placeholder.unparsed("points", String.valueOf(currentPoints)),
Placeholder.unparsed("buy_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, true))),
Placeholder.unparsed("sell_multiplier", String.valueOf(Price.getCurrentMultiplier(currentPoints, false))))));
}
@Override @Override
public String getName() { public String getName() {
return "points"; return "points";
@@ -108,10 +113,11 @@ public class CommandPoints extends SubCommand {
@Override @Override
public List<String> getTabComplete(CommandSender commandSender, String[] args) { public List<String> getTabComplete(CommandSender commandSender, String[] args) {
List<String> res = new ArrayList<>(); List<String> res = new ArrayList<>();
if (args.length == 2) if (args.length == 2) {
res.addAll(VillagerTypeManager.getVillagerTypes().stream() res.addAll(VillagerTypeManager.getVillagerTypes().stream()
.map(VillagerType::getName) .map(VillagerType::getName)
.collect(Collectors.toList())); .collect(Collectors.toList()));
}
res.add("all"); res.add("all");
return res; return res;
} }
@@ -16,7 +16,7 @@ public class CommandReload extends SubCommand {
Config.reload(); Config.reload();
VillagerConfig.reload(); VillagerConfig.reload();
WorthConfig.reload(); WorthConfig.reload();
commandSender.sendMiniMessage("<green>Reloaded VillagerShopUI config.</green>", null); commandSender.sendRichMessage("<green>Reloaded VillagerShopUI config.</green>");
return true; return true;
} }
@@ -20,7 +20,7 @@ public class CommandRemoveVillager extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
if (!(commandSender instanceof Player player)) { if (!(commandSender instanceof Player player)) {
commandSender.sendMiniMessage(Config.NO_CONSOLE, null); commandSender.sendRichMessage(Config.NO_CONSOLE);
return true; return true;
} }
@@ -33,7 +33,7 @@ public class CommandRemoveVillager extends SubCommand {
LoadedVillagers.removeLoadedVillager(uuid); LoadedVillagers.removeLoadedVillager(uuid);
VillagerConfig.removeVillager(uuid); VillagerConfig.removeVillager(uuid);
entity.remove(); entity.remove();
player.sendMiniMessage(Config.REMOVED_VILLAGER, TagResolver.resolver( player.sendRichMessage(Config.REMOVED_VILLAGER, TagResolver.resolver(
Placeholder.unparsed("uuid", uuid.toString()))); Placeholder.unparsed("uuid", uuid.toString())));
} }
return true; return true;
@@ -26,21 +26,21 @@ public class CommandSell extends SubCommand {
@Override @Override
public boolean onCommand(CommandSender commandSender, String[] args) { public boolean onCommand(CommandSender commandSender, String[] args) {
if (!(commandSender instanceof Player player)) { if (!(commandSender instanceof Player player)) {
commandSender.sendMiniMessage(Config.NO_CONSOLE, null); commandSender.sendRichMessage(Config.NO_CONSOLE);
return true; return true;
} }
if (args.length == 1) { if (args.length == 1) {
//TODO open gui //TODO open gui
player.sendMiniMessage(getHelpMessage(), null); //TODO remove later player.sendRichMessage(getHelpMessage()); //TODO remove later
return true; return true;
} }
if (args.length != 2) { if (args.length != 2) {
player.sendMiniMessage(getHelpMessage(), null); player.sendRichMessage(getHelpMessage());
return true; return true;
} }
EconUser user = EconUser.getUser(player.getUniqueId()); EconUser user = EconUser.getUser(player.getUniqueId());
if (user == null) { if (user == null) {
player.sendMiniMessage(Config.LOADING_ECON_DATA, null); player.sendRichMessage(Config.LOADING_ECON_DATA);
return true; return true;
} }
Material item = Material.valueOf(args[1].toUpperCase()); Material item = Material.valueOf(args[1].toUpperCase());
@@ -50,7 +50,7 @@ public class CommandSell extends SubCommand {
.anyMatch(material -> material.equals(item))) .anyMatch(material -> material.equals(item)))
.findFirst(); .findFirst();
if (optionalVillagerType.isEmpty()) { if (optionalVillagerType.isEmpty()) {
player.sendMiniMessage(Config.NO_SELL_AT_SPAWN, TagResolver.resolver(Placeholder.unparsed("material", item.name()))); player.sendRichMessage(Config.NO_SELL_AT_SPAWN, TagResolver.resolver(Placeholder.unparsed("material", item.name())));
return true; return true;
} }
VillagerType villagerType = optionalVillagerType.get(); VillagerType villagerType = optionalVillagerType.get();
@@ -61,7 +61,7 @@ public class CommandSell extends SubCommand {
} }
Integer curPoints = user.getPointsMap().getOrDefault(villagerType.getName(), 0); Integer curPoints = user.getPointsMap().getOrDefault(villagerType.getName(), 0);
double cost = price.calculatePriceThing(curPoints, price.getPoints(), false, price.getPoints()); double cost = price.calculatePriceThing(curPoints, price.getPoints(), false, price.getPoints());
player.sendMiniMessage(Config.SELL_ITEM_MESSAGE, TagResolver.resolver( player.sendRichMessage(Config.SELL_ITEM_MESSAGE, TagResolver.resolver(
Placeholder.unparsed("material", item.name()), Placeholder.unparsed("material", item.name()),
Placeholder.unparsed("price", String.valueOf(cost)), Placeholder.unparsed("price", String.valueOf(cost)),
Placeholder.unparsed("points", String.valueOf(price.getPoints())), Placeholder.unparsed("points", String.valueOf(price.getPoints())),
+6 -1
View File
@@ -18,7 +18,7 @@ public final class Config extends AbstractConfig {
static Config config; static Config config;
static int version; static int version;
public Config() { public Config() {
super(new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "VillagerShopUI"), "config.yml"); super(new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "VillagerShopUI"), "config.yml");
} }
public static void reload() { public static void reload() {
@@ -105,11 +105,15 @@ public final class Config extends AbstractConfig {
"<gold>Price: <dark_aqua><price></dark_aqua></gold>", "<gold>Price: <dark_aqua><price></dark_aqua></gold>",
"<gold>Points: <dark_aqua><points></dark_aqua></gold>"); "<gold>Points: <dark_aqua><points></dark_aqua></gold>");
public static List<String> TRANSACTION_ITEM_DESCRIPTION_NO_POINTS = List.of(
"<gold>Amount: <dark_aqua><amount></dark_aqua></gold>",
"<gold>Price: <dark_aqua><price></dark_aqua></gold>");
private static void guiText() { private static void guiText() {
VILLAGER_NAME = config.getString("gui-text.villager-name", VILLAGER_NAME); VILLAGER_NAME = config.getString("gui-text.villager-name", VILLAGER_NAME);
CONFIRM_BUTTON = config.getString("gui-text.confirm-button", CONFIRM_BUTTON); CONFIRM_BUTTON = config.getString("gui-text.confirm-button", CONFIRM_BUTTON);
TRANSACTION_ITEM_NAME = config.getString("gui-text.transaction-item-name", TRANSACTION_ITEM_NAME); TRANSACTION_ITEM_NAME = config.getString("gui-text.transaction-item-name", TRANSACTION_ITEM_NAME);
TRANSACTION_ITEM_DESCRIPTION = config.getStringList("gui-text.transaction-item-description", TRANSACTION_ITEM_DESCRIPTION); TRANSACTION_ITEM_DESCRIPTION = config.getStringList("gui-text.transaction-item-description", TRANSACTION_ITEM_DESCRIPTION);
TRANSACTION_ITEM_DESCRIPTION_NO_POINTS = config.getStringList("gui-text.transaction-item-description-no-points", TRANSACTION_ITEM_DESCRIPTION_NO_POINTS);
} }
public static String NOT_ENOUGH_MONEY = "<red>You only have $<money>, you need at least $<price> for this purchase.</red>"; public static String NOT_ENOUGH_MONEY = "<red>You only have $<money>, you need at least $<price> for this purchase.</red>";
@@ -199,6 +203,7 @@ public final class Config extends AbstractConfig {
); );
} }
}); });
VillagerMessagesConfig.reload();
} }
private static TreeSet<ItemStack> loadProducts(ConfigurationSection productsSection) { private static TreeSet<ItemStack> loadProducts(ConfigurationSection productsSection) {
@@ -4,6 +4,8 @@ import com.alttd.objects.LoadedVillagers;
import com.alttd.objects.VillagerType; import com.alttd.objects.VillagerType;
import com.alttd.objects.VillagerTypeManager; import com.alttd.objects.VillagerTypeManager;
import com.alttd.util.Logger; import com.alttd.util.Logger;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
public class VillagerConfig extends AbstractConfig { public class VillagerConfig extends AbstractConfig {
@@ -27,11 +29,10 @@ public class VillagerConfig extends AbstractConfig {
private static void loadVillagers() { private static void loadVillagers() {
LoadedVillagers.clearLoadedVillagers(); LoadedVillagers.clearLoadedVillagers();
config.getConfigurationSection("").getKeys(false).forEach(key -> { config.getConfigurationSection("").getKeys(false).forEach(key -> {
VillagerType villagerType = VillagerTypeManager.getVillagerType(config.getString(key, "")); Optional<VillagerType> optionalVillagerType = VillagerTypeManager.getVillagerType(config.getString(key, ""));
if (villagerType != null) optionalVillagerType
LoadedVillagers.addLoadedVillager(UUID.fromString(key), villagerType); .ifPresentOrElse(present -> LoadedVillagers.addLoadedVillager(UUID.fromString(key), present),
else () -> Logger.warning("Invalid config entry %.", key));
Logger.warning("Invalid config entry %.", key);
}); });
} }
@@ -0,0 +1,53 @@
package com.alttd.config;
import com.alttd.objects.VillagerType;
import com.alttd.objects.VillagerTypeManager;
import com.alttd.util.Logger;
import org.bukkit.configuration.ConfigurationSection;
import java.io.File;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public class VillagerMessagesConfig extends AbstractConfig {
static VillagerMessagesConfig config;
static int version;
protected VillagerMessagesConfig() {
super(new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "VillagerShopUI"), "villager-messages.yml");
}
protected static void reload() {
config = new VillagerMessagesConfig();
version = config.getInt("config-version", 1);
config.set("config-version", 1);
config.readConfig(VillagerMessagesConfig.class, null);
}
private static void loadVillagerMessages() {
Logger.info("Reloading VillagerMessages config...");
ConfigurationSection configurationSection = config.getConfigurationSection("messages");
if (configurationSection == null) {
Logger.warning("No villager messages found in config.");
config.getStringList("messages.example-tag", List.of("This is an example"));
return;
}
Set<String> keys = configurationSection.getKeys(false);
if (keys.isEmpty()) {
Logger.warning("No villager types found in config.");
}
keys.forEach(key -> {
Optional<VillagerType> optionalVillagerType = VillagerTypeManager.getVillagerType(key);
if (optionalVillagerType.isEmpty()) {
Logger.info("Unknown villager type: " + key);
return;
}
optionalVillagerType.get().setMessages(configurationSection.getStringList(key));
});
}
}
@@ -17,7 +17,7 @@ public class WorthConfig extends AbstractConfig {
static int version; static int version;
public WorthConfig() { public WorthConfig() {
super(new File(System.getProperty("user.home") + File.separator + "share" + File.separator + "configs" + File.separator + "VillagerShopUI"), "worth.yml"); super(new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "VillagerShopUI"), "worth.yml");
} }
public static void reload() { public static void reload() {
@@ -54,9 +54,8 @@ public class WorthConfig extends AbstractConfig {
} }
Material material; Material material;
try { material = Material.getMaterial(key);
material = Material.getMaterial(key); if (material == null) {
} catch (Exception e) {
Logger.warning("Invalid material % in trade worth", key); Logger.warning("Invalid material % in trade worth", key);
continue; continue;
} }
@@ -81,9 +80,8 @@ public class WorthConfig extends AbstractConfig {
} }
Material material; Material material;
try { material = Material.getMaterial(key);
material = Material.getMaterial(key); if (material == null) {
} catch (Exception e) {
Logger.warning("Invalid material % in trade worth", key); Logger.warning("Invalid material % in trade worth", key);
continue; continue;
} }
@@ -5,7 +5,10 @@ import com.alttd.GUI.windows.TradeGUI;
import com.alttd.VillagerUI; import com.alttd.VillagerUI;
import com.alttd.config.Config; import com.alttd.config.Config;
import com.alttd.config.VillagerConfig; import com.alttd.config.VillagerConfig;
import com.alttd.cosmos.event.player.PlayerInteractOnEntityEvent;
import com.alttd.objects.*; import com.alttd.objects.*;
import net.kyori.adventure.text.ComponentLike;
import org.bukkit.Sound;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Villager; import org.bukkit.entity.Villager;
@@ -33,12 +36,12 @@ public class VillagerEvents implements Listener {
Player player = event.getPlayer(); Player player = event.getPlayer();
event.setCancelled(true); event.setCancelled(true);
if (!player.hasPermission(loadedVillager.getPermission())) { if (!player.hasPermission(loadedVillager.getPermission())) {
player.sendMiniMessage(Config.NO_PERMISSION, null); //TODO more specific message? player.sendRichMessage(Config.NO_PERMISSION); //TODO more specific message?
return; return;
} }
EconUser user = EconUser.getUser(player.getUniqueId()); EconUser user = EconUser.getUser(player.getUniqueId());
if (user == null) { if (user == null) {
player.sendMiniMessage(Config.LOADING_ECON_DATA, null); player.sendRichMessage(Config.LOADING_ECON_DATA);
return; return;
} }
new BukkitRunnable() { new BukkitRunnable() {
@@ -65,6 +68,27 @@ public class VillagerEvents implements Listener {
}.runTaskAsynchronously(VillagerUI.getInstance()); }.runTaskAsynchronously(VillagerUI.getInstance());
} }
@EventHandler
public void onPlayerInteractOnEntity(PlayerInteractOnEntityEvent event) {
Player player = event.getPlayer();
if (!(event.getEntity() instanceof Villager villager)) {
return;
}
VillagerType loadedVillager = LoadedVillagers.getLoadedVillager(villager.getUniqueId());
if (loadedVillager == null) {
return;
}
loadedVillager.getRandomMessage().ifPresent(component -> player.sendMessage((ComponentLike) component));
if (loadedVillager instanceof BlackMarketVillagerType) {
player.playSound(player.getLocation(), Sound.ENTITY_VILLAGER_HURT, 1.0F, 1.0F);
} else if (loadedVillager instanceof ShopVillagerType) {
player.playSound(player.getLocation(), Sound.ENTITY_VILLAGER_YES, 1.0F, 1.0F);
}
}
@EventHandler @EventHandler
public void onVillagerDeath(EntityDeathEvent event) { public void onVillagerDeath(EntityDeathEvent event) {
if (!event.getEntityType().equals(EntityType.VILLAGER)) if (!event.getEntityType().equals(EntityType.VILLAGER))
@@ -0,0 +1,20 @@
package com.alttd.mappers;
import org.bukkit.entity.Villager;
import java.util.Optional;
public class VillagerTypeMapper {
public static Optional<Villager.Type> map(String villagerType) {
return switch (villagerType.toUpperCase()) {
case "DESERT" -> Optional.of(Villager.Type.DESERT);
case "JUNGLE" -> Optional.of(Villager.Type.JUNGLE);
case "PLAINS" -> Optional.of(Villager.Type.PLAINS);
case "SAVANNA" -> Optional.of(Villager.Type.SAVANNA);
case "SNOW" -> Optional.of(Villager.Type.SNOW);
case "SWAMP" -> Optional.of(Villager.Type.SWAMP);
case "TAIGA" -> Optional.of(Villager.Type.TAIGA);
default -> Optional.empty();
};
}
}
@@ -1,5 +1,9 @@
package com.alttd.objects; package com.alttd.objects;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.entity.Villager; import org.bukkit.entity.Villager;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -15,14 +19,22 @@ public class BlackMarketVillagerType implements VillagerType {
private final int maxTradesPerReboot; private final int maxTradesPerReboot;
private final HashMap<UUID, Set<ItemStack>> playerTrades = new HashMap<>(); private final HashMap<UUID, Set<ItemStack>> playerTrades = new HashMap<>();
private final HashMap<UUID, Integer> playerTradeCount = new HashMap<>(); private final HashMap<UUID, Integer> playerTradeCount = new HashMap<>();
private final List<String> messages = new ArrayList<>();
private final Random random = new Random();
public BlackMarketVillagerType(String name, String displayName, String profession, int maxAvailableItems, int maxTradesPerReboot, Set<ItemStack> trading) { public BlackMarketVillagerType(String name, String displayName, String profession, int maxAvailableItems, int maxTradesPerReboot, Set<ItemStack> trading) {
this.name = name; this.name = name;
this.displayName = displayName; this.displayName = displayName;
this.profession = Villager.Profession.valueOf(profession.toUpperCase());
this.maxAvailableItems = maxAvailableItems; this.maxAvailableItems = maxAvailableItems;
this.maxTradesPerReboot = maxTradesPerReboot; this.maxTradesPerReboot = maxTradesPerReboot;
this.trading = trading; this.trading = trading;
this.profession = getProfession(profession.toLowerCase());
}
Villager.Profession getProfession(String professionName) {
NamespacedKey namespacedKey = NamespacedKey.minecraft(professionName);
return Registry.VILLAGER_PROFESSION.get(namespacedKey);
} }
private Set<ItemStack> getResizedCustomTradingSet() { private Set<ItemStack> getResizedCustomTradingSet() {
@@ -85,4 +97,25 @@ public class BlackMarketVillagerType implements VillagerType {
public String getPermission() { public String getPermission() {
return "villagerui.villager." + getName(); return "villagerui.villager." + getName();
} }
@Override
public Optional<Component> getRandomMessage() {
if (messages.isEmpty()) {
return Optional.empty();
}
int index = random.nextInt(messages.size());
String message = messages.get(index);
return Optional.of(MiniMessage.miniMessage().deserialize(message));
}
@Override
public void addMessage(String message) {
messages.add(message);
}
@Override
public void setMessages(List<String> messages) {
this.messages.clear();
this.messages.addAll(messages);
}
} }
@@ -132,7 +132,7 @@ public class EconUser {
public void notifyPlayer(UUID uuid, String villagerType) { public void notifyPlayer(UUID uuid, String villagerType) {
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if (player != null && player.isOnline()) if (player != null && player.isOnline())
player.sendMiniMessage(Config.NOTIFY_POINTS_RESET, Placeholder.unparsed("villager_type", villagerType)); player.sendRichMessage(Config.NOTIFY_POINTS_RESET, Placeholder.unparsed("villager_type", villagerType));
} }
public static void tryLoadUser(UUID uuid) { public static void tryLoadUser(UUID uuid) {
@@ -1,10 +1,13 @@
package com.alttd.objects; package com.alttd.objects;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.entity.Villager; import org.bukkit.entity.Villager;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.Set; import java.util.*;
import java.util.TreeSet;
public class ShopVillagerType implements VillagerType{ public class ShopVillagerType implements VillagerType{
private final String name; private final String name;
@@ -12,13 +15,21 @@ public class ShopVillagerType implements VillagerType{
private final Set<ItemStack> buying; private final Set<ItemStack> buying;
private final Set<ItemStack> selling; private final Set<ItemStack> selling;
private final Villager.Profession profession; private final Villager.Profession profession;
private final List<String> messages = new ArrayList<>();
private final Random random = new Random();
public ShopVillagerType(String name, String displayName, TreeSet<ItemStack> buying, TreeSet<ItemStack> selling, String profession) { public ShopVillagerType(String name, String displayName, TreeSet<ItemStack> buying, TreeSet<ItemStack> selling, String profession) {
this.name = name; this.name = name;
this.displayName = displayName; this.displayName = displayName;
this.buying = buying; this.buying = buying;
this.selling = selling; this.selling = selling;
this.profession = Villager.Profession.valueOf(profession.toUpperCase()); this.profession = getProfession(profession.toLowerCase());
}
Villager.Profession getProfession(String professionName) {
NamespacedKey namespacedKey = NamespacedKey.minecraft(professionName);
return Registry.VILLAGER_PROFESSION.get(namespacedKey);
} }
public String getName() { public String getName() {
@@ -44,4 +55,22 @@ public class ShopVillagerType implements VillagerType{
public String getPermission() { public String getPermission() {
return "villagerui.villager." + getName(); return "villagerui.villager." + getName();
} }
public Optional<Component> getRandomMessage() {
if (messages.isEmpty()) {
return Optional.empty();
}
int index = random.nextInt(messages.size());
String message = messages.get(index);
return Optional.of(MiniMessage.miniMessage().deserialize(message));
}
public void addMessage(String message) {
messages.add(message);
}
public void setMessages(List<String> messages) {
this.messages.clear();
this.messages.addAll(messages);
}
} }
@@ -1,8 +1,11 @@
package com.alttd.objects; package com.alttd.objects;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Villager; import org.bukkit.entity.Villager;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
public interface VillagerType { public interface VillagerType {
@@ -18,4 +21,10 @@ public interface VillagerType {
Villager.Profession getProfession(); Villager.Profession getProfession();
String getPermission(); String getPermission();
Optional<Component> getRandomMessage();
void addMessage(String message);
void setMessages(List<String> messages);
} }
@@ -1,6 +1,7 @@
package com.alttd.objects; package com.alttd.objects;
import java.util.HashSet; import java.util.HashSet;
import java.util.Optional;
import java.util.Set; import java.util.Set;
public class VillagerTypeManager { public class VillagerTypeManager {
@@ -10,8 +11,8 @@ public class VillagerTypeManager {
return villagerTypes; return villagerTypes;
} }
public static VillagerType getVillagerType(String name) { public static Optional<VillagerType> getVillagerType(String name) {
return villagerTypes.stream().filter(villagerType -> villagerType.getName().equals(name)).findFirst().orElse(null); return villagerTypes.stream().filter(villagerType -> villagerType.getName().equals(name)).findFirst();
} }
public static void addVillagerType(VillagerType villagerType) { public static void addVillagerType(VillagerType villagerType) {